blustone
blustone

Reputation: 345

How should I identify buttons?

I would really appreciate an answer: I have a few JButtons generated with this:

for(int i = 0; i < buttons.length; i++){
        buttons[ i] = new JButton(blank);
        if(i == 3 || i == 6){
            newLine++;
            lineCount = 0;
        }
        buttons[ i].setBounds(lineCount*150,newLine*150,150,150);
        cont.add(buttons[ i]);
        buttons[ i].addActionListener(this);
        lineCount++;
    }

so of course they don't have global names...

Because of this, I need to know how to take the image "out" of the JButton so I know what kind of button it is or be able to identify buttons by name(?).
So how can I do this? Thanks!

by the way, cont is a java.awt.Container

Upvotes: 0

Views: 168

Answers (3)

mKorbel
mKorbel

Reputation: 109813

use putClientProperty for identifying JComponent

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

Upvotes: 2

Aniket Inge
Aniket Inge

Reputation: 25705

use setIcon() and getIcon() methods to set and get image-icons on JButton

Edit in question, demands edit in answer:

Identification of button is best done with either:

  1. Component.getName() and Component.setName() or
  2. using different strings with getText() and setText().

Upvotes: 2

Dan D.
Dan D.

Reputation: 32391

I don't find a good approach to identify buttons based on their icons. Your components, including JButtons, can have names that you can use for identification. This is how acceptance testing tools work.

button.setName(uniqueName);
button.getName();

Upvotes: 4

Related Questions