【问题标题】:Adding buttons using gridlayout使用网格布局添加按钮
【发布时间】:2012-12-09 13:37:38
【问题描述】:

我正在尝试创建一个由 9x9 JButtons 制成的简单井字游戏板。 我使用了一个二维数组和一个网格布局,但结果是什么,一个没有任何按钮的框架。 我做错了什么?

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 方法将按钮添加到数组中,然后直接添加到面板中。

【问题讨论】:

    标签: java swing jpanel jbutton grid-layout


    【解决方案1】:

    您需要将按钮添加到您的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]);
          }
       }
    }
    

    【讨论】:

      【解决方案2】:
      // add buttons to the panel INSTEAD of the layout
      // experimentLayout.addLayoutComponent("testName", buttons[k][j]);
      panel.add(buttons[k][j]);
      

      进一步的建议:

      1. 不要扩展JFrame,只要需要就保留一个引用。仅在添加或更改功能时扩展框架..
      2. 使用setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 代替setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);,如this answer 所示。
      3. 使用panel.setPreferredSize(new Dimension(500,500)); 代替setSize(500,500);。或者更好的是,扩展JButton 以创建一个SquareButton,它返回的首选大小等于最大首选宽度或高度。最后一个将确保 GUI 是它需要的大小,正方形并留出足够的空间来显示文本。
      4. 而不是 setLocationRelativeTo(null); 使用 setLocationByPlatform(true);,如第 2 点中链接的答案所示。
      5. setVisible(true); 之前添加pack(),以确保GUI 的大小是显示内容所需的大小。
      6. 而不是setResizable(false) 调用setMinimumSize(getSize())
      7. 在 EDT 上启动和更新 GUI。有关详细信息,请参阅Concurrency in Swing

      【讨论】:

      • 非常感谢您的建议!我总是混淆 setsize 和 preferredsize 以及你提到的其他东西,我不知道该使用什么。再次感谢!
      猜你喜欢
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-07
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      相关资源
      最近更新 更多