How to get specific ID for a JButton?

◇◆丶佛笑我妖孽 提交于 2019-12-04 06:24:38

问题


I'm trying to build a program that utilizes a 3x3 grid of buttons (using Java Swing), so I initialize it with a GridLayout and a loop to create the buttons:

     panel.setBorder(BorderFactory.createEmptyBorder(3,3,5,5))
     panel.setLayout(new GridLayout(3,3,10,10));

    String[] buttons = {"Top Left", "Top Middle", "Top Right", "Middle Left", "Middle", "Middle Right", "Bottom Left", "Bottom Middle", "Bottom Right"};

    for(int i = 0; i < buttons.length; i++) {
        buttray[i] = new JButton(buttons[i]);
        panel.add(buttray[i]);
        buttray[i].addActionListener(this);
    }

The buttons load just fine, but I do not understand how to use ActionListeners to differentiate between the buttons. When I check the paramString() method from the printout, each button gives the same modifier:

Top Left
ACTION_PERFORMED,cmd=Top Left,when=1431640106712,modifiers=Button1
Top Middle
ACTION_PERFORMED,cmd=Top Middle,when=1431640107566,modifiers=Button1
Top Right
ACTION_PERFORMED,cmd=Top Right,when=1431640107978,modifiers=Button1

Does this modifier value act as the button's identifier, and if so, how do I change it?


回答1:


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.



回答2:


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
    }   



}


来源:https://stackoverflow.com/questions/30248026/how-to-get-specific-id-for-a-jbutton

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