我正在尝试创建一个由 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 方法将按钮添加到数组中,然后直接添加到面板中。
最佳答案
您需要将按钮添加到您的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]);
}
}
}
关于java - 使用网格布局添加按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13787873/