1

我有一个当前使用超过 200 个按钮的应用程序,每个按钮都返回其变量名的字符串。有没有办法做到这一点?为每个设置 name 属性将非常耗时。

4

2 回答 2

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);
}
于 2012-11-17T09:23:19.770 回答
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"));
}
于 2012-11-17T09:24:05.523 回答