Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Lesson 16: GUI with Swing — Components, Events, Layouts & Applet Lifecycle

Lesson 17 of 18 in the free Programming in Java notes on Siksha Sarovar, written by Rohit Jangra.

16.1 AWT vs Swing

AspectAWTSwing
ComponentsHeavyweight (native OS peers)Lightweight (drawn in Java)
Look & feelPlatform-dependentPluggable, consistent everywhere
Component setBasic (Button, TextField)Rich (JTable, JTree, JTabbedPane)
Packagejava.awtjavax.swing
NamingButton, FrameJButton, JFrame (J-prefix)
MVC-basedNoYes (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
ListenerEventFired by
ActionListenerActionEventButton click, Enter in text field
ItemListenerItemEventCheckbox/combo selection
KeyListenerKeyEventkeyPressed/Released/Typed
MouseListenerMouseEventclick/press/release/enter/exit
WindowListenerWindowEventopen/close/iconify
FocusListenerFocusEventfocus gained/lost

Adapter classes (MouseAdapter, WindowAdapter…) provide empty implementations of multi-method listeners so you override only what you need.

16.4 Layout Managers

LayoutArrangementDefault for
FlowLayoutLeft→right, wraps like textJPanel
BorderLayoutNORTH/SOUTH/EAST/WEST/CENTER (center stretches)JFrame content pane
GridLayoutEqual-size rows × colsCalculators, keypads
BoxLayoutSingle row or columnToolbars, forms
CardLayoutStack of "cards", one visibleWizards
GridBagLayoutGrid with weights/spansComplex 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
  1. init() — once, on load: build UI, read <param> tags via getParameter("name").
  2. start() — after init and on every page revisit: resume animations/threads.
  3. paint(Graphics g) — whenever drawing is needed: g.drawString("Hi", 20, 20); call repaint() to request it (repaint → update → paint chain).
  4. stop() — page hidden: pause work.
  5. 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

  1. Differentiate AWT and Swing (any five points). Why are Swing components called lightweight?
  2. Explain the delegation event model with its three participants. Write the three ways to register an ActionListener (separate class, anonymous class, lambda).
  3. Compare FlowLayout, BorderLayout and GridLayout with diagrams. What is the default layout of JFrame and JPanel?
  4. Explain the applet life cycle with a neat diagram and the skeleton code of all five methods. Differentiate an applet from an application.
  5. Write a Swing program for a simple calculator with two text fields, +/−/×/÷ buttons and a result label using GridLayout.
  6. What is the Event Dispatch Thread? Why must Swing UIs be created via SwingUtilities.invokeLater?