0

Java swing で Tic Tac Toe プログラムを作成しようとしていて、フレームを作成しました。JButton 配列のボタンで int 配列をアクティブにするにはどうすればよいですか? Tic Tac Toe グリッドのスポットの値を int 配列に保持したいので、ボタンが押されると、int 配列の対応するスポットが 0 または 1 になり、ボタンのテキストが次のように変わります。 XまたはO。

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

public class TicTacToeGui extends javax.swing.JFrame implements ActionListener
{

    int[][] grid = new int[3][3];
    public final static int r = 3;
    public final static int c = 3;
    public final static int X = 0;
    public final static int O = 1;

    TicTacToeGui()
    {
        this.setTitle("Tic Tac Toe");
        JButton[][] button = new JButton[3][3];
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(r, c));
        for(int i = 0; i < r; i++)
        {
            for(int j = 0; j < c; j++)
            {
                button[i][j] = new JButton("");
                button[i][j].addActionListener(this);
                panel.add(button[i][j]);
            }

        }
        this.add(panel);
        this.setSize(400, 400);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public void actionPerformed(ActionEvent e){
        if(e.getSource() instanceof JButton){

        }
    }
    public static void main(String [] args)
    {
        new TicTacToeGui().setVisible(true);
    }

}
4

3 に答える 3

2

独自のJButton実装を作成し、インデックス値を提供できます。私たちはあなたがそれを抽出できることをActionListener

public void actionPerformed(ActionEvent e){
    if(e.getSource() instanceof MySuperButton){

        MySuperButton btn = (MySuperButton)e.getSource();
        int[] index = btn.getIndex();
        // or
        int row = btn.getRow();
        int col = btn.getColumn();

    }
}

次に、設定すると、次のことができます。

for(int i = 0; i < r; i++)
{
    for(int j = 0; j < c; j++)
    {
        button[i][j] = new MySuperButton(i, j); // Store the row/column
        button[i][j].addActionListener(this);
        panel.add(button[i][j]);
    }

}

これにより、ボタンの状態を内部的に保存することもできます...

JToggleButtonもご覧ください。

于 2012-07-25T00:28:49.783 に答える
0

JButtonのsetActionCommandメソッドを使用して、button [0] [0]のアクションコマンドを「00」に設定し、button[2][1]のコマンドを「21」に設定します。この病気により、actionPerformedから簡単に正しい位置を取得できます。また、2つだけでなく、3つの状態が必要です。私が何について話しているのかわからない場合は、三目並べのゲームをプレイして、途中で配列を書き留めてください。

于 2012-07-25T00:36:45.077 に答える
0

e.getSource()JButton インデックスが int 配列を反映していると仮定すると、ボタン配列で押されている ( in ) JButton を検索できますがactionPerformed、ボタン配列をクラスのインスタンス変数として配置する必要があるため、他のメソッドから使​​用できます。actionPerformed()。_ インデックスが見つかったら、int 配列内の対応する値を更新するだけです。

于 2012-07-25T00:23:07.580 に答える