[英]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);
}
}
}
}
If you can see I made an int Array
and I have 9 buttons and I want to know who won by writing all winning cases in that array like: {4,5,6}{7,8,9}.
如果你能看到我制作了一个 int
Array
,我有 9 个按钮,我想通过在该数组中写入所有获胜案例来知道谁获胜,例如: {4,5,6}{7,8,9}.
but I don't know how to use my array for Jbutton to make it work, can someone give me tips?但我不知道如何将我的数组用于 Jbutton 使其工作,有人可以给我提示吗?
You can do that in many ways of course, for eg you can check the entire "board" in actionPerformed to see if you have a winner.当然,您可以通过多种方式做到这一点,例如,您可以在 actionPerformed 中检查整个“板”,看看您是否有赢家。
But I think you program could benefit from an abstraction that reminds of the game you are building;但是我认为你的程序可以从一个抽象的东西中受益,它提醒你正在构建的游戏; place the buttons in an matrix (instead of the array) and why not create your custom JButton by extending the java class - in that class you can add the coordination the button have in the matrix.
将按钮放在矩阵(而不是数组)中,为什么不通过扩展 java 类来创建自定义 JButton - 在该类中,您可以添加按钮在矩阵中的协调。 Then it will be much easier for you to check for a winner.
这样您就可以更轻松地检查获胜者。
With a matrix I mean two dimensional array like JButton[][] buttons = new JButton[3][3]
Here is one example on how you can extends the JButton
class How to create a custom JButton class in Java?对于矩阵,我的意思是二维数组,如
JButton[][] buttons = new JButton[3][3]
下面是一个关于如何扩展JButton
类的示例 如何在 Java 中创建自定义 JButton 类? Of course you need to add logic related to your program in the CustomButton class, and maybe give a name meaningful in that context.当然,您需要在 CustomButton 类中添加与您的程序相关的逻辑,并可能给出一个在该上下文中有意义的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.