[英]How can I write a method that return an int from an array of buttons when one is pressed?
[英]How can i write my winning method with an int array
public class Logik extends JFrame implements ActionListener {
private static final int[] WINCASE = { 0, 1, 2 };
JButton[] buttons = new JButton[9];
public int counter = 0;
public Logik() {
JFrame f = new JFrame("TicTacToe");
f.setVisible(true);
f.setSize(400, 420);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
JPanel p = new JPanel();
f.add(p);
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton(String.valueOf(i));
buttons[i].setPreferredSize(new Dimension(120, 120));
buttons[i].addActionListener(this);
buttons[i].setText("");
p.add(buttons[i]);
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
JButton b = (JButton) e.getSource();
if (counter % 2 == 0) {
b.setText("X");
b.setEnabled(false);
counter++;
} else {
b.setText("O");
counter++;
b.setEnabled(false);
}
}
}
}
如果你能看到我制作了一个 int Array
,我有 9 个按钮,我想通过在该数组中写入所有获胜案例来知道谁获胜,例如: {4,5,6}{7,8,9}.
但我不知道如何将我的数组用于 Jbutton 使其工作,有人可以给我提示吗?
当然,您可以通过多种方式做到这一点,例如,您可以在 actionPerformed 中检查整个“板”,看看您是否有赢家。
但是我认为你的程序可以从一个抽象的东西中受益,它提醒你正在构建的游戏; 将按钮放在矩阵(而不是数组)中,为什么不通过扩展 java 类来创建自定义 JButton - 在该类中,您可以添加按钮在矩阵中的协调。 这样您就可以更轻松地检查获胜者。
对于矩阵,我的意思是二维数组,如JButton[][] buttons = new JButton[3][3]
下面是一个关于如何扩展JButton
类的示例 如何在 Java 中创建自定义 JButton 类? 当然,您需要在 CustomButton 类中添加与您的程序相关的逻辑,并可能给出一个在该上下文中有意义的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.