【发布时间】:2018-10-10 23:24:11
【问题描述】:
该类扩展了 JPanel,
public void createDisplay(){
frame = new JFrame();
frame.setTitle(title);
frame.setSize(new Dimension(width, height));
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setPreferredSize(new Dimension(width, height));
this.setMaximumSize(new Dimension(width, height));
this.setMinimumSize(new Dimension(width, height));
this.setLayout(null); //have tried default and BorderLayout
this.setSize(new Dimension(width, height));
this.setBounds(0, 0, width, height);
//basically trying everything
frame.add(this);
frame.pack();
}
在启动时,此代码运行良好,JPanel 完全覆盖了父框架的大小
但是我的程序后来尝试将新的 JPanel 添加到类的扩展 JPanel 中:
public void gameOverWindow(){ ;
JPanel panel = new JPanel(new BorderLayout());
panel.setPreferredSize(new Dimension(200, 100));
JLabel label = new JLabel("Game Over");
label.setPreferredSize(new Dimension(40, 15));
//trying setPosition also doesn't work with BorderLayout or FlowLayout
JButton button_01 = new JButton("new");
button_01.setPreferredSize(new Dimension(100, 10));
JButton button_02 = new JButton("exit");
button_02.setPreferredSize(new Dimension(100, 10));
panel.add(label, BorderLayout.NORTH);
panel.add(button_01, BorderLayout.WEST);
panel.add(button_02, BorderLayout.EAST);
this.add(panel);
this.revalidate();
}
这个新的 JPanel 以正确的 BorderLayout 格式显示内容,但是 JPanel 本身将保留在扩展 JPanel 的顶部中心,我知道这是因为默认布局设置为 FlowLayout,但是将其设置为 BorderLayout 会只是使面板占据整个屏幕。将 Layout 设置为 null 会完全破坏框架,并且除了 Frame 的 Minimize 和 Close 按钮之外什么都没有出现。尝试设置此 JPanel 的位置或边界也不适用于任何布局。我已经在网上阅读了很多关于此的其他帖子,但它们似乎都不同并且变得令人困惑,我如何控制我的新 JPanel 的位置?
【问题讨论】:
-
* 但是 JPanel 本身将保持在扩展 JPanel 的顶部中心"* - 这就是
panel.add(label, BorderLayout.NORTH);将要做的。"我如何控制我的新 JPanel 的位置?" - 使用适当的布局。避免使用setXxxSize、setSize、setBounds、setLocation -
您不会拘泥于使用单个布局管理器,您可以使用多个容器,将它们与不同的布局管理器组合在一起
-
@MadProgrammer 该面板的标签和按钮布置得很好,它是我希望能够移动的实际 JPanel 面板位置,尝试 this.add(panel, BorderLayout.center) 不会改变它
-
那么,您将面板添加到面板中对吗?
-
@correct,该面板被添加到 JFrame