RKTechGame | Introduction to AWT and Swing in Java

What is AWT (Abstract Window Toolkit)?

AWT Java ka ek purana GUI toolkit hai jisme platform-dependent components hote hain. Matlab ye components host operating system ke widgets par dependent hain. Isme buttons, labels, text fields jese basic GUI elements available hain.

What is Swing?

Swing Java ke liye ek advanced lightweight GUI toolkit hai. Ye pure Java me likha gaya hai aur platform independent hi look and feel deta hai. Swing me advanced components jaise tables, trees, tabbed panes, dialogs etc hote hain.

Difference Between AWT and Swing

Feature AWT Swing
Package java.awt javax.swing
Component Type Heavyweight (native peers) Lightweight (Java-based)
Platform Dependency Dependent on OS Platform-independent
Look and Feel Native OS look Customizable, pluggable
Execution Speed Relatively slower Faster
MVC Support No Yes
Advanced Components Limited Rich components like JTable, JTree, JTabbedPane

Simple AWT Example

import java.awt.*;
import java.awt.event.*;

public class AWTExample extends Frame {
  Label label;
  TextField textField;
  Button button;

  public AWTExample() {
    setLayout(new FlowLayout());

    label = new Label("Name:");
    textField = new TextField(20);
    button = new Button("Submit");

    add(label);
    add(textField);
    add(button);

    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("AWT Button clicked! Input: " + textField.getText());
      }
    });

    setTitle("AWT Example");
    setSize(300, 150);
    setVisible(true);
  }

  public static void main(String[] args) {
    new AWTExample();
  }
}

Simple Swing Example

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

public class SwingExample extends JFrame {
  JTextField textField;
  JButton button;

  public SwingExample() {
    setLayout(new FlowLayout());

    textField = new JTextField(20);
    button = new JButton("Submit");

    add(new JLabel("Name:"));
    add(textField);
    add(button);

    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("Swing Button clicked! Input: " + textField.getText());
      }
    });

    setTitle("Swing Example");
    setSize(300, 150);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
  }

  public static void main(String[] args) {
    new SwingExample();
  }
}