Write a program to demonstrate a simple swing application.

Program: Simple Swing Application

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

public class SimpleSwingApp {
    public static void main(String[] args) {
        // Create a frame (main window)
        JFrame frame = new JFrame("Simple Swing App");
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout());

        // Create a label
        JLabel label = new JLabel("Enter your name:");

        // Create a text field
        JTextField textField = new JTextField(15);

        // Create a button
        JButton button = new JButton("Greet");

        // Create an action listener for the button
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String name = textField.getText();
                JOptionPane.showMessageDialog(frame, "Hello, " + name + "!");
            }
        });

        // Add components to the frame
        frame.add(label);
        frame.add(textField);
        frame.add(button);

        // Set the frame to visible
        frame.setVisible(true);
    }
}

✅ Explanation:

  • JFrame: Main window
  • JLabel: Displays a static text
  • JTextField: Input field to enter text
  • JButton: Button to perform an action
  • JOptionPane: Displays a popup message

Output Behavior:

  • A window appears with a label, text field, and button.
  • When the user enters their name and clicks the button, a greeting message pops up.

Leave a Reply

Your email address will not be published. Required fields are marked *