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); } }
Advertisement
Answer
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.
Don’t attempt to use a switch statement or nested if/else statements. This is an indication of poor design.
Is there a more efficient way to do this without having repetitive code?
If you want to share the same ActionListener
for all your buttons then you would need to write a generic ActionListener
.
Something like:
ActionListener al = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); cardLayout.show(cards, command) } }
Then when you create your buttons you would use:
JButton loginButton = new JButton("Login"); loginButton.setActionCommand(LOGIN_PANEL); loginButton.addActionListener( al );
Or you can use a Java lambda to easily create a unique ActionListener
for each button. Something like:
loginButton.addActionListener((e) -> cardLayout.show(cards, LOGIN_PANEL));
I’ve heard I could use Abstract Action to give multiple buttons the same action
You would use an Action
, to give provide unique functionality. The benefit of an Action
is that it can be shared by different components, like JButton
or a JMenuItem
, 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.