gpt4 book ai didi

java - 2D JButton 数组,想要为游戏添加 Action 监听器

转载 作者:行者123 更新时间:2023-12-01 18:17:07 24 4
gpt4 key购买 nike

我想制作 TIC TAC TOE 游戏,但我有一个问题。我创建了一个 2D 数组,但我不知道如何解决它们以使 ActionListener 工作。

这是我的代码:

public class GUI {
public static JButton[][] buttonsall = new JButton[3][3];
public static JFrame frame = new JFrame("TIC TAC TOE");
public static void draw() {
// frame
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
frame.setBackground(Color.white);
frame.setBounds(500, 500, 600,600);
// actionListener
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
//dont know further here
}
}
};

//buttons buttonsall[x][y]
for (int y = 0; y<3;y++) {
for (int x = 0; x<3;x++) {
buttonsall[x][y] = new JButton();
buttonsall[x][y].setVisible(true);
buttonsall[x][y].setSize(80, 80);
buttonsall[x][y].addActionListener(listener);
System.out.println(buttonsall[x][y] +" "+x +" "+y);
frame.add(buttonsall[x][y]);
buttonsall[x][y].setBackground(Color.white);
}
}
frame.setLayout(new GridLayout(3,3));
}

最佳答案

您可以在创建每个 JButton 时为其设置名称。我更新您的代码如下:


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class GUI {
public static JButton[][] buttonsall = new JButton[3][3];
public static JFrame frame = new JFrame("TIC TAC TOE");

public static void draw() {
// frame
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
frame.setBackground(Color.white);
frame.setBounds(500, 500, 600, 600);
// actionListener
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
//dont know further here
JButton b = (JButton)e.getSource();

System.out.println("Button is:" + b.getName());
}
}
};

//buttons buttonsall[x][y]
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
buttonsall[x][y] = new JButton();
buttonsall[x][y].setVisible(true);
buttonsall[x][y].setName("Button_" + x + "_" + y);
buttonsall[x][y].setSize(80, 80);
buttonsall[x][y].addActionListener(listener);
System.out.println(buttonsall[x][y] + " " + x + " " + y);
frame.add(buttonsall[x][y]);
buttonsall[x][y].setBackground(Color.white);
}
}
frame.setLayout(new GridLayout(3, 3));
}

public static void main(String[] args) {

GUI.draw();

}
}

关于java - 2D JButton 数组,想要为游戏添加 Action 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60345532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com