我只想在Eclipse中用Java创建一个TicTacToe游戏。已经大约一个月了,我仍然不知道如何创建具有3 * 3网格的JButtons数组。我试过看很多教程,我自己也试过。
如果有人为我提供创建3 * 3网格JButton的代码,这将很有帮助。
答案 0 :(得分:1)
这是我想您正在搜索的内容:
package so1;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
public class MyWindow extends JFrame {
public MyWindow() {
JPanel panel = new JPanel();
int maxWidth = 3;
int maxHeight = 3;
JButton[][] buttons = new JButton[maxWidth][maxHeight];
panel.setLayout(new GridLayout(maxWidth, maxHeight));
for (int i = 0; i < maxWidth; i++) {
for (int j = 0; j < maxHeight; j++) {
buttons[i][j] = new JButton(i + "," + j);
panel.add(buttons[i][j], maxWidth * i + j);
}
}
setContentPane(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public static void main(String[] args) {
MyWindow ex = new MyWindow();
ex.setVisible(true);
}
}
答案 1 :(得分:0)
JButton[][] buttons = new JButton[3][3];
答案 2 :(得分:0)
JButton[][] buttons = new JButton[3][3];
要将值赋给button[0][0]
,您必须执行以下操作:
buttons[0][0] = new JButton();