2012-07-25 112 views
0

我想用java swing制作一个Tic Tac Toe程序,并且我制作了框架。我怎么能让JButton数组中的按钮激活int数组?我想要int数组来保存井字格网格中的点的值,所以当按下按钮时,int数组中相应的点将是0或1,并且按钮的文本将变为一个X或O.JButton数组到int数组

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); 
    } 

} 

回答

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

0

假设将JButton索引镜像int数组,可以搜索对JButton被按压(在actionPerformede.getSource())按钮阵列中,但你必须把按钮数组作为实例变量的类,所以你可以从其他方法使用它,尤其是。 actionPerformed()。一旦找到索引,只需在int数组中更新它的对应值即可。

0

使用JButton的setActionCommand方法设置按钮的动作命令[0] [0]为“00”和从按钮[2] [1]到“21”的命令。这让你很容易从actionPerformed获得位置。另外,你需要三个状态,而不仅仅是2.如果你不确定我在说什么,玩一个井字游戏并在大约一半的时候写下这个数组。