所以我正在做一项作业,但我似乎陷入了一个似乎无法克服的错误。本质上,当尝试创建 10x10 网格时,它不会出现,而其他所有内容(例如标题和菜单)都是在我运行应用程序时出现的。这是我迄今为止所做的重要部分
public class minesweeperGUI extends JFrame{
private JFrame gameGUI;
private JPanel board;
private JButton[][] boardButtons = new JButton [10][10];
public minesweeperGUI(){
gameGUI = new JFrame("Enhanced Minesweeper"); //Title of the Window
gameGUI.setVisible(true); //We want (true) to set it visible
gameGUI.setSize(400,550); //400 550
gameGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //This will close the frame when you press X. IMPORTANT
gameGUI.getContentPane().setBackground(Color.CYAN);
gameGUI.setLayout(null);
//Panel for minesweeper board
board = new JPanel();
GridLayout experimentLayout = new GridLayout(10, 10);
board.setLayout(experimentLayout);
board.setSize(400,550);
for(int x=0;x<boardButtons.length;x++){
for(int y=0;y<boardButtons[x].length;y++){
boardButtons[x][y] = new JButton();
board.add(boardButtons[x][y]);
}
}
gameGUI.add(board);
}
public static void main(String[] args) {
minesweeperGUI mainInterface = new minesweeperGUI();
}
}
任何类型的帮助将不胜感激:)
最佳答案
gameGUI.setVisible(true); //We want (true) to set it visible
- 是的,但它应该是
minesweeperGUI()
中的最后一个代码行,否则您添加JComponent
s 到已经可见的 Swing Gui(缺少自动刷新、重绘的通知程序)
minesweeperGUI mainInterface = new minesweeperGUI();
应包含在
invokeLater
中,更多 Oracle 线索Initial Thread
类名应该是
MinesweeperGUI
,搜索Java Namings Convention
gameGUI.setLayout(null); and board.setSize(400,550);
那里失踪了
setBounds
对于board.setSize(400,550);
(将JPanel
放置到JFrame
,因为JPanel
有零Dimension
)没有理由使用
null layout
,删除gameGUI.setLayout(null);
覆盖
getPreferredSize
对于private JPanel board;
删除代码行
gameGUI.setLayout(null);
和board.setSize(400,550);
添加代码行
pack()
之前setVisible(true)
,为JFrame
调整合适的尺寸(基于getPreferredSize
为private JPanel board;
)
关于java - JButton 的 2D 数组未出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26967230/