Java – get button name from actionlistener?
I have browsed the Internet, but I can't find the answer
I am using the for loop to create 36 buttons called A1, A2, etc., and assign a unique action command to each button at the same time
Later, I want to get the name of the button from the actionperformed (ActionEvent E) method
I can make actioncommand simple enough, but I also need the name of the button
Any help a lot appitecaited!
Edit:
This is the code I'm using:
String letters[] = {"0","a","b","c","d","e","f"};
JButton btn[] = new JButton[35];
int count = 0;
for (int f=1; f < 7;f++){
for (int i=1; i < 7;i++){
btn[i] = new JButton(letters[f]+i,cup);
System.out.println(btn[i]));
mainGameWindow.add(btn[i]);
btn[i].addActionListener(this);
String StringCommand = Integer.toString(randomArrayNum());
btn[i].setActionCommand(StringCommand);
count++;
if(count == 18){
generateArray();
}
}
}
This is 6 × The 6 grid provides 36 buttons, namely a1-6, b1-6, C1-6, etc
Once I create a button in this way, I seem to have no control over the button. I can't assign an icon or get the name of the button
Thank you in advance
Solution
Keep the reference of the button in the map
String letters[] = {"0","f"};
JButton btn;
int count = 0;
HashMap<String,JButton> buttonCache = new HashMap<String,JButton>();
for (int f=1; f < 7;f++){
for (int i=1; i < 7;i++){
btn = new JButton(letters[f]+i,cup);
mainGameWindow.add(btn[i]);
btn.addActionListener(this);
String stringCommand = Integer.toString(randomArrayNum());
btn.setActionCommand(stringCommand);
buttonMap.put(stringCommand,btn);
count++;
if(count == 18){
generateArray();
}
}
}
Then, in actionlistener, get the button from the command:
public void actionPerformed(ActionEvent e) {
String command = ((JButton) e.getSource()).getActionCommand();
JButton button = buttonCache.get(command);
if (null != button) {
// do something with the button
}
}
edit
Answer this again five years later. I don't know why I suggest using HashMap: P
This code is exactly the same. There is no third-party map:
String letters[] = {"0","f"};
int count = 0;
for (int f=1; f < 7;f++){
for (int i=1; i < 7;i++) {
String stringCommand = Integer.toString(randomArrayNum());
Button btn = new JButton(letters[f]+i,cup);
btn.setActionCommand(stringCommand);
btn.addActionListener(this);
mainGameWindow.add(btn[i]);
// NOTE : I have no idea what this is for...
count++;
if(count == 18){
generateArray();
}
}
}
In actionlistener
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
String command = button.getActionCommand();
// do something with the button
// the command may help identifying the button...
}
