问题
I have an application that is currently using over 200 buttons, each of which returns the String of their variable name. Is there any way to do this? Setting the name property for each of these would be far too time consuming.
回答1:
Use a collection of buttons:
ActionListener theActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(((JButton) e.getSource()).getName());
}
};
List<JButton> buttons = new ArrayList<JButton>();
for (int i = 0; i < 200; i++) {
JButton button = new JButton("Button " + (i + 1));
button.setName("Button " + (i + 1));
button.addActionListener(theActionListener);
buttons.add(button);
}
回答2:
use JButton#putClientProperty for identifying concrete JButton
buttons[i][j].putClientProperty("column", i);
buttons[i][j].putClientProperty("row", j);
buttons[i][j].addActionListener(new MyActionListener());
and get from ActionListener (for example)
public class MyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
System.out.println("clicked column " + btn.getClientProperty("column")
+ ", row " + btn.getClientProperty("row"));
}
- but proper way for
JButtonshould be to use Swing Action instead of ActionListener
来源:https://stackoverflow.com/questions/13429219/variable-name-of-swing-component-in-netbeans