本文介绍了使用gridlayout添加按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个由9x9 JButtons制成的简单的井字游戏板.我使用了一个2d数组和一个gridlayout,但是结果什么都没有,没有任何按钮的框架.我在做什么错了?
I'm trying to create a simple tic tac toe board made by 9x9 JButtons.I used a 2d array and a gridlayout but the result is nothing, a frame without any button.What I'm doing wrong?
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方法将按钮添加到数组中,然后直接添加到面板中.
The addButton method is adding the buttons to the array and straight after to the panel.
推荐答案
您需要将按钮添加到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]);
}
}
}
这篇关于使用gridlayout添加按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!