user1831598
user1831598

Reputation: 11

Variable name of Swing component in Netbeans

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.

Upvotes: 1

Views: 2394

Answers (2)

mKorbel
mKorbel

Reputation: 109823

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

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 692281

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);
}

Upvotes: 2

Related Questions