您正在混合重量(AWT)组件和轻量(Swing)
组件,这是不可取的,因为它们往往不能很好地配合使用。
JScrollPane包含一个
JViewPort,您可以在上面添加一个子组件,也
就是视图。
因此,该呼叫
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);
Now you can add new components to the view as you need…
view.add(...);
如果您不想维护对的引用view,则可以通过调用进行访问,
JViewport#getView这将返回由
查看端口管理的组件。
JPanel view = (JPanel)scrollPane.getViewPort().getView();
工作实例
这对我来说很好
nb- view.validate()在
添加新组件之后,我将代码添加到了您可能没有的代码中……
public class TestScrollPane01 {
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); } }}


