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

Write a program that opens a new window containing a square JPanel. This JPanel

ID: 3655924 • Letter: W

Question

Write a program that opens a new window containing a square JPanel. This JPanel should have two Components in it:

1. The top Component should be an empty gray box (a JLabel with no text).

2. The bottom Component should be a JComboBox that allows the user to select digits 1 through 9 or blank.

When the user selects a number in the JComboBox, that number should appear in the formerly empty gray box, which now is a white box. When the user selects "blank", the top panel should empty and become gray.

Explanation / Answer

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class HelloWorldGUI2 {

private static class HelloWorldDisplay extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString( "Hello World!", 20, 30 );
}
}

private static class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}

public static void main(String[] args) {

HelloWorldDisplay displayPanel = new HelloWorldDisplay();
JButton okButton = new JButton("OK");
ButtonHandler listener = new ButtonHandler();
okButton.addActionListener(listener);

JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(displayPanel, BorderLayout.CENTER);
content.add(okButton, BorderLayout.SOUTH);

JFrame window = new JFrame("GUI Test");
window.setContentPane(content);
window.setSize(250,100);
window.setLocation(100,100);
window.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