Variable name of Swing component in Netbeans

爱⌒轻易说出口 提交于 2020-01-05 05:40:45

问题


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 JButton should be to use Swing Action instead of ActionListener


来源:https://stackoverflow.com/questions/13429219/variable-name-of-swing-component-in-netbeans

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!