Sure! Below is an example of a simple Java program that creates a GUI using Swing.
This program will
display a window with a label, text field, button, and a text area, which is a common layout for basic
applications.
▎Java Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleGuiApp {
public static void main(String[] args) {
// Create the frame
JFrame frame = new JFrame("Simple GUI Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
// Create a panel to hold components
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 1)); // Set layout to GridLayout with 4 rows and 1 column
// Create components
JLabel label = new JLabel("Enter your text:");
JTextField textField = new JTextField();
JButton button = new JButton("Submit");
JTextArea textArea = new JTextArea();
// Add action listener to the button
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String inputText = textField.getText();
textArea.append(inputText + "\n"); // Append the input text to the text area
textField.setText(""); // Clear the text field after submission
});
// Add components to the panel
panel.add(label);
panel.add(textField);
panel.add(button);
panel.add(new JScrollPane(textArea)); // Add scroll pane for the text area
// Add panel to the frame
frame.add(panel);
// Set frame visibility
frame.setVisible(true);
}
▎Explanation of the Code:
• JFrame: This is the main window of the application.
• JPanel: A container that holds and organizes the components.
• JLabel: Displays a label prompting the user to enter text.
• JTextField: A single-line input field where users can type their text.
• JButton: A button that the user can click to submit their input.
• JTextArea: A multi-line area that displays submitted text. It is wrapped in a JScrollPane to allow
scrolling if the content exceeds the visible area.
• ActionListener: This interface is implemented to handle button clicks. When the button is clicked, it
retrieves the text from the JTextField, appends it to the JTextArea, and clears the JTextField.
▎How to Run the Program:
1. Make sure you have Java Development Kit (JDK) installed on your machine.
2. Copy the code into a file named SimpleGuiApp.java.
3. Open a terminal or command prompt and navigate to the directory where you saved the file.
4. Compile the program using:
javac SimpleGuiApp.java
5. Run the program using:
java SimpleGuiApp
This will open a GUI window where you can enter text, click the "Submit" button, and see your entered
text appear in the text area below.