Reputation: 65
I'm writing a program right now that involves two JButtons. The class that contains these JButtons implements ActionListener and therefore contains the method ActionPerformed(ActionEvent e). Is there anyway to have these JButtons both do unique actions within the same ActionPerformed method?
Upvotes: 0
Views: 9569
Reputation: 81694
Sure. Compare the source
of the ActionEvent
object to see which button the event came from (i.e., call getSource()
) and then act accordingly.
Upvotes: 0
Reputation: 14053
You can always get the source of your actionEvent with e.getSource()
. Then just compare that source with your buttons and do the specific action if they're equal.
Upvotes: 0
Reputation: 133587
Sure, you can distinguish them in the following way:
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if (src == bt1) {
// do actions for bt1;
}
else if (src == b2) {
// do action for bt2;
}
}
Upvotes: 3