基本上我想做的就是为熄灯游戏绘制两行按钮(作业),但我不知道如何使两个面板都显示出来。我以前几乎没有图形,而且我真的不明白我在做什么。 面板本身可以工作,但它只显示我第二个添加的面板(我假设它覆盖了前一个面板)
public static void main(String[] args) {
String nButtonsString = JOptionPane.showInputDialog("How many buttons would you like?");
int nButtons = Integer.parseInt(nButtonsString);
JFrame myFrame = new JFrame();
myFrame.setTitle("Linear Lights Out Game.");
myFrame.setSize(FRAME_SIZE);
JPanel control_buttons = new Linear_Controls();
myFrame.add(control_buttons);
JPanel lights = new LinearLightsPanel(nButtons);
myFrame.add(lights);
myFrame.pack();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
最佳答案
myFrame.add(control_buttons);
myFrame.add(lights);
默认情况下,JFrame 使用 BorderLayout。此外,默认情况下,组件会添加到 BorderLayout 的 CENTER
中。但是,CENTER 只能包含单个组件,因此仅显示最后添加的组件。尝试:
myFrame.add(control_buttons, BorderLayout.NORTH);
现在两个组件应该显示出来。
阅读 Swing 教程中关于 Using Layout Managers 的部分了解更多信息和示例。另请查看 Trail/Table of Contents
链接,了解有关 Swing 基本用法的其他有用主题。
关于java swing 多个 jpanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23016525/