Netbeans中Swing组件的变量名称

时间:2012-11-17 09:12:17

标签: java swing jbutton

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

2 个答案:

答案 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"));
}