Introduction to Java Swing - potatoscript/JavaSwing GitHub Wiki

🎨 Introduction to Java Swing 🍵

🚀 What is Java Swing?

Java Swing is a GUI (Graphical User Interface) toolkit that allows you to create desktop applications using Java. It provides a set of ready-made components (like buttons, text fields, and tables) that help you build powerful and interactive user interfaces.

Why Use Swing?

  • 🖥️ Cross-Platform: Works on Windows, macOS, and Linux without modification.
  • 🎨 Customizable: You can change the look and feel easily.
  • Lightweight: Faster and more efficient compared to older GUI toolkits like AWT.
  • 🛠️ Rich Components: Provides a wide range of components such as buttons, labels, text fields, tables, and more.

🎯 Step 1: Setting Up Java Swing

📚 Requirements:

  1. 📝 Java Development Kit (JDK): Make sure you have JDK installed.
  2. 🖥️ IDE: We will use IntelliJ IDEA or Eclipse (recommended for beginners).

📥 Step 2: Install JDK

  1. 🔍 Check if JDK is Installed:

    • Open a terminal or command prompt.
    • Type:
    java -version
    
    • If JDK is installed, it will display the version. If not, proceed to the next step.
  2. 📦 Download and Install JDK:

    • Go to Oracle JDK Download Page.
    • Select the correct version for your operating system.
    • Install JDK following the on-screen instructions.

🧑‍💻 Step 3: Set Up Your IDE (IntelliJ/Eclipse)

🛠️ Option 1: IntelliJ IDEA

  1. 📥 Download IntelliJ IDEA:

  2. 🏗️ Install IntelliJ:

    • Follow the on-screen instructions.
    • Open IntelliJ and select New Project.
  3. 🎛️ Set Up a Java Project:

    • Select Java from the list.
    • Choose the correct JDK path.
    • Click Next and then Finish to create your project.

🛠️ Option 2: Eclipse

  1. 📥 Download Eclipse:

  2. 🏗️ Install Eclipse:

    • Follow the on-screen instructions.
    • Open Eclipse and choose a workspace.
  3. 🎛️ Set Up a Java Project:

    • Click on FileNewJava Project.
    • Name your project (e.g., SwingApp).
    • Click Finish.

📝 Step 4: Creating Your First Java Swing Application


🔥 Example 1: Basic Hello World GUI

import javax.swing.*;

public class HelloSwing {
    public static void main(String[] args) {
        // Create a new JFrame
        JFrame frame = new JFrame("Hello Swing!");

        // Create a JLabel to display text
        JLabel label = new JLabel("👋 Hello, Swing World!", SwingConstants.CENTER);

        // Add the label to the frame
        frame.add(label);

        // Set frame size and close operation
        frame.setSize(400, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Make the frame visible
        frame.setVisible(true);
    }
}

🎨 Explanation:

  • 🖥️ JFrame: Creates the main window.
  • 📝 JLabel: Displays text and icons.
  • 🔥 setSize: Sets the width and height of the window.
  • setDefaultCloseOperation: Closes the application when the window is closed.
  • 👀 setVisible(true): Displays the window.

👩‍🎨 Output:

+----------------------------------+
|                                  |
|      👋 Hello, Swing World!      |
|                                  |
+----------------------------------+

🧩 Step 5: Understanding Swing Components

📚 Basic Components:

Component Description Example
JButton Creates a clickable button. new JButton("Click Me!")
JLabel Displays text and icons. new JLabel("Hello World")
JTextField Input field to enter text. new JTextField(20)
JTextArea Multi-line text area. new JTextArea(5, 20)
JComboBox Dropdown menu. new JComboBox(options)
JList Displays a list of items. new JList(items)
JCheckBox Creates a checkbox. new JCheckBox("Accept Terms")

🕹️ Step 6: Handling Button Click Events

🔥 Example 2: Button with Click Event

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

public class ButtonExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Button Click Example");

        // Create a button
        JButton button = new JButton("Click Me! 🎉");

        // Add ActionListener to the button
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(frame, "🎯 Button Clicked!");
            }
        });

        // Add button to frame
        frame.add(button);
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

👩‍🎨 Explanation:

  • 🎛️ JButton: Creates a button.
  • 🎮 ActionListener: Handles button clicks.
  • 📢 JOptionPane: Displays a popup message.

👩‍💻 Output:

+----------------------------+
|                            |
|   🎉 Click Me!              |
|                            |
+----------------------------+

Clicking the button shows:

🎯 Button Clicked!

🎨 Step 7: Customizing Look and Feel

🖌️ Set Look and Feel:

try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
    e.printStackTrace();
}

🎨 Popular Look and Feel Options:

  • javax.swing.plaf.metal.MetalLookAndFeel
  • com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel
  • com.sun.java.swing.plaf.motif.MotifLookAndFeel
  • UIManager.getSystemLookAndFeelClassName() (Default system look)

🎁 Step 8: Packaging and Running Your Application

📦 Compile and Run:

  1. Open terminal or command prompt.
  2. Navigate to the folder where your Java file is saved.
  3. Compile:
javac HelloSwing.java
  1. Run:
java HelloSwing

📝 Create JAR File:

jar cvfe HelloSwing.jar HelloSwing *.class

🎓 Summary

🎉 You’ve learned:

  • What Java Swing is.
  • How to set up Java Swing in IntelliJ/Eclipse.
  • How to create basic GUI applications.
  • How to handle button clicks and customize appearance.