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

The following is code for a console with 6 buttons and two panels: import java.a

ID: 3637845 • Letter: T

Question

The following is code for a console with 6 buttons and two panels:
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.*;

public class ch16pa1
{
public static void main(String args[])
{
JFrame frame = new JFrame("Ch 16 PA 1");
frame.setLayout(new FlowLayout());
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JButton b1 = new JButton("Button 1");
JButton b2 = new JButton("Button 2");
JButton b3 = new JButton("Button 3");
JButton b4 = new JButton("Button 4");
JButton b5 = new JButton("Button 5");
JButton b6 = new JButton("Button 6");
p1.add(b1);
p1.add(b2);
p1.add(b3);
p2.add(b4);
p2.add(b5);
p2.add(b6);
frame.add(p1);
frame.add(p2);
frame.setSize(650,100);
// frame.pack();
frame.setVisible(true);

}
}

Add the code that will display a message on the console indicating which button has been clicked.

Explanation / Answer

You need a listener for each button. That is the way Swing and AWT operates. In other languages it is called a callback. Let me illustrate how I like to write listeners. where you have extends JFrame for the class replace that with this snippet: extends JFrame, implements ActionListener This makes your class implement this particular Listener interface. ActionListener is at java.awt.event.ActionListener. There is one required method: public void actionPerformed(ActionEvent arg0) In it you should arg0.getActionCommand to get the source of the button click. Here you can distinguish between buttons One last part is needed. For each button, you need to call the addActionListener method to register the button with the ActionListener. Once it is registered, then the action listener will respond to button pushes. Ah, one last point, the argument to addActionListener is this so you have addActionListener(this) because you just made your class implement the interface. That should be enough to get you along your way.