Ive gone through some stack overflow questions and found this similar question.
From what I understand using a switch statement in an actionPerformed method for this context will not work and an if-else statement is required.
Is there a more efficient way to do this without having repetitive code? I've heard I could use Abstract Action to give multiple buttons the same action but i haven't figured out how to use it properly.
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == loginButton){
cardLayout.show(cards, LOGIN_PANEL);
}
else if(e.getSource() == signUpButton){
cardLayout.show(cards, SIGN_UP_PANEL);
}
else if(e.getSource() == transactionHistoryButton){
cardLayout.show(cards,TABLE_PANEL);
}
else if(e.getSource() == depositButton){
cardLayout.show(cards, DEPOSIT_PANEL);
}
else if(e.getSource() == withdrawButton){
cardLayout.show(cards, WITHDRAW_PANEL);
}
else if(e.getSource() == checkBalanceButton){
cardLayout.show(cards,BALANCE_PANEL);
}
else if(e.getSource() == logout){
cardLayout.show(cards, OPTION_PANEL);
}
else if(e.getSource() == backButtonP1){
cardLayout.show(cards, OPTION_PANEL);
}
else if(e.getSource() == backButtonP2){
cardLayout.show(cards, OPTION_PANEL);
}
else if(e.getSource() == backButtonP3){
cardLayout.show(cards, UNLOCKED_PANEL);
}
else if(e.getSource() == backButtonP4){
cardLayout.show(cards, UNLOCKED_PANEL);
}
else if(e.getSource() == backButtonP5){
cardLayout.show(cards, UNLOCKED_PANEL);
}
else if(e.getSource() == backButtonP6){
cardLayout.show(cards, UNLOCKED_PANEL);
}
}
Don't attempt to use a switch statement or nested if/else statements. This is an indication of poor design.
If you want to share the same
ActionListenerfor all your buttons then you would need to write a genericActionListener.Something like:
Then when you create your buttons you would use:
Or you can use a Java lambda to easily create a unique
ActionListenerfor each button. Something like:You would use an
Action, to give provide unique functionality. The benefit of anActionis that it can be shared by different components, likeJButtonor aJMenuItem, to perform the same Action.Read the section from the Swing tutorial on How to Use Action for the benefits of using an Action over an ActionListener.