Modify the code below so that two separate listener classes are used - one for e
ID: 3937034 • Letter: M
Question
Modify the code below so that two separate listener classes are used - one for each of the two buttons. public class LettRight Panel extends JPanel {private JButton left, right; private JLabel label; public LeftRightPanel () {left = new JButton ("Left"); right = new JButton ("Right"); label = new JLabel("Left/Right"); ButtonListener listener = new ButtonListener(); left.addActionListener (listener); right.addActionLiatener (listener); add (left); add (right); add (label);} private class ButtonListener implements ActionListener public void actionPerformed (ActionEvent event) {if (event.getSource() == left) label.setText("Left"); else label.setText("Right");}}}Explanation / Answer
Hi,
I have modifief the code and highlighted the code changes below.
LeftRightPanel.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class LeftRightPanel extends JPanel{
private JButton left, right;
private JLabel label;
public LeftRightPanel(){
left = new JButton("Left");
right = new JButton("Right");
label = new JLabel("Left/Right");
LeftButtonListener leftListener = new LeftButtonListener();
RightButtonListener rightListener = new RightButtonListener();
left.addActionListener(leftListener);
right.addActionListener(rightListener);
add(left);
add(right);
add(label);
}
private class LeftButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
label.setText("Left");
}
}
private class RightButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
label.setText("Right");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.