【发布时间】:2014-03-30 16:18:29
【问题描述】:
我正在尝试创建所谓的“15 游戏”,它就像一个带有 16 个按钮的幻灯片拼图,其中 15 个按钮的数字为 1-15 和一个空按钮。单击空按钮旁边的按钮将与单击的按钮和空按钮切换位置。但是现在我正在尝试设置由 Swing、gridlayout 和 16 个按钮组成的 gui。但是我不能让它工作,这是我的代码:
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 窗口,根本没有按钮。为什么会这样,我做错了什么?
【问题讨论】:
-
在您开始添加按钮之前致电
panel.setLayout()。当您添加按钮时,布局的作用是告诉面板按钮的位置。如果在按钮之后添加布局,则效果不佳。您还想将面板添加到框架中,否则也不会有什么好处。
标签: java swing jframe jbutton grid-layout