How to get specific ID for a JButton?

前端 未结 2 386
攒了一身酷
攒了一身酷 2021-01-27 07:10

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:

            


        
相关标签:
2条回答
  • 2021-01-27 07:54

    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
        }   
    
    
    
    }
    
    0 讨论(0)
  • 2021-01-27 07:56

    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.
    0 讨论(0)
提交回复
热议问题