问题
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:
- Set/get the action command of each button (eg
if (e.getActionCommand().equals("Top Left")
) - Use == to compare instances (eg
if (e.getSource() == buttray[0] )
) - Get the text of the JButton (eg
if (e.getSource().getText().equals("Top Left")
) - Set/get the name of the JButton (eg
if (e.getSource().getName().equals("Top Left")
) - Add a different ActionListener to each button (in other words 1:1 Listener to button)
- ...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