我如何找出单击了哪个按钮?

问题描述 投票:13回答:4

我的按钮正常工作,并且我是每个按钮的监听者,如下所示:

for(int i = 0; i <= 25; ++i) {
    buttons[i] = new Button(Character.toString(letters[i]));
    buttons[i].addActionListener(actionListener);
    panel1.add(buttons[i]);
}

在这里您可以看到调用了侦听器,我想找出我要单击的按钮。有没有办法做到这一点?

ActionListener actionListener = new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
        System.out.println(actionEvent.getSource());
    }
};

我需要某种方法来找到数组中的按钮。

java swing button actionlistener
4个回答
21
投票

尝试一下

ActionListener actionListener = new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
        System.out.println(actionEvent.getActionCommand());
    }
};

7
投票

为了获得标签,请尝试此。

ActionListener actionListener = new ActionListener()
{
      public void actionPerformed(ActionEvent actionEvent) {
            JButton button = (JButton)actionEvent.getSource();
            String label = button.getLabel(); //Deprecated 

            String label2 = button.getText();
     }
};

5
投票

ActionEvent具有方法getActionCommand(),该方法将获取JButton的actionCommand字符串。通常这也是文本(对于JButtons)。


0
投票
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    l1.setText("");//name of level what you want

    t1.setText(null);//text field what you want 

    t2.setText(null);//text field what you want
}
© www.soinside.com 2019 - 2024. All rights reserved.