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

Java - JLabel/GUI assignment Write a program which displays a window containing

ID: 640089 • Letter: J

Question

Java - JLabel/GUI assignment

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. 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 calling System.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);
   }

}

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