Here are four Java programs demonstrating simple GUI applications using the Swing library.
Each
program includes the source code and a description of its expected behavior and output.
### 1. Simple Button and Message Dialog
This program creates a window with a single button. When the button is clicked, a small message dialog
box appears with the text "Button clicked!".
```java
import [Link].*;
import [Link];
import [Link];
public class SimpleButtonApp {
public static void main(String[] args) {
// Create the main frame
JFrame frame = new JFrame("Simple Button App");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](300, 200);
[Link](null); // Use null layout for absolute positioning (simple example)
// Create a button
JButton button = new JButton("Click Me!");
[Link](90, 50, 100, 40); // x, y, width, height
// Add an ActionListener to the button
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Display a message dialog when the button is clicked
[Link](frame, "Button clicked!");
});
// Add the button to the frame
[Link](button);
// Make the frame visible
[Link](true);
```
**Expected Result:**
A window titled "Simple Button App" will appear. Inside, there will be a button labeled "Click Me!".
When you click this button, a small pop-up window will appear with the title "Message" (or similar,
depending on OS) and the text "Button clicked!". Clicking "OK" on the pop-up will close it.
### 2. Name Input and Greeting
This program features a text field for entering a name and a "Submit" button. Upon clicking "Submit", a
message dialog displays a personalized greeting using the entered name.
```java
import [Link].*;
import [Link];
import [Link];
import [Link].*;
public class NameInputApp {
public static void main(String[] args) {
JFrame frame = new JFrame("Name Input App");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](350, 200);
[Link](new FlowLayout()); // Use FlowLayout for simplicity
JLabel nameLabel = new JLabel("Enter your name:");
JTextField nameField = new JTextField(20); // 20 columns wide
JButton submitButton = new JButton("Submit");
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = [Link](); // Get text from the text field
if ([Link]()) {
[Link](frame, "Please enter your name!", "Error",
JOptionPane.ERROR_MESSAGE);
} else {
[Link](frame, "Hello, " + name + "!");
});
[Link](nameLabel);
[Link](nameField);
[Link](submitButton);
[Link](true);
```
**Expected Result:**
A window titled "Name Input App" will appear. It will have the text "Enter your name:", followed by a
text field, and then a "Submit" button. You can type your name into the text field. When you click
"Submit", a pop-up dialog will appear saying "Hello, [Your Name]!". If you click "Submit" without
entering a name, an error message "Please enter your name!" will be displayed.
### 3. Color Selection with JComboBox
This program presents a drop-down list of colors. After selecting a color and clicking the "Show Color"
button, a message dialog will display the name of the selected color.
```java
import [Link].*;
import [Link];
import [Link];
import [Link].*;
public class ColorSelectorApp {
public static void main(String[] args) {
JFrame frame = new JFrame("Color Selector App");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](350, 200);
[Link](new FlowLayout());
JLabel label = new JLabel("Select a color:");
String[] colors = {"Red", "Green", "Blue", "Yellow", "Orange"};
JComboBox<String> colorComboBox = new JComboBox<>(colors);
JButton showColorButton = new JButton("Show Color");
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String selectedColor = (String) [Link](); // Get selected item
[Link](frame, "You selected: " + selectedColor);
});
[Link](label);
[Link](colorComboBox);
[Link](showColorButton);
[Link](true);
```
**Expected Result:**
A window titled "Color Selector App" will appear. It will display "Select a color:" followed by a drop-
down list (combo box) containing "Red", "Green", "Blue", "Yellow", and "Orange". Next to it, there will
be a "Show Color" button. When you select a color from the drop-down and click "Show Color", a pop-
up dialog will appear stating "You selected: [Selected Color]!".
### 4. Simple Calculator
This program simulates a basic calculator. It includes a text field for displaying numbers and results, and
buttons for digits (0-9), arithmetic operations (+, -, \*, /), and a "Calculate" button. This implementation
handles simple two-operand operations.
```java
import [Link].*;
import [Link].*;
import [Link];
import [Link];
public class SimpleCalculatorApp {
private JTextField displayField;
private String currentInput = "";
private double result = 0;
private String lastOperation = "";
private boolean newNumber = true; // Flag to indicate if a new number is being entered
public SimpleCalculatorApp() {
JFrame frame = new JFrame("Simple Calculator");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](300, 400);
[Link](new BorderLayout());
displayField = new JTextField("0");
[Link](false); // User cannot type directly
[Link]([Link]);
[Link](new Font("Arial", [Link], 24));
[Link](displayField, [Link]);
JPanel buttonPanel = new JPanel();
[Link](new GridLayout(5, 4, 5, 5)); // 5 rows, 4 columns, with gaps
String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+",
"C" // Clear button
};
for (String label : buttonLabels) {
JButton button = new JButton(label);
[Link](new Font("Arial", [Link], 18));
[Link](new ButtonClickListener());
[Link](button);
[Link](buttonPanel, [Link]);
[Link](true);
private class ButtonClickListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String command = [Link]();
if ([Link]("[0-9]")) { // Digit buttons
if (newNumber) {
currentInput = command;
newNumber = false;
} else {
currentInput += command;
[Link](currentInput);
} else if ([Link](".")) { // Decimal point
if (newNumber) {
currentInput = "0.";
newNumber = false;
} else if () {
currentInput += ".";
[Link](currentInput);
} else if ([Link]("[+\\-*/]")) { // Operation buttons
if (![Link]() && !newNumber) {
calculate(); // Calculate previous operation if any
lastOperation = command;
newNumber = true;
} else if ([Link]() && [Link]()) {
// If no number entered yet, start with 0 for calculation
result = 0;
lastOperation = command;
newNumber = true;
} else {
// If an operation was just pressed, change it
lastOperation = command;
}
} else if ([Link]("=")) { // Calculate button
calculate();
lastOperation = ""; // Reset operation after calculation
newNumber = true; // Next input starts a new number
} else if ([Link]("C")) { // Clear button
currentInput = "";
result = 0;
lastOperation = "";
newNumber = true;
[Link]("0");
private void calculate() {
if ([Link]()) {
return; // Nothing to calculate
double currentValue = [Link](currentInput);
if ([Link]()) {
result = currentValue;
} else {
switch (lastOperation) {
case "+":
result += currentValue;
break;
case "-":
result -= currentValue;
break;
case "*":
result *= currentValue;
break;
case "/":
if (currentValue != 0) {
result /= currentValue;
} else {
[Link](null, "Cannot divide by zero!", "Error",
JOptionPane.ERROR_MESSAGE);
result = 0; // Reset result on error
break;
[Link]([Link](result));
currentInput = [Link](result); // Set current input to result for chained operations
public static void main(String[] args) {
[Link](SimpleCalculatorApp::new);
```
**Expected Result:**
A window titled "Simple Calculator" will appear. At the top, there's a display field showing "0". Below it,
there's a grid of buttons:
* Digits: 0-9
* Operations: +, -, \*, /
* Decimal point: .
* Equals: =
* Clear: C
You can click the digit buttons to enter numbers into the display. Clicking an operation button (+, -, \*, /)
will store the current number and operation. Clicking another number and then "=" will perform the
calculation and display the result. For example:
1. Click "5" -> display shows "5"
2. Click "+" -> display still shows "5" (or "0" if `newNumber` logic resets it, but the internal `result` is 5)
3. Click "3" -> display shows "3"
4. Click "=" -> display shows "8.0"
Clicking "C" will clear the display and reset the calculator. An error message "Cannot divide by zero!" will
appear if you attempt to divide by zero.