16.1 AWT vs Swing
| Aspect | AWT | Swing |
|---|---|---|
| Components | Heavyweight (native OS peers) | Lightweight (drawn in Java) |
| Look & feel | Platform-dependent | Pluggable, consistent everywhere |
| Component set | Basic (Button, TextField) | Rich (JTable, JTree, JTabbedPane) |
| Package | java.awt | javax.swing |
| Naming | Button, Frame | JButton, JFrame (J-prefix) |
| MVC-based | No | Yes (separable model/view) |
Swing sits on top of AWT — events and layout managers still come from java.awt/java.awt.event.
16.2 Building a Window — JFrame, JPanel, Components
JFrame frame = new JFrame("My App"); // top-level window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // else app lingers!
frame.setSize(400, 250);
JPanel panel = new JPanel(); // container/canvas
panel.add(new JLabel("Name:"));
panel.add(new JTextField(15));
panel.add(new JButton("Submit"));
frame.add(panel);
frame.setVisible(true); // LAST: show it
Core components: JLabel (display), JTextField/JTextArea/JPasswordField (input), JButton, JCheckBox, JRadioButton (+ ButtonGroup for exclusivity), JComboBox (dropdown), JList, JMenuBar/JMenu/JMenuItem, JOptionPane (dialogs). A JFrame's content pane holds the components; frame.add(...) forwards to it.
Threading rule: Swing is single-threaded — all UI work belongs on the Event Dispatch Thread (EDT); launch with SwingUtilities.invokeLater(() -> createUI());. Long tasks on the EDT freeze the GUI (advanced-paper point).
16.3 Event Handling — The Delegation Model
Three actors: an event source (button) fires an event object (ActionEvent) to registered listeners (ActionListener). This delegation event model replaced Java 1.0's inheritance model — cleaner separation of UI and logic.
JButton btn = new JButton("Count");
btn.addActionListener(new ActionListener() { // anonymous class
@Override public void actionPerformed(ActionEvent e) { count++; }
});
btn.addActionListener(e -> label.setText("Clicks: " + (++count))); // lambda
| Listener | Event | Fired by |
|---|---|---|
| ActionListener | ActionEvent | Button click, Enter in text field |
| ItemListener | ItemEvent | Checkbox/combo selection |
| KeyListener | KeyEvent | keyPressed/Released/Typed |
| MouseListener | MouseEvent | click/press/release/enter/exit |
| WindowListener | WindowEvent | open/close/iconify |
| FocusListener | FocusEvent | focus gained/lost |
Adapter classes (MouseAdapter, WindowAdapter…) provide empty implementations of multi-method listeners so you override only what you need.
16.4 Layout Managers
| Layout | Arrangement | Default for |
|---|---|---|
| FlowLayout | Left→right, wraps like text | JPanel |
| BorderLayout | NORTH/SOUTH/EAST/WEST/CENTER (center stretches) | JFrame content pane |
| GridLayout | Equal-size rows × cols | Calculators, keypads |
| BoxLayout | Single row or column | Toolbars, forms |
| CardLayout | Stack of "cards", one visible | Wizards |
| GridBagLayout | Grid with weights/spans | Complex forms |
panel.setLayout(new GridLayout(4, 3, 5, 5)); — rows, cols, hgap, vgap. setLayout(null) enables absolute positioning (setBounds) — acceptable in exams, discouraged in practice.
16.5 Applet Lifecycle — Still on Papers
An applet was a Java program embedded in a web page, subclassing java.applet.Applet (or JApplet); no main — the browser drives it through five callbacks:
init() --> start() --> [paint(Graphics g)] --> stop() --> destroy()
once each visit whenever redraw leave page unload
- init() — once, on load: build UI, read
<param>tags viagetParameter("name"). - start() — after init and on every page revisit: resume animations/threads.
- paint(Graphics g) — whenever drawing is needed:
g.drawString("Hi", 20, 20); callrepaint()to request it (repaint → update → paint chain). - stop() — page hidden: pause work.
- destroy() — applet discarded: final cleanup.
Applet vs application: no main vs main; runs in browser/appletviewer sandbox vs JVM; lifecycle-driven vs sequential; restricted (no local file access) vs full privileges. Applets are removed from modern Java (deprecated Java 9, removed 17) — state this and examiners smile — but the lifecycle question persists, so memorize the five methods and diagram.
🎯 Exam Focus
- Differentiate AWT and Swing (any five points). Why are Swing components called lightweight?
- Explain the delegation event model with its three participants. Write the three ways to register an ActionListener (separate class, anonymous class, lambda).
- Compare FlowLayout, BorderLayout and GridLayout with diagrams. What is the default layout of JFrame and JPanel?
- Explain the applet life cycle with a neat diagram and the skeleton code of all five methods. Differentiate an applet from an application.
- Write a Swing program for a simple calculator with two text fields, +/−/×/÷ buttons and a result label using GridLayout.
- What is the Event Dispatch Thread? Why must Swing UIs be created via SwingUtilities.invokeLater?