Nearby lessons

121 of 125

Java - GUI with AWT and Swing

📌 What You Will Learn
  • What a GUI is and how Java makes windows
  • AWT vs Swing — the difference
  • Important components: Button, TextField, Label, etc.
  • Layout managers
  • Event handling — making buttons work
  • The modern replacement: JavaFX

GUI with AWT and Swing is a core concept of the Java language. This lesson explains What is GUI?, AWT vs Swing and Your First Window with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

What is GUI?

A GUI (Graphical User Interface) is the part of a program the user sees and clicks — windows, buttons, text boxes, menus. Before GUI, programs were command-line: you typed commands and got text. GUI made computers friendly.

Java has two classic GUI toolkits: AWT (old, uses operating system components) and Swing (newer, draws its own components). Both live in the java.awt and javax.swing packages.

AWT vs Swing

PointAWTSwing
Full formAbstract Window ToolkitSwing (part of Java Foundation Classes)
ComponentsUses OS components (heavyweight)Draws its own (lightweight)
Look & feelDepends on the operating systemSame everywhere (pluggable)
SpeedFaster (native)A little slower (Java-drawn)
RichnessFew componentsMany rich components (JTable, JTree)
MVC supportNoYes
Which to useLegacy onlyThe classic standard
In simple words: Swing draws its own components; AWT uses the operating system's. That is why a Swing window looks the same on every computer, while an AWT window changes its look with the OS.

Your First Window

That opens a simple resizable window with the title My First Window. setVisible(true) shows it; EXIT_ON_CLOSE makes the app close when you press the X.

In simple words: A `JFrame` is the window itself. You just create it, set its size, and make it visible — the components you add later sit inside it.
Example03
JCode Cell
1import javax.swing.*;
2 
3class FirstWindow {
4 public static void main(String[] args) {
5 JFrame frame = new JFrame("My First Window");
6 frame.setSize(400, 300);
7 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
8 frame.setVisible(true);
9 }
10}

Common Components

ComponentWhat it shows/does
JLabelA short text or picture (non-editable).
JTextFieldOne-line box where the user types text.
JPasswordFieldText field that hides the typed characters.
JButtonA clickable button.
JTextAreaMulti-line text area.
JCheckBoxA tick box (choose any number).
JRadioButtonA round button (choose only one).
JComboBoxA drop-down list.
JListA list of items.

A Form with Components

setBounds(x, y, width, height) places a component. The numbers are pixels from the top-left corner of the window.

Example05
JCode Cell
1import javax.swing.*;
2 
3class FormDemo {
4 public static void main(String[] args) {
5 JFrame frame = new JFrame("Student Form");
6 frame.setSize(400, 250);
7 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
8 frame.setLayout(null); // manual placement
9 
10 JLabel nameLbl = new JLabel("Name:");
11 nameLbl.setBounds(50, 40, 80, 25);
12 JTextField nameTxt = new JTextField();
13 nameTxt.setBounds(150, 40, 180, 25);
14 
15 JButton submit = new JButton("Submit");
16 submit.setBounds(150, 100, 100, 30);
17 
18 frame.add(nameLbl);
19 frame.add(nameTxt);
20 frame.add(submit);
21 
22 frame.setVisible(true);
23 }
24}

Layout Managers

Instead of manual positioning, layout managers arrange components automatically:

LayoutHow it arranges
FlowLayoutLeft to right, new row when space ends (default).
BorderLayoutFive regions: North, South, East, West, Center.
GridLayoutEqual-size grid of rows and columns.
GridBagLayoutMost powerful (and complex) flexible grid.
nullNo manager — you place everything manually.
In simple words: A layout manager arranges components automatically. You just say north, center or grid cell, and the manager does the positioning math for you.
Example06
JCode Cell
1import javax.swing.*;
2import java.awt.*;
3 
4class BorderLayoutDemo {
5 public static void main(String[] args) {
6 JFrame frame = new JFrame("Border Layout");
7 frame.setSize(400, 300);
8 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
9 
10 frame.setLayout(new BorderLayout());
11 frame.add(new JButton("NORTH"), BorderLayout.NORTH);
12 frame.add(new JButton("CENTER"), BorderLayout.CENTER);
13 frame.add(new JButton("SOUTH"), BorderLayout.SOUTH);
14 
15 frame.setVisible(true);
16 }
17}

Event Handling — Making Buttons Work

A button does nothing until we attach an event listener. The listener is an object that waits for the click and runs our code. This is where the anonymous inner class from Chapter 6 shows up in real life.

Trainer's Note: Every click makes the label count up. The ActionListener interface has one method, actionPerformed(ActionEvent e), which runs on every click. In modern code this is often written as a lambda: btn.addActionListener(e -> { ... }).
In simple words: A button does nothing until you attach a listener. The listener is an object whose actionPerformed method runs on every click and does the real work.
Example07
JCode Cell
1import javax.swing.*;
2import java.awt.event.*;
3 
4class ClickDemo {
5 public static void main(String[] args) {
6 JFrame frame = new JFrame("Click Counter");
7 frame.setSize(300, 150);
8 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
9 frame.setLayout(null);
10 
11 JButton btn = new JButton("Click me");
12 btn.setBounds(90, 30, 120, 40);
13 JLabel lbl = new JLabel("Clicks: 0");
14 lbl.setBounds(110, 80, 100, 30);
15 
16 // listener using an anonymous inner class
17 btn.addActionListener(new ActionListener() {
18 int count = 0;
19 public void actionPerformed(ActionEvent e) {
20 count++;
21 lbl.setText("Clicks: " + count);
22 }
23 });
24 
25 frame.add(btn);
26 frame.add(lbl);
27 frame.setVisible(true);
28 }
29}

Common Event Types

EventListenerWhen it fires
Button click / actionActionListenerWhen a button is pressed or Enter in a text field
Mouse move / clickMouseListenerWhen the mouse does something
Key pressKeyListenerWhen a key is typed
Window closeWindowListenerWhen the window opens/closes
Text changeDocumentListenerWhen text in a field changes

The Modern Replacement — JavaFX

Trainer's Note: Updated knowledge: Oracle stopped developing Swing features and moved Java desktop GUI to JavaFX. JavaFX has a scene graph, FXML styling, CSS support and hardware-accelerated graphics. However, most exam syllabuses and older projects still use Swing. Learn Swing for the basics, and if you love GUI work, move to JavaFX next. Also note: JavaFX is no longer bundled inside the JDK (since Java 11) — you download it separately.

CUI vs GUI — Question and Answer

The classic material begins the GUI chapter with this question. CUI = Character User Interface, GUI = Graphical User Interface.

PointCUIGUI
Full formCharacter User InterfaceGraphical User Interface
InteractionTyping commands and textClicking buttons, windows, menus
ExamplesCommand prompt, old DOS programsWindows, mobile apps
Ease of useDifficult for beginnersEasy and friendly
LooksOnly textColourful graphics and images

Java programs can be CUI (console programs like our earlier chapters) or GUI (AWT/Swing windows). The classic AWT program builds a Frame and adds components like Button and Label:

Example10
JCode Cell
1import java.awt.*;
2 
3class FirstAWT {
4 public static void main(String[] args) {
5 Frame f = new Frame("AWT Window");
6 f.setSize(300, 200);
7 f.setVisible(true);
8 }
9}
📝 Key Takeaways
  • GUI = windows and clickable components; AWT uses OS parts, Swing draws its own.
  • JFrame is the window; components like JLabel, JTextField, JButton go inside it.
  • Layout managers (Flow, Border, Grid) arrange components automatically.
  • Events need listeners: addActionListener runs code on a click.
  • Anonymous inner classes or lambdas provide the event code.
  • Modern GUI work uses JavaFX; Swing still appears in exams and legacy projects.

🧠 Test Your Knowledge

10 Questions
Progress: 0 / 10