Reputation: 345
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
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
Reputation: 25705
use setIcon()
and getIcon()
methods to set and get image-icons on JButton
Identification of button is best done with either:
Component.getName()
and Component.setName()
or getText()
and setText()
. Upvotes: 2
Reputation: 32391
I don't find a good approach to identify buttons based on their icons. Your components, including JButton
s, can have names that you can use for identification. This is how acceptance testing tools work.
button.setName(uniqueName);
button.getName();
Upvotes: 4