【问题标题】:Java - How can I difference between two or more JButtons?Java - 如何区分两个或多个 JButton?
【发布时间】:2018-03-08 13:43:57
【问题描述】:

我实际上正在做一个项目,我有一个 ArrayListJButtons,并添加了一个 ActionListener。而且我不知道如何在我的ActionPerformed 方法中区分它们。这些按钮都具有相同的标题,但任何按钮都执行相同的操作。

【问题讨论】:

  • 按钮的声明肯定不同; JButton button1 = new JButton(); JButton button2 = new JButton(); 然后if (event.getSource().equals(button1)) {
  • yourEvent.getSource() - 这将准确告诉您哪个组件触发了该事件。

标签: java swing jbutton actionlistener


【解决方案1】:

在你的 actionPerformed 方法中做这样的事情:

public void actionPerformed(ActionEvent e) { 
    if(e.getSource() == jButton1){
      //perform action when jButton1 clicked
    }
    if(e.getSource() == jButton2){
      //perform action when jButton2 clicked
    }
//So on and so forth
}

【讨论】:

  • 我刚刚意识到我一直使用.equals() 代替JButtons。
猜你喜欢
  • 1970-01-01
  • 2013-06-13
  • 1970-01-01
  • 2011-07-29
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 2016-01-03
相关资源
最近更新 更多