Fea*_*aro 4 java swing jcomponent layout-manager
我jScrollPane在表格上有一个按钮.该按钮为其添加了一个组件jScrollPane.我正在使用FlowLayout带有中心对齐的组件来安排组件jScrollPane.
第一个组件没有出现问题,并且完美对齐.当我再次按下按钮时,似乎没有任何事情发生.当我按照调试器时,它显示一切都像以前一样发生.
单击按钮时执行的代码:
jScrollPane.getViewport().add(new Component());
Run Code Online (Sandbox Code Playgroud)
这就是我在设置FlowLayout上Viewport的jScrollPane:
jScrollPane.getViewport().setLayout(new FlowLayout(FlowLayout.CENTER));
Run Code Online (Sandbox Code Playgroud)
您将重量级(AWT)组件与轻量级(Swing)组件混合使用,这是不可取的,因为它们不能很好地协同工作.
JScrollPane包含一个JViewPort可以添加子组件的视图,AKA视图.

(来自JavaDocs的图片)
所以调用jScrollPane.getViewport().setLayout(new FlowLayout(FlowLayout.CENTER));实际上是设置JViewPort布局管理器,这实际上是不可取的.
您应该做的是创建要添加到滚动窗格的组件,设置它的布局并将其所有子组件添加到它,然后将其添加到滚动窗格.如果需要,您可以在以后阶段向"视图"添加组件,但这取决于您...
// Declare "view" as a class variable...
view = new JPanel(); // FlowLayout is the default layout manager
// Add the components you need now to the "view"
JScrollPane scrollPane = new JScrollPane(view);
Run Code Online (Sandbox Code Playgroud)
现在,您可以根据需要向视图中添加新组件...
view.add(...);
Run Code Online (Sandbox Code Playgroud)
如果您不想维护引用view,可以通过调用来访问它,JViewport#getView这将返回由视图端口管理的组件.
JPanel view = (JPanel)scrollPane.getViewPort().getView();
Run Code Online (Sandbox Code Playgroud)
工作实例
这对我来说很好......
nb - view.validate()在我添加了一个新组件之后,我添加了我的代码,你可能没有这个代码......
public class TestScrollPane01 {
public static void main(String[] args) {
new TestScrollPane01();
}
public TestScrollPane01() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new MainPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MainPane extends JPanel {
private JScrollPane scrollPane;
private int count;
public MainPane() {
setLayout(new BorderLayout());
scrollPane = new JScrollPane(new JPanel());
((JPanel)scrollPane.getViewport().getView()).add(new JLabel("First"));
add(scrollPane);
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JPanel view = ((JPanel)scrollPane.getViewport().getView());
view.add(new JLabel("Added " + (++count)));
view.validate();
}
});
add(add, BorderLayout.SOUTH);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Run Code Online (Sandbox Code Playgroud)