首页 文章

使用gridlayout添加按钮

提问于
浏览
4

我正在尝试制作一个由9x9 JButton制作的简单的tic tac toe board . 我使用了二维数组和一个gridlayout,但结果是什么,没有任何按钮的框架 . 我做错了什么?

import java.awt.GridLayout;
import javax.swing.*;


public class Main extends JFrame
{
    private JPanel panel;
    private JButton[][]buttons;
    private final int SIZE = 9;
    private GridLayout experimentLayout;
    public Main()
    {
        super("Tic Tac Toe");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500,500);
        setResizable(false);
        setLocationRelativeTo(null);

        experimentLayout =  new GridLayout(SIZE,SIZE);

        panel = new JPanel();
        panel.setLayout(experimentLayout);


        buttons = new JButton[SIZE][SIZE];
        addButtons();


        add(panel);
        setVisible(true);
    }
    public void addButtons()
    {
        for(int k=0;k<SIZE;k++)
            for(int j=0;j<SIZE;j++)
            {
                buttons[k][j] = new JButton(k+1+", "+(j+1));
                experimentLayout.addLayoutComponent("testName", buttons[k][j]);
            }

    }


    public static void main(String[] args) 
    {
        new Main();

    }

}

addButton方法是将按钮添加到数组中,然后直接添加到面板中 .

2 回答

  • 4

    您需要将按钮添加到 JPanel

    public void addButtons(JPanel panel) {
       for (int k = 0; k < SIZE; k++) {
          for (int j = 0; j < SIZE; j++) {
             buttons[k][j] = new JButton(k + 1 + ", " + (j + 1));
             panel.add(buttons[k][j]);
          }
       }
    }
    
  • 8
    // add buttons to the panel INSTEAD of the layout
    // experimentLayout.addLayoutComponent("testName", buttons[k][j]);
    panel.add(buttons[k][j]);
    

    进一步建议:

    • 不要扩展 JFrame ,只要需要就保留对它的引用 . 仅在添加或更改功能时扩展框架 .

    • 而不是 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 使用 setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); ,见于this answer .

    • 而不是 setSize(500,500); 使用 panel.setPreferredSize(new Dimension(500,500)); . 或者更好的是,扩展 JButton 以使 SquareButton 返回优先大小等于宽度或高度的最大首选大小 . 最后一个将确保GUI是它需要的大小,方形和允许足够的空间来显示文本 .

    • 而不是 setLocationRelativeTo(null); 使用 setLocationByPlatform(true); ,如第2点中链接的答案所示 .

    • setVisible(true); 之前添加 pack() ,以确保GUI是显示内容所需的大小 .

    • 而不是 setResizable(false) 调用 setMinimumSize(getSize()) .

    • 在EDT上启动并更新GUI . 有关详细信息,请参阅Concurrency in Swing .

相关问题