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

GUI Write a program which displays a window containing two buttons, labeled \"on

ID: 640156 • Letter: G

Question

GUI

Write a program which displays a window containing two buttons, labeled "one" and "two". When a button is pressed, a report of this event should be printed on the console (e.g. "Button two has been pressed"). You should be able to press the buttons as often as you like, in any order, and wind up with a sequence of printed messages. When you click the close button at the corner of the window (marked X), the program should stop.

create a JFrame with a JButton and an ActionListener that exits the program when the button is pressed. For the assignment, you want to arrange for the window's close button to exit the program. You also want to change the JButton's ActionListener so that it prints a message to System.out rather than callingSystem.exit(). At that point, you should be able to test the one button.

Then, add a second button. Remember it will need its own ActionListener to print the slightly different message.

Explanation / Answer

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class Buttons {
  
   public static int , twoC =0 ;
  
   public static void main(String[] args){
       JFrame frame = new JFrame("Buttons");
       JButton JButton("One");
       JButton two = new JButton("Two");
       JPanel panel = new JPanel(new FlowLayout());
      
       one.addActionListener(new ActionListener() {
           @Override
           public void actionPerformed(ActionEvent e) {
               ++oneC;
               System.out.println("Button one has been pressed "+oneC+" times");  
           }
       });
      
       two.addActionListener(new ActionListener() {
           @Override
           public void actionPerformed(ActionEvent e) {
               ++twoC;
               System.out.println("Button two has been pressed "+twoC+" times");  
           }
       });
      
       one.setVisible(true);
       two.setVisible(true);
      
       panel.add(one);
       panel.add(two);
      
       frame.add(panel);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setSize(200,200);
       frame.setVisible(true);
   }

}