πŸš€ Introduction to Swing in Java (Complete Guide with AWT vs Swing, Examples & Best Practices)


🌟 Introduction

In previous blogs, we explored AWT (Abstract Window Toolkit) and built basic GUI applications πŸͺŸ

πŸ‘‰ But AWT has some limitations:

  • Platform-dependent ❌
  • Limited components ❌
  • Less flexible ❌

To overcome these, Java introduced Swing 🎯

πŸ‘‰ Swing is a more powerful, flexible, and modern GUI toolkit built on top of AWT.


🧠 What is Swing?

πŸ‘‰ Swing is part of the javax.swing package and is used to create rich GUI applications.


πŸ”₯ Key Features of Swing

  • Platform-independent 🌍
  • Lightweight components ⚑
  • Rich set of components 🎨
  • Customizable Look & Feel 🎯

βš–οΈ AWT vs Swing (VERY IMPORTANT)


FeatureAWTSwing
Packagejava.awtjavax.swing
ComponentsHeavyweightLightweight
Look & FeelOS dependentPlatform independent
Components AvailableLimitedRich
CustomizationLessHigh

🧠 Key Understanding

πŸ‘‰ AWT uses native OS components
πŸ‘‰ Swing draws components itself (Java-based)


🧱 Basic Structure of Swing Program


βœ… First Swing Program (Complete Runnable Code)

import javax.swing.*;

public class FirstSwingApp {
    public static void main(String[] args) {

        JFrame frame = new JFrame("My First Swing App");

        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setVisible(true);
    }
}

πŸ” Explanation

  • JFrame β†’ main window πŸͺŸ
  • setSize() β†’ sets window size
  • setDefaultCloseOperation() β†’ closes program properly βœ…
  • setVisible(true) β†’ displays window

🧩 Swing Components


πŸ”Ή 1. JButton

import javax.swing.*;

public class ButtonSwing {
    public static void main(String[] args) {

        JFrame frame = new JFrame("Button Example");

        JButton button = new JButton("Click Me");

        frame.add(button);

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

πŸ” Explanation

  • JButton β†’ clickable button πŸ”˜
  • Works similar to AWT but more flexible

πŸ”Ή 2. JLabel

import javax.swing.*;

public class LabelSwing {
    public static void main(String[] args) {

        JFrame frame = new JFrame("Label Example");

        JLabel label = new JLabel("Welcome to Swing");

        frame.add(label);

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

πŸ”Ή 3. JTextField

import javax.swing.*;

public class TextFieldSwing {
    public static void main(String[] args) {

        JFrame frame = new JFrame("TextField Example");

        JTextField tf = new JTextField(15);

        frame.setLayout(new java.awt.FlowLayout());
        frame.add(tf);

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

πŸ› οΈ Mini Swing Application (Input + Processing)


πŸ§ͺ Even/Odd Checker in Swing

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

public class SwingEvenOdd {
    public static void main(String[] args) {

        JFrame frame = new JFrame("Even Odd Checker");
        frame.setLayout(new FlowLayout());

        JTextField tf = new JTextField(10);
        JButton btn = new JButton("Check");
        JLabel result = new JLabel("");

        frame.add(new JLabel("Enter Number:"));
        frame.add(tf);
        frame.add(btn);
        frame.add(result);

        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    int num = Integer.parseInt(tf.getText());

                    if (num % 2 == 0) {
                        result.setText("Even Number βœ…");
                    } else {
                        result.setText("Odd Number πŸ”₯");
                    }
                } catch (Exception ex) {
                    result.setText("Invalid Input ❌");
                }
            }
        });

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

πŸ” Explanation

  • Same logic as AWT
  • Better UI and control
  • setDefaultCloseOperation() removes need for WindowAdapter

⚠️ Common Mistakes Students Make


❌ Forgetting setDefaultCloseOperation()

πŸ‘‰ Window closes but program keeps running


❌ Mixing AWT and Swing improperly

πŸ‘‰ Can cause UI issues


❌ Not setting layout

πŸ‘‰ Components may overlap


❌ Forgetting setVisible(true)

πŸ‘‰ Window will not appear


🀯 Common Confusions


πŸ€” Why Swing is called Lightweight?

πŸ‘‰ Does NOT depend on OS components


πŸ€” Is Swing better than AWT?

πŸ‘‰ Yes β€” more flexible and powerful


πŸ€” Can we use AWT with Swing?

πŸ‘‰ Yes, but not recommended


πŸ’Ό Interview Questions


❓ What is Swing?

πŸ‘‰ Java GUI toolkit with lightweight components


❓ Difference between AWT and Swing?

πŸ‘‰ AWT β†’ Heavyweight
πŸ‘‰ Swing β†’ Lightweight


❓ What is JFrame?

πŸ‘‰ Top-level container in Swing


❓ Why Swing is platform-independent?

πŸ‘‰ Components are written in Java


🎯 Best Practices


βœ”οΈ Always use Swing over AWT
βœ”οΈ Use proper layouts
βœ”οΈ Handle events properly
βœ”οΈ Keep UI simple


🏁 Conclusion

Swing is the modern solution for GUI development in Java πŸš€

In this blog, you learned:

  • βœ”οΈ What Swing is
  • βœ”οΈ Differences between AWT and Swing
  • βœ”οΈ Swing components
  • βœ”οΈ Building real applications

πŸ’‘ Final Thought

πŸ‘‰ If AWT is the foundation,
πŸ‘‰ Swing is the real-world tool πŸ’ͺ


πŸ”₯ One-Line Summary

πŸ‘‰ β€œSwing provides powerful, flexible, and platform-independent GUI components in Java.”


πŸ’» Happy Coding! πŸ˜„

Next step: Event Delegation Model (deep dive) πŸ”₯

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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