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 javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleButtonApp {
public static void main(String[] args) {
// Create the main frame
JFrame frame = new JFrame("Simple Button App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLayout(null); // Use null layout for absolute positioning (simple example)
// Create a button
JButton button = new JButton("Click Me!");
button.setBounds(90, 50, 100, 40); // x, y, width, height
// Add an ActionListener to the button
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Display a message dialog when the button is clicked
JOptionPane.showMessageDialog(frame, "Button clicked!");
});
// Add the button to the frame
frame.add(button);
// Make the frame visible
frame.setVisible(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 javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
public class NameInputApp {
public static void main(String[] args) {
JFrame frame = new JFrame("Name Input App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(350, 200);
frame.setLayout(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");
submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText(); // Get text from the text field
if (name.isEmpty()) {
JOptionPane.showMessageDialog(frame, "Please enter your name!", "Error",
JOptionPane.ERROR_MESSAGE);
} else {
JOptionPane.showMessageDialog(frame, "Hello, " + name + "!");
});
frame.add(nameLabel);
frame.add(nameField);
frame.add(submitButton);
frame.setVisible(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 javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
public class ColorSelectorApp {
public static void main(String[] args) {
JFrame frame = new JFrame("Color Selector App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(350, 200);
frame.setLayout(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");
showColorButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String selectedColor = (String) colorComboBox.getSelectedItem(); // Get selected item
JOptionPane.showMessageDialog(frame, "You selected: " + selectedColor);
});
frame.add(label);
frame.add(colorComboBox);
frame.add(showColorButton);
frame.setVisible(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 javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 400);
frame.setLayout(new BorderLayout());
displayField = new JTextField("0");
displayField.setEditable(false); // User cannot type directly
displayField.setHorizontalAlignment(JTextField.RIGHT);
displayField.setFont(new Font("Arial", Font.PLAIN, 24));
frame.add(displayField, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(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);
button.setFont(new Font("Arial", Font.PLAIN, 18));
button.addActionListener(new ButtonClickListener());
buttonPanel.add(button);
frame.add(buttonPanel, BorderLayout.CENTER);
frame.setVisible(true);
private class ButtonClickListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.matches("[0-9]")) { // Digit buttons
if (newNumber) {
currentInput = command;
newNumber = false;
} else {
currentInput += command;
displayField.setText(currentInput);
} else if (command.equals(".")) { // Decimal point
if (newNumber) {
currentInput = "0.";
newNumber = false;
} else if (!currentInput.contains(".")) {
currentInput += ".";
displayField.setText(currentInput);
} else if (command.matches("[+\\-*/]")) { // Operation buttons
if (!currentInput.isEmpty() && !newNumber) {
calculate(); // Calculate previous operation if any
lastOperation = command;
newNumber = true;
} else if (currentInput.isEmpty() && lastOperation.isEmpty()) {
// 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 (command.equals("=")) { // Calculate button
calculate();
lastOperation = ""; // Reset operation after calculation
newNumber = true; // Next input starts a new number
} else if (command.equals("C")) { // Clear button
currentInput = "";
result = 0;
lastOperation = "";
newNumber = true;
displayField.setText("0");
private void calculate() {
if (currentInput.isEmpty()) {
return; // Nothing to calculate
double currentValue = Double.parseDouble(currentInput);
if (lastOperation.isEmpty()) {
result = currentValue;
} else {
switch (lastOperation) {
case "+":
result += currentValue;
break;
case "-":
result -= currentValue;
break;
case "*":
result *= currentValue;
break;
case "/":
if (currentValue != 0) {
result /= currentValue;
} else {
JOptionPane.showMessageDialog(null, "Cannot divide by zero!", "Error",
JOptionPane.ERROR_MESSAGE);
result = 0; // Reset result on error
break;
displayField.setText(String.valueOf(result));
currentInput = String.valueOf(result); // Set current input to result for chained operations
public static void main(String[] args) {
SwingUtilities.invokeLater(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.