一个动作侦听器,用于一组面板内的按钮数组

时间:2013-12-07 00:05:14

标签: arrays jbutton actionlistener

我正在尝试为一系列按钮创建一个动作侦听器。我通过制作一个3乘3的面板网格来创建网格,每个面板都有一个3乘3的网格按钮。我需要一种方法让动作监听器告诉我按下了哪个按钮。有没有人有任何想法?

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

public class GameBoardDisplayTest {

    protected JFrame gameBoardFrame = new JFrame();
    protected JButton[] buttonArray = new JButton[9];
    protected JPanel[] panelArray = new JPanel[9];
    protected String playerXName;
    protected String playerOName;
    protected JPanel gameStatePanel = new JPanel(new GridLayout(3,1));


    public GameBoardDisplayTest(String player1, String player2){

        playerXName = player1;
        playerOName = player2;

        gameBoardFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gameBoardFrame.setSize(1000,1000);
        gameBoardFrame.setLocationRelativeTo(null);
        gameBoardFrame.setVisible(true);
        gameBoardFrame.setLayout(new GridLayout(4,3,10,10));

        for (int i = 0; i != 9; i++){
            panelArray[i] = new JPanel(new GridLayout(3,3));
            }

        for (int i = 0; i != 9; i++){
            for (int j = 0; j != 9; j++){
                buttonArray[j] = new JButton("-");
                    buttonArray[j].addActionListener(new ButtonListener());
                panelArray[i].add(buttonArray[j]);
                }
            }


        for (int i = 0; i != 9; i++){

            gameBoardFrame.add(panelArray[i]);

    }    

        gameStatePanel.add(new JLabel("Current Turn's Player"));
        gameStatePanel.add(new JLabel("Current Grid"));
        gameStatePanel.add(new JLabel("Game Start"));


        gameBoardFrame.add(new JLabel("X: " + playerXName));
    gameBoardFrame.add(gameStatePanel);
        gameBoardFrame.add(new JLabel("O: " + playerOName));

    }

    private class ButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println(e.getSource());
        }
    }

  public static void main(String[] args){

    String firstPlayerName = JOptionPane.showInputDialog("Enter the name of the first player: ");

    String secondPlayerName = JOptionPane.showInputDialog("Enter the name of the second player: ");


    GameBoardDisplayTest gridDisplay = new GameBoardDisplayTest(firstPlayerName,secondPlayerName);
}

}

1 个答案:

答案 0 :(得分:1)

您可以在actionPerformed中再次循环。

int buttonLocation;

public void actionPerformed(ActionEvent e){
    for (int i = 0; i < buttonArray.length; i++){
        if (e.getSource() == buttonArray[i])
            buttonLocation = i;
            break;
    }
}

我对你认为你有81个按钮感到有点困惑。您的阵列只有9个按钮。所以我的回答可能不完全正确,但这是解决问题的一种方法。建议,你可能想要一个JButton的2D数组,因为它更有意义,获得一个tic tac toe board的网格索引