我正在尝试编写一个基本的 GUI 应用程序:它只是一个带有文本框和几个按钮的可滚动窗口。我已经设置JFrame
和JScrollPane
如下:
public class MainFrame extends JFrame {
public MainFrame() {
this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.PAGE_AXIS));
JScrollPane scrollPane = new JScrollPane();
JPanel contentPanel = new JPanel(); contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.PAGE_AXIS));
contentPanel.setPreferredSize(new Dimension(600,1600));
scrollPane.setViewportView(contentPanel);
this.setContentPane(scrollPane);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.getViewport().add(new PCData());
scrollPane.getViewport().add(Box.createRigidArea(new Dimension(0,100)));
scrollPane.getViewport().add(new PCData());
this.validate();
this.setSize(625,800);
this.setVisible(true);
}
public static void main(String[] args) {new MainFrame();}
}
类PCData
如下:
public class PCData extends JPanel {
public PCData() {
this.setSize(new Dimension(600,300));
this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
this.add(new JTextField());
JPanel nameData = new JPanel();
nameData.setLayout(new BoxLayout(nameData, BoxLayout.LINE_AXIS));
nameData.add(new JTextField());
nameData.add(Box.createRigidArea(new Dimension(5, 0)));
nameData.add(new JTextField());
this.add(nameData);
}
}
然而,我最终只PCData
显示了两个区域中的一个,尽管首选大小。内容窗格不可滚动。但是,如果我删除三行:
//scrollPane.getViewport().add(new PCData());
//scrollPane.getViewport().add(Box.createRigidArea(new Dimension(0,100)));
//scrollPane.getViewport().add(new PCData());
再次变为可JScrollPane
滚动。为什么会发生这种情况,如何让两个PCData
面板都显示?(请注意:我正在寻找原因和方式,而不仅仅是如何。)