First Swing Application - potatoscript/JavaSwing GitHub Wiki

๐ŸŽจ Creating Your First Swing Application (VS Code) ๐Ÿ’ป

๐Ÿ“š Step 1: Prerequisites

๐Ÿ“ 1. Install Java Development Kit (JDK)

  1. ๐Ÿ” Check if JDK is Installed:

    • Open Command Prompt or Terminal.
    • Type:
    java -version
    
    • If JDK is installed, it should display something like:
    java version "17.0.1" 2023-10-12 LTS
    
    • If JDK is not installed, proceed to the next step.
  2. ๐Ÿ“ฅ Download and Install JDK:

    • Go to Oracle JDK Download Page.
    • Select the appropriate version for your operating system.
    • Follow the installation steps.

๐Ÿง‘โ€๐Ÿ’ป 2. Install Visual Studio Code (VS Code)

  1. ๐Ÿ“ฅ Download VS Code:

  2. ๐Ÿ—๏ธ Install VS Code:

    • Follow the installation instructions.
    • Launch VS Code after installation.

๐Ÿ”ฅ 3. Install Java Extension Pack in VS Code

  1. Open VS Code.
  2. Click on the Extensions icon (๐Ÿ“ฆ) on the left sidebar.
  3. Search for Java Extension Pack.
  4. Click Install to install the following essential extensions:
    • โœ… Java Extension Pack
    • โœ… Debugger for Java
    • โœ… Java Test Runner
    • โœ… Maven for Java
    • โœ… Java Language Support
  5. Wait for the installation to complete.

๐Ÿ“ Step 2: Setting Up Your Java Project in VS Code


๐Ÿ“š 1. Create a New Java Project

  1. Open VS Code.
  2. Press Ctrl + Shift + P to open the Command Palette.
  3. Type:
Java: Create Java Project
  1. Select Java: Create Java Project.
  2. Choose No Build Tools (for beginners).
  3. Select a folder where you want to create your project.
  4. Name the project MySwingApp.
  5. Click Create.

๐Ÿ“ 2. Create a Java Class

  1. Open your project folder in VS Code.
  2. Right-click on the src folder.
  3. Select New File and name it:
HelloSwing.java
  1. Open HelloSwing.java and add the following code:
import javax.swing.*;

public class HelloSwing {
    public static void main(String[] args) {
        // Set Look and Feel
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Create JFrame window
        JFrame frame = new JFrame("Hello Swing!");

        // Create JLabel with text
        JLabel label = new JLabel("๐Ÿ‘‹ Hello, Swing World!", SwingConstants.CENTER);

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

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

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

โ–ถ๏ธ Step 3: Run Your First Swing Application


๐Ÿš€ 1. Open the Terminal in VS Code

  • Press Ctrl + ` (or go to Terminal โ†’ New Terminal).
  • Make sure the terminal is in the project directory.
cd /path/to/MySwingApp

๐Ÿ“ฆ 2. Compile the Java File

  • Run the following command:
javac HelloSwing.java
  • If no errors appear, it means the code was successfully compiled. A HelloSwing.class file will be generated.

โ–ถ๏ธ 3. Run the Application

  • Run the application using:
java HelloSwing
  • A window will pop up with the text:
+----------------------------------+
|                                  |
|      ๐Ÿ‘‹ Hello, Swing World!      |
|                                  |
+----------------------------------+

๐ŸŽจ Step 4: Understanding Basic Swing Components


๐Ÿ“ Explanation of the Code

โœ… JFrame:

  • JFrame creates the main window of your application.
  • setSize(400, 200) sets the size of the window.
  • setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) closes the application when the window is closed.

โœ… JLabel:

  • JLabel displays text and images.
  • SwingConstants.CENTER centers the label content horizontally.

โœ… setLookAndFeel:

  • This changes the appearance of the application to match the systemโ€™s look.

โœ… setVisible(true):

  • This makes the frame visible on the screen.

๐Ÿ“š Common Swing Components Overview

Component Description Example Code
JFrame Main window new JFrame("Title")
JLabel Display text/icons new JLabel("Hello")
JButton Button for actions new JButton("Click Me")
JTextField Single-line text input new JTextField(20)
JTextArea Multi-line text input new JTextArea(5, 20)
JCheckBox Checkbox for options new JCheckBox("Accept")
JComboBox Dropdown list for selection new JComboBox(options)
JList List of selectable items new JList(items)
JPanel Container for grouping items new JPanel()
JMenuBar Menu bar for the application new JMenuBar()

๐ŸŽฎ Step 5: Adding a Button and Handling Events


๐Ÿ”ฅ Example: Button with Click Event

  1. Open HelloSwing.java and replace the code with:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

        // Create a JButton
        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);

        // Set frame properties
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

โ–ถ๏ธ 2. Compile and Run Again

  1. Compile:
javac HelloSwing.java
  1. Run:
java HelloSwing

๐Ÿ‘ฉโ€๐ŸŽจ Output:

+----------------------------+
|                            |
|   ๐ŸŽ‰ Click Me!              |
|                            |
+----------------------------+

Clicking the button shows:

๐ŸŽฏ Button Clicked!

๐ŸŽ Step 6: Create a JAR File and Run


๐Ÿ“ฆ 1. Compile and Create JAR File

  1. Compile the project:
javac HelloSwing.java
  1. Create a JAR file:
jar cfe HelloSwing.jar HelloSwing *.class

โ–ถ๏ธ 2. Run the JAR File

java -jar HelloSwing.jar

๐ŸŽ‰ Your Swing application will open in a window!


๐ŸŽจ Bonus: Customize Look and Feel


๐ŸŽจ 1. Set Native Look and Feel

Add the following code before creating Swing components:

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

๐ŸŽจ 2. Change Look and Feel Options

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)