我正在尝试编写一个基本的 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
区域之一。内容 Pane 不可滚动。但是,如果我删除这三行:
//scrollPane.getViewport().add(new PCData());
//scrollPane.getViewport().add(Box.createRigidArea(new Dimension(0,100)));
//scrollPane.getViewport().add(new PCData());
JScrollPane
再次变得可滚动。为什么会发生这种情况?如何才能显示两个 PCData
面板? (请注意:我正在寻找为什么和如何,而不仅仅是如何。)
最佳答案
scrollPane.getViewport().add(new PCData());
scrollPane.getViewport().add(Box.createRigidArea(new Dimension(0,100)));
scrollPane.getViewport().add(new PCData());
只能将单个组件添加到视口(viewport)。
所以你需要创建一个面板。将 3 个组件添加到面板中。然后将面板添加到视口(viewport)。
关于java - 我的第二个 JPanel 去哪里了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16706210/