我有一个当前使用200多个按钮的应用程序,每个按钮都返回其变量名称的String。有没有办法做到这一点?为每个设置name属性将非常耗时。
答案 0 :(得分:2)
使用一组按钮:
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);
}
答案 1 :(得分:1)
使用JButton#putClientProperty
识别具体的JButton
buttons[i][j].putClientProperty("column", i);
buttons[i][j].putClientProperty("row", j);
buttons[i][j].addActionListener(new MyActionListener());
从ActionListener
获取(例如)
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"));
}
JButton
的正确方法应该是使用Swing Action代替ActionListener