【问题标题】:How to implement actionlistener for a grid of buttons in java swing?java - 如何在java swing中为按钮网格实现actionlistener?
【发布时间】:2013-10-07 03:53:28
【问题描述】:

我正在用 java 开发一个打地鼠游戏。我正在创建一个 10*10 的按钮网格。但是我无法访问 actionlistener 中单击按钮的 id。这是我到目前为止的代码。

    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 个按钮时,它仍然会打印“点击了其他按钮”。

【问题讨论】:

    标签: java swing jbutton actionlistener


    【解决方案1】:

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

    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方法中,简单查找ActionEventactionCommand属性....

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

    同样,您可以使用buttons 数组根据ActionEvent 的源查找按钮

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

    但这取决于你...

    【讨论】:

    • 非常感谢!!这正是我想知道的:)
    • @YashKelkar 如果它解决了您的问题,请接受答案。谢谢。
    • 我可能会在那个地方使用source == buttons[i][j],因为你不想要值相等,而是要引用相等。
    【解决方案2】:

    使用按钮对象,而不是字符串。您不需要跟踪按钮的 ID 或名称。只需遍历所有按钮即可找出来源。

    在创建按钮时,您可以按下列表中的所有 whack-a-mole 按钮。并在找到源时遍历它们。

    使用setActionCommand() & getActionCommand() 而不是setName() 来处理按钮敲击

     for(JButton button : buttonList )
        if (ae.getSource() == button) {
            //Do required tasks.
        }
    

    【讨论】:

      猜你喜欢
      • 2011-08-20
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-10
      • 1970-01-01
      • 2012-05-01
      • 1970-01-01
      相关资源
      最近更新 更多