Applet with Swing Components
1. What Is Swing? (beginner upgrade!)
Swing (javax.swing) = pretty AWT replacement: JButton (vs Button!), JFrame (vs Frame!), JApplet (vs Applet!). Lightweight (Java-drawn, same everywhere!), pluggable look, more widgets (tables, trees!).
2. AWT vs Swing (exam table!)
| AWT | Swing | |
|---|---|---|
| Package | java.awt |
javax.swing (J-prefix!) |
| Weight | heavyweight (OS peers!) | lightweight (Java!) |
| Look | native (differs!) | same + LaF (Metal/Nimbus!) |
| Widgets | few | many (JTable, JTree!) |
| Close | manual listener! | setDefaultCloseOperation(EXIT_ON_CLOSE)! |
3. Code — Same App, Both Ways!
// AWT applet (old!)
import java.applet.Applet;
import java.awt.Button;
public class A extends Applet { public void init() { add(new Button("ok")); } }
// Swing applet (nicer!)
import javax.swing.*;
public class S extends JApplet { // JApplet!
public void init() { add(new JButton("ok")); } // J-prefix!
}
// Modern desktop (no browser!):
JFrame f = new JFrame("Hi");
f.add(new JButton("ok"));
f.setSize(250, 150);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // auto-close! (no listener!)
f.setVisible(true);
4. Traps
- Swing needs EDT for big apps (
SwingUtilities.invokeLater— viva point!). JAppletdeprecated too (like Applet!). Learn pattern, buildJFrame/JPanelreal!- Mix AWT + Swing heavy/light = paint bugs (avoid mixing!).
5. Exam Points
- AWT vs Swing table + program — 7 marks, very frequent.
- J-prefix + close-operation — 3 marks, frequent.