How to get specific ID for a JButton?

丶灬走出姿态 提交于 2019-12-02 12:19:19

There are multiple ways to distinguish which button fired the ActionEvent:

  1. Set/get the action command of each button (eg if (e.getActionCommand().equals("Top Left"))
  2. Use == to compare instances (eg if (e.getSource() == buttray[0] ))
  3. Get the text of the JButton (eg if (e.getSource().getText().equals("Top Left"))
  4. Set/get the name of the JButton (eg if (e.getSource().getName().equals("Top Left"))
  5. Add a different ActionListener to each button (in other words 1:1 Listener to button)
  6. ...and perhaps more ways will be added in the comments section below.

you already keep a track of the buttons by the array index i.e. buttray[i]. Use getSource()

   public void actionPerformed(ActionEvent e) 
{
    // TODO Auto-generated method stub
    for(int i=0;i<buttray.length;i++)
    if(e.getSource()==buttray[i])
    {   
        //code here
    }   



}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!