Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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");
       }
      
   }  

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote