java - JButton 的 2D 数组未出现

标签 java arrays swing jframe jbutton

所以我正在做一项作业,但我似乎陷入了一个似乎无法克服的错误。本质上,当尝试创建 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);

    1. 覆盖 getPreferredSize对于 private JPanel board;

    2. 删除代码行 gameGUI.setLayout(null);board.setSize(400,550);

    3. 添加代码行pack()之前setVisible(true) ,为 JFrame 调整合适的尺寸(基于getPreferredSizeprivate JPanel board;)

关于java - JButton 的 2D 数组未出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26967230/

相关文章:

java - Play 2.2.1插件未加载

python - 在 matlab 和 python 中创建迭代数组

javascript - 数组中的逻辑或

c - strstr 带有常规 char 数组,而不是字符串

java - ExecutorService 与 Swing 定时器

java - 处理java找不到符号错误

java - java的image magick问题

java - 未触发 MAC OS X Java Swing Mouse Released 事件

java - 将焦点放在 JLayeredPane 中的 JPanel

java - 完成的 Java 项目,现在创建 jar 或 .exe 文件(带数据库)