Note: despite the original Turkish title mentioning JavaScript, this guide is about building graphical user interfaces in Java with the Swing library. This English version is an adapted summary of my Turkish study notes; the full notes and all original examples are available in the Turkish version.

What is a GUI?

A GUI (graphical user interface) is the visual layer between a program and its user. It lets people interact with software in an intuitive, user-friendly way, without needing technical knowledge of the computer. Every operating system tries to offer an interface that is both pleasant to look at and easy to use, so a developer who wants their software to have a good interface needs a solid grasp of GUI programming. You can either use the GUI classes and APIs provided by the platform, or go further and build your own drawing routines and interface system.

GUI example

AWT and Swing

Java offers two main libraries for GUIs: AWT (Abstract Window Toolkit) and Swing. AWT came first, but because it relied on native platform widgets, programs could look and behave inconsistently, or even fail, on different operating systems. That went against Java’s core promise of “write once, run anywhere.” Swing, introduced with Java 1.2, was built on top of AWT to fix this: its widgets are drawn by Swing itself rather than by the platform, so they behave the same everywhere. Swing still reuses parts of AWT, for example the java.awt.event package for event handling.

Swing architecture

Swing follows a Model-View-Controller (MVC) style: the model holds the data and logic, the view is the visual part, and the controller connects them (in Swing the line between model and controller is not always strict). Swing is built on two basic concepts:

  • Components: the visual building blocks, such as JLabel, JButton, JTextField, JComboBox, JRadioButton, JCheckBox, JToggleButton, JTable, JList, JScrollPane and JTabbedPane.
  • Containers: objects that hold components. Every component must live inside a container, so every GUI application has at least one. Containers can be nested; the outermost one (such as a JFrame) is the top-level container.

Swing components and containers
Swing class diagram

Creating a window with JFrame

JFrame is the main window. It holds your components and provides the basic window methods and events. A minimal example:

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class FrameDemo extends JFrame {
    public FrameDemo() {
        setTitle("FrameDemo");
        setSize(640, 480);
        setLocationRelativeTo(null);          // center on screen
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new FrameDemo().setVisible(true));
    }
}
  • setTitle(String) sets the window title.
  • setSize(int, int) sets the window size.
  • setLayout(LayoutManager) sets how components are arranged.
  • setVisible(true) shows the window (the default is false).
  • setDefaultCloseOperation(...) defines what happens when the window is closed.

JLabel

Labels display text or an image on the interface. They are mostly decorative, but with a MouseListener they can also act like buttons. The text on a label is drawn, not editable, so use a text field when the user needs to type.

JLabel example

Common constructors: JLabel(), JLabel(String text), JLabel(Icon image), and variants that also take a horizontal alignment.

JTextField

A single-line text input. Useful methods: setText() to set its content, getText() to read it, and setEditable(false) to make it read-only.

JTextField name = new JTextField(12);   // 12 columns wide
name.setText("Thank you");
String value = name.getText();

JButton

Buttons can have text, an icon, or both, and react to clicks through an ActionListener.

JButton button = new JButton("Continue");
button.addActionListener(e -> System.out.println("Clicked!"));
frame.add(button);

JComboBox

A drop-down list. You can add items one by one with addItem() or pass an array to the constructor, and preselect an item with setSelectedIndex().

String[] languages = {"C#", "C", "C++", "Java"};
JComboBox<String> combo = new JComboBox<>(languages);
combo.addItem("PHP");
combo.setSelectedIndex(3);   // "Java" is selected at startup

JRadioButton and JCheckBox

Radio buttons let the user pick exactly one option; group them with a ButtonGroup so that selecting one deselects the others. Check boxes are similar, but the user can select several at once. Use setSelected() and isSelected() to set and read their state.

JRadioButton linux = new JRadioButton("Linux");
JRadioButton windows = new JRadioButton("Windows");
ButtonGroup group = new ButtonGroup();
group.add(linux);
group.add(windows);

JCheckBox tea = new JCheckBox("Tea", true);
if (tea.isSelected()) { /* ... */ }

JToggleButton

A button that stays pressed after one click and is released with the next click. It can fire action, item and change events.

JTable

JTable shows data in rows and columns. The data usually comes from a table model, for example a DefaultTableModel built from a one-dimensional array of column names and a two-dimensional array of rows. Put the table in a JScrollPane so it can scroll.

String[] columns = {"No", "Name", "Surname"};
String[][] rows = {{"10", "Rıdvan", "Çakır"}, {"20", "Aykut", "Yılmaz"}};
JTable table = new JTable(new DefaultTableModel(rows, columns));
frame.add(new JScrollPane(table));

JPanel

Panels are separate areas inside a window, each with its own container and, if you like, its own layout, background color or border. They are ideal for splitting a window into regions such as top, bottom, left, right and center. Note that the coordinates of a component are relative to the panel that contains it, not to the window.

JPanel layout example

Ready-made dialogs: JOptionPane

For simple input, messages or warnings, you don’t need to design your own form: JOptionPane provides ready-made dialogs. showInputDialog() reads a string from the user, and showMessageDialog() displays a message. The message type (for example ERROR_MESSAGE, WARNING_MESSAGE or INFORMATION_MESSAGE) decides which icon is shown.

String input = JOptionPane.showInputDialog("Enter a number:");
JOptionPane.showMessageDialog(null,
    "Invalid input! The number must be between 1 and 9.",
    "Invalid input", JOptionPane.ERROR_MESSAGE);

JOptionPane input dialog
JOptionPane message types

Event-driven programming

Events are the foundation of visual applications: every action the user takes while the program runs, such as a mouse click or a key press, is an event. In Java, event handling has four parts:

  • Event source: the object that triggers the event (a button, the keyboard, the mouse).
  • Event object: carries information about what happened.
  • Event listener: an object registered to be notified when the event occurs.
  • Event handler: the method that runs in response.

Common event types include ActionEvent (e.g. a button click), AdjustmentEvent (scroll bars), ComponentEvent (a component is moved or resized), ContainerEvent (a component is added or removed), FocusEvent, ItemEvent, KeyEvent, MouseEvent, MouseWheelEvent, TextEvent and WindowEvent. Each has a matching listener interface, such as ActionListener, KeyListener, MouseListener, MouseMotionListener or WindowListener.

A simple keyboard example that shows the keys you press in a label:

public class KeyDemo extends JFrame implements KeyListener {
    private final JLabel label = new JLabel("Press a key");
    private String typed = "";

    public KeyDemo() {
        setBounds(10, 20, 600, 500);
        add(label);
        addKeyListener(this);
    }

    public void keyPressed(KeyEvent e) {
        typed += e.getKeyChar();
        label.setText(typed);
    }
    public void keyReleased(KeyEvent e) { }
    public void keyTyped(KeyEvent e) { }
}

Sources

The Turkish version lists the tutorials and books used while preparing these notes, including Java Yeni Başlayanlar İçin (Mehmet Kirazlı and Sezer Tanrıverdioğlu) and several Turkish Java tutorial sites.