我正在尝试创建所谓的“15 游戏”,它就像一个有 16 个按钮的幻灯片拼图,其中 15 个按钮包含数字 1-15,还有一个空按钮。单击空按钮旁边的按钮将与单击的按钮和空按钮交换位置。但现在我正在尝试设置 gui,它是由 Swing、gridlayout 和 16 个按钮组成的。但是我无法让它工作,这是我的代码:
package game;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
public class TheGame{
public static void main(String[] args){
TheGame game = new TheGame();
}
public TheGame(){
JMenuBar menubar = new JMenuBar();
JFrame frame = new JFrame("15Game");
GridLayout grid = new GridLayout(4,4,3,3);
JPanel panel = new JPanel();
Cell cell1 = new Cell("1");
Cell cell2 = new Cell("2");
Cell cell3 = new Cell("3");
Cell cell4 = new Cell("4");
Cell cell5 = new Cell("5");
Cell cell6 = new Cell("6");
Cell cell7 = new Cell("7");
Cell cell8 = new Cell("8");
Cell cell9 = new Cell("9");
Cell cell10 = new Cell("10");
Cell cell11 = new Cell("11");
Cell cell12 = new Cell("12");
Cell cell13 = new Cell("13");
Cell cell14 = new Cell("14");
Cell cell15 = new Cell("15");
Cell cellEmpty = new Cell("");
panel.add(cell1);
panel.add(cell2);
panel.add(cell3);
panel.add(cell4);
panel.add(cell5);
panel.add(cell6);
panel.add(cell7);
panel.add(cell8);
panel.add(cell9);
panel.add(cell10);
panel.add(cell11);
panel.add(cell12);
panel.add(cell13);
panel.add(cell14);
panel.add(cell15);
panel.add(cellEmpty);
panel.setLayout(grid);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
这是单元格:
package game;
import javax.swing.JButton;
public class Cell extends JButton {
//Variables
public Cell(String s){
this.setText(s);
}
当我创建这个时,它只弹出一个小的空 GUI 窗口,根本没有按钮。为什么会这样,我做错了什么?
最佳答案
您需要将包含按钮的面板添加到框架
frame.add(panel);
关于java - 为什么网格布局中不显示按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22746403/