如何在Java swing中为按钮网格实现actionlistener? [英] How to implement actionlistener for a grid of buttons in java swing?

查看:88
本文介绍了如何在Java swing中为按钮网格实现actionlistener?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java开发一款小游戏。我正在创建一个10 * 10的按钮网格。但是,我无法访问actionlistener中单击的按钮的ID。这是我到目前为止的代码。

I am developing a whack-a-mole game in java. I am creating a 10*10 grid of buttons. However I am not being able to access the id of the clicked button in the actionlistener. Here is the code I have so far.

    String buttonID;
    buttonPanel.setLayout(new GridLayout(10,10));
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            buttonID = Integer.toString(++buttonCount);
            buttons[i][j] = new JButton();
            buttons[i][j].setName(buttonID);
            buttons[i][j].addActionListener(this);
            buttons[i][j].setDisabledIcon(null);
            buttonPanel.add(buttons[i][j]);
        }
    }

   public void actionPerformed(ActionEvent ae) {
    if (ae.getSource()==startButton) {
        System.out.println("Game has been started");
    }
    if (ae.getSource() == "34") {  //please see the description below
        System.out.println("Yes I have clicked this button");
    }
    else {
        System.out.println("Other button is clicked");
    }
}

目前,我刚刚打印了一些内容。我不知道如何将ae.getsource()与单击的按钮进行比较。我只是尝试将其与 34进行比较。但是,当我单击网格上的第34个按钮时,它仍然打印单击了其他按钮。

Currently I have just printed a few things. I don't know how to compare the ae.getsource() with the button that was clicked. I just tried trying to compare it with "34". But when I click the 34th button on the grid it still prints "Other button is clicked".

推荐答案

使用按钮 actionCommand 属性可根据您的要求唯一地标识每个按钮...

Use the buttons actionCommand property to uniquely identify each button as per your requirements...

for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        buttonID = Integer.toString(++buttonCount);
        //...
        buttons[i][j].setActionCommand(String.toString(buttonID));
        //...
    }
}

然后在您 actionPerformed 方法,只需查找 ActionEvent actionCommand 属性c> ....

Then in you actionPerformed method, simple look up the actionCommand property of the ActionEvent....

public void actionPerformed(ActionEvent ae) {
    String cmd = ae.getActionCommand();
    if ("0".equals(cmd)) {
        //...
    } else if ...

同样,您可以使用按钮数组基于 ActionEvent 的来源

Equally, you could using your buttons array to find the button based on the ActionEvent's source

public void actionPerformed(ActionEvent ae) {
    Object source = ae.getSource();
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            if (source == (buttons[i][j])) {
                //...
                break;
            }
        }
    }

但这取决于您。 ..

But that's up to you...

这篇关于如何在Java swing中为按钮网格实现actionlistener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆