My question is basically just the title, but I have a button in my code that makes some JRadiobuttons appear, do I then need to make another action performed method and give it a different name or something? Nothing happens when I use the same action performed method.
so like:
@Override
public void actionPerformed(ActionEvent a) {
if( a.getSource() == button1 ) {
System.out.println("hi");
}
}
@Override
public void ActionPerformed(ActionEvent b){
if(b.getSource()==firstJRadioButton){
System.out.println("hi there");
}
}```
The code above gives me an error and is not my exact code, but I hope it sort of says what I am trying to do if that makes sense.
It's always better to put your real working code in a question.
The short answer is that you need to make another
ActionListenerobject, with anotheractionPerformedmethod, or adapt your singleactionPerformedmethod to handle all your components.An
ActionListeneris an instance of a class which implements theActionListenerinterface, so you can only have one action listener per class.This means that there are two ways of handling the actions of multiple components:
Have a single
ActionListenerinstance and then check which component has performed the action:Have an
ActionListenerfor each component. This is a better approach, as yourActionListenerimplementation doesn't end up with all your code in it.You don't have to use a lambda for the
ActionListener, you might create your own class hierarchy ofActionListenerimplementations to reuse common code and improve testability:(these are not best practice Swing programs, just the shortest way to illustrate this point)