Java GUI Toolkits and Your First JFrame: AWT, Swing and JavaFX
Where Java desktop GUIs stand today: AWT peers, painted Swing components, JavaFX and OpenJFX, then a first Swing window: JFrame, the event dispatch thread, close operations, frame properties, the content pane, paintComponent, preferred sizes, pack and headless mode.
kvi5hnuCode Sprout team member13 min readOn this page
Most programs people use today run in a browser or on a phone, but desktop applications are far from dead: IDEs such as IntelliJ IDEA, database tools, scientific and trading applications, and countless internal company tools are Java desktop programs. Graphics code also matters on servers, where the same APIs render charts, thumbnails and reports into image files. This part of the course covers Java's standard toolkit for both, Swing and the AWT, starting with how they came about and how to put a first window on the screen.
A short history of Java GUI toolkits
AWT (1996). Java 1.0 shipped the Abstract Window Toolkit. Each AWT component (a button, a text field) was backed by a peer: the native widget of the operating system. That gave programs the native look, but behavior differed in subtle ways between Windows, macOS and the Unix toolkits, and the library could only offer what every platform had in common. Developers joked about "write once, debug everywhere."
Swing (1998). Netscape had built a library that took the opposite approach: ask the operating system only for a blank window, and paint every button, menu and scroll bar yourself. Sun and Netscape developed this idea into Swing, which became part of Java 1.2. Swing components look and behave the same everywhere, and a pluggable look and feel can imitate the native style or provide a cross-platform one. Swing does not replace the AWT; it is built on top of it. Windows, event handling and the drawing API are still AWT classes.
JavaFX (2007 onwards). Sun introduced JavaFX with its own scripting language to compete with Adobe Flash; it did not catch on. JavaFX 2 (2011) became an ordinary Java API with a scene graph, CSS styling, animation, and hardware-accelerated rendering, and it was bundled with Oracle's JDK from 7u6 through Java 10 (OpenJDK builds generally did not include it). Since Java 11, JavaFX has been a separate open-source project, OpenJFX, released on the same six-month schedule as the JDK (JavaFX 25 accompanies JDK 25). You add it as a dependency, like any library.
Where things stand now. Swing and the AWT remain part of every JDK in the java.desktop module and are maintained: Java 9 added proper high-DPI scaling (JEP 263) and APIs for taskbars, dock icons and desktop integration (JEP 272). Applets are gone: the browser plugin and Java Web Start disappeared years ago, and the Applet API itself was removed in Java 26 (JEP 504). Alternatives outside the JDK include JavaFX, Eclipse SWT (native widgets) and Compose Multiplatform (Kotlin). Modern-looking Swing applications often use a third-party look and feel such as FlatLaf.
This course uses Swing: it comes with every JDK and its concepts (components, layout, events, painting) carry over to the other toolkits.
A first window
A top-level window, one that is not inside another window, is a frame, class JFrame. Here is a complete program that shows one:
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class FirstWindow {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
var frame = new JFrame("First Window");
frame.add(new GreetingComponent()); // goes into the content pane
frame.pack(); // size the frame to its content
frame.setIconImage(makeIcon());
frame.setLocationByPlatform(true); // let the OS choose a position
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
static Image makeIcon() {
var img = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = img.createGraphics();
g.setColor(new Color(0x2563EB));
g.fillRoundRect(2, 2, 28, 28, 8, 8);
g.dispose();
return img;
}
}
class GreetingComponent extends JComponent {
private static final long serialVersionUID = 1L;
@Override protected void paintComponent(Graphics g) {
g.drawString("Drawn by paintComponent, not a label", 40, 100);
}
@Override public Dimension getPreferredSize() {
return new Dimension(320, 200);
}
}
Run it with java FirstWindow.java on a machine with a display. The rest of this section explains each part.
The event dispatch thread
Swing is not thread-safe. All work with Swing components (creating them, changing them, reading their state) must happen on a single thread, the event dispatch thread (EDT), which also delivers mouse clicks and key presses. EventQueue.invokeLater(runnable) (or the equivalent SwingUtilities.invokeLater) puts a task on that thread's queue and returns at once. invokeAndWait waits for the task to finish.
Creating the user interface on the main thread usually seems to work, which is why old examples do it, but as Swing grew more complex the JDK developers stopped guaranteeing that it is safe. Rare, unreproducible glitches are the result. Always start your UI with invokeLater.
Once main has scheduled that task, it returns, but the program keeps running: the EDT is alive as long as a window is displayable. Long-running work such as a network call or a big computation must not run on the EDT, or the whole interface freezes. Part 11 shows how to hand such work to a background thread (with SwingWorker) and send results back.
Closing the frame
setDefaultCloseOperation decides what happens when the user clicks the close button:
| Constant | Effect |
|---|---|
HIDE_ON_CLOSE (default) | The frame becomes invisible; the program keeps running. |
DISPOSE_ON_CLOSE | The frame is hidden and its native resources are released. When the last window is disposed and no other non-daemon threads run, the JVM exits. |
EXIT_ON_CLOSE | Calls System.exit(0). Fine for a single-window application. |
DO_NOTHING_ON_CLOSE | Nothing happens automatically; a window listener can ask "Save changes?" first. |
Frame properties
Frames start out invisible, which lets you add components and set them up before calling setVisible(true). The methods for size and position mostly come from the superclasses: JFrame extends Frame, which extends Window, Container and finally Component, the root of all AWT and Swing components.
setSize(w, h),setLocation(x, y)andsetBounds(x, y, w, h)set size and position in pixels; the screen origin (0, 0) is the top-left corner.setLocationByPlatform(true)lets the windowing system choose a position, usually cascading new windows.setLocationRelativeTo(null)centers the frame on the screen.setTitle,setResizable,setIconImage(orsetIconImageswith several sizes),setUndecorated(no title bar), andsetExtendedState(Frame.MAXIMIZED_BOTH).Toolkit.getDefaultToolkit().getScreenSize()returns the primary screen size. With several monitors, askGraphicsEnvironment.getLocalGraphicsEnvironment()for its screen devices, or usegetMaximumWindowBounds()for the area not covered by task bars.
These getter/setter pairs are called properties: getTitle/setTitle form the title property of type String. For boolean properties the getter starts with is, as in isResizable/setResizable. GUI builders and the JavaBeans Introspector discover properties from these method names, as the demo shows.
Sizes are in logical pixels. On a high-resolution display with 200% scaling, a 320×200 frame occupies 640×400 physical pixels, and Swing scales its drawing automatically.
Drawing inside a frame
A JFrame is a surprisingly layered object. Its border and title bar come from the operating system. Inside, a JRootPane holds a JLayeredPane (containing the optional menu bar and the content pane) and, on top of everything, an invisible glass pane:

Everything you add to the frame goes into the content pane: frame.add(c) is shorthand for frame.getContentPane().add(c). The content pane uses a BorderLayout, so a single component added this way fills it. The other panes matter only for special tasks: the glass pane can intercept mouse input or draw an overlay over all components.
To draw something, do not paint on the frame itself. Write a class that extends JComponent (or JPanel, which also fills its background) and override paintComponent(Graphics g). The Graphics object carries the current color, font and clipping area, and has methods to draw shapes, text and images (the next article covers them). Coordinates in paintComponent are relative to the component, with (0, 0) at its top-left corner.
Two rules for painting:
- Never call
paintComponentyourself. Swing calls it whenever the component needs to be redrawn: when the window first appears, when it is resized, when it is uncovered by another window, when it is restored. The pixels of a window are not saved, so your method must always be able to draw everything from the component's current state. - To request a redraw, call
repaint(). It schedules a paint; several requests in quick succession are merged.
A component should also report how large it would like to be by overriding getPreferredSize(). Then frame.pack() sizes the frame so that the content pane gets the preferred sizes of its contents, which is better than guessing pixel sizes with setSize.
Java 25 shortcuts
With compact source files and module imports (both final in Java 25), small GUI programs get shorter: void main() instead of the public static form, and import module java.desktop; instead of several package imports. One snag: the module import brings in both java.awt.List and, through the automatic import of java.base, java.util.List, so a plain List becomes ambiguous ("reference to List is ambiguous"). Add import java.util.List;, since a single-type import wins over module imports.
Headless mode
Many machines have no display: servers, containers, build agents, and the judge that runs the programs in this course. There the AWT runs in headless mode, which you can also force with -Djava.awt.headless=true or by setting that system property before any AWT class is used. In headless mode, windows cannot be created (new JFrame() throws HeadlessException), but nearly everything else works: lightweight Swing components can be created, laid out and painted into an image, and the whole drawing API is available. That is how servers generate charts and thumbnails, and how GUI code is unit-tested.
The program
The demo works in headless mode. It confirms that a frame cannot be created without a display, prints the class hierarchy of JFrame and JPanel, lists a few frame properties found by the JavaBeans introspector, examines the panes inside a JRootPane, compares the main thread with the EDT, lays out a custom component the way pack() would, and paints it into an image, which it prints as text, one character per pixel.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.beans.*;
import java.util.*;
import javax.swing.*;
public class Solution {
/** A component that paints itself: the Swing way to put content in a window. */
static class BadgeComponent extends JComponent {
private static final long serialVersionUID = 1L;
@Override protected void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.drawRect(2, 1, 35, 9); // outline
g.fillOval(6, 3, 6, 6); // a "light"
g.fillRect(16, 5, 18, 2); // a "slider"
}
@Override public Dimension getPreferredSize() { return new Dimension(40, 12); }
}
static void printAscii(BufferedImage img) {
for (int y = 0; y < img.getHeight(); y++) {
var line = new StringBuilder();
for (int x = 0; x < img.getWidth(); x++)
line.append((img.getRGB(x, y) & 0xFFFFFF) == 0 ? '#' : '.');
System.out.println(line);
}
}
static String chain(Class<?> c) {
var names = new ArrayList<String>();
for (; c != null; c = c.getSuperclass()) names.add(c.getName());
return String.join(" -> ", names);
}
public static void main(String[] args) throws Exception {
System.setProperty("java.awt.headless", "true"); // this demo runs without a display
System.out.println("== Running without a screen ==");
System.out.println("headless: " + GraphicsEnvironment.isHeadless());
try {
new JFrame("Hello");
} catch (HeadlessException e) {
System.out.println("new JFrame(...) -> HeadlessException (windows need a display)");
}
System.out.println("\n== Where JFrame comes from ==");
System.out.println(chain(JFrame.class));
System.out.println(chain(JPanel.class));
System.out.println("\n== Properties: get/set (and is) method pairs ==");
var wanted = Set.of("title", "resizable", "defaultCloseOperation", "iconImage", "locationByPlatform", "visible");
for (PropertyDescriptor pd : Introspector.getBeanInfo(JFrame.class).getPropertyDescriptors())
if (wanted.contains(pd.getName()))
System.out.printf("%-22s %-8s get: %-24s set: %s%n", pd.getName(), pd.getPropertyType().getSimpleName(),
pd.getReadMethod() == null ? "-" : pd.getReadMethod().getName(),
pd.getWriteMethod() == null ? "-" : pd.getWriteMethod().getName());
System.out.println("\n== The panes inside every JFrame (a JRootPane) ==");
var root = new JRootPane();
root.setJMenuBar(new JMenuBar());
System.out.println("root pane children: " + Arrays.stream(root.getComponents()).map(c -> c.getClass().getSimpleName()).toList());
System.out.println("layered pane holds: " + Arrays.stream(root.getLayeredPane().getComponents()).map(c -> c.getClass().getSimpleName()).toList());
System.out.println("content pane: " + root.getContentPane().getClass().getSimpleName()
+ ", uses a BorderLayout: " + (root.getContentPane().getLayout() instanceof BorderLayout));
System.out.println("glass pane visible: " + root.getGlassPane().isVisible());
System.out.println("\n== The event dispatch thread ==");
System.out.println("main thread is EDT? " + SwingUtilities.isEventDispatchThread());
var badge = new BadgeComponent[1];
var img = new BufferedImage[1];
EventQueue.invokeAndWait(() -> {
System.out.println("inside invokeAndWait: EDT? " + SwingUtilities.isEventDispatchThread()
+ ", thread " + Thread.currentThread().getName());
// Build and lay out components on the EDT, as for a real window
badge[0] = new BadgeComponent();
var content = new JPanel(new BorderLayout());
content.add(badge[0], BorderLayout.CENTER);
content.setSize(content.getPreferredSize()); // what pack() does for a frame
content.doLayout();
System.out.println("preferred size: " + content.getPreferredSize().width + "x" + content.getPreferredSize().height
+ ", badge bounds: " + badge[0].getBounds());
img[0] = new BufferedImage(40, 12, BufferedImage.TYPE_INT_RGB);
Graphics2D g = img[0].createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 40, 12);
badge[0].paint(g); // render offscreen instead of on screen
g.dispose();
});
System.out.println("\n== What paintComponent drew (40 x 12 pixels) ==");
printAscii(img[0]);
}
}
== Running without a screen ==
headless: true
new JFrame(...) -> HeadlessException (windows need a display)
== Where JFrame comes from ==
javax.swing.JFrame -> java.awt.Frame -> java.awt.Window -> java.awt.Container -> java.awt.Component -> java.lang.Object
javax.swing.JPanel -> javax.swing.JComponent -> java.awt.Container -> java.awt.Component -> java.lang.Object
== Properties: get/set (and is) method pairs ==
defaultCloseOperation int get: getDefaultCloseOperation set: setDefaultCloseOperation
iconImage Image get: getIconImage set: setIconImage
locationByPlatform boolean get: isLocationByPlatform set: setLocationByPlatform
resizable boolean get: isResizable set: setResizable
title String get: getTitle set: setTitle
visible boolean get: isVisible set: setVisible
== The panes inside every JFrame (a JRootPane) ==
root pane children: [JPanel, JLayeredPane]
layered pane holds: [JPanel, JMenuBar]
content pane: JPanel, uses a BorderLayout: true
glass pane visible: false
== The event dispatch thread ==
main thread is EDT? false
inside invokeAndWait: EDT? true, thread AWT-EventQueue-0
preferred size: 40x12, badge bounds: java.awt.Rectangle[x=0,y=0,width=40,height=12]
== What paintComponent drew (40 x 12 pixels) ==
........................................
..####################################..
..#..................................#..
..#..................................#..
..#....#####.........................#..
..#....#####....##################...#..
..#...######....##################...#..
..#....#####.........................#..
..#....#####.........................#..
..#..................................#..
..####################################..
........................................
Points to notice:
JFramederives from the AWT classesFrameandWindow, whileJPanelderives fromJComponent. Top-level windows are "heavyweight" (they have a native window); everything inside is "lightweight" and painted by Swing.- The content pane uses a
BorderLayout, which is why a single added component stretched to the full 40×12 area. paintwas called directly here only because we render into our own image. In a visible window, Swing calls it.
Common questions
Is Swing still worth learning in 2026? For desktop tools, internal applications and maintaining existing software, yes: it ships with every JDK, is stable and well documented, and large applications such as IntelliJ IDEA are built on it. For new consumer-facing desktop apps, JavaFX or a web front end are also common choices. The concepts (components, layouts, events, painting, the UI thread) transfer to all of them.
Swing or JavaFX for a new project? JavaFX has a modern scene graph, CSS styling, animations and better media support, but is a separate dependency. Swing has no dependencies and a vast ecosystem of components and look-and-feels. For simple tools, Swing with FlatLaf is the lowest-friction option.
How do I make Swing look modern?
Use a look and feel such as FlatLaf (FlatLightLaf.setup() before creating components), or the system look and feel with UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()). Set it before creating any component.
Why does my window appear but stay blank or freeze?
Usually because long-running code runs on the event dispatch thread, or the UI was built off the EDT. Build the UI in invokeLater, and move slow work to a SwingWorker or another thread.
How do I package a Swing app for users?
jpackage (Java 16+) creates native installers (.dmg, .msi, .deb) with a bundled, trimmed runtime, so users don't need Java installed. For simple cases, an executable JAR with Main-Class in the manifest also works.
Why does my program print HeadlessException?
It ran without a display (a server, a container, SSH without X forwarding, or -Djava.awt.headless=true), and tried to create a window. Drawing into images still works headless.
API reference
| Class / method | Purpose |
|---|---|
EventQueue.invokeLater(r), invokeAndWait(r), SwingUtilities.isEventDispatchThread() | Run code on the EDT. |
new JFrame(title), setVisible, setDefaultCloseOperation | Create, show and configure closing. |
add(component), getContentPane(), setJMenuBar, getGlassPane() | Content and panes. |
pack(), setSize, setLocation, setBounds, setLocationByPlatform, setLocationRelativeTo | Size and position. |
setTitle, setResizable, setIconImage(s), setUndecorated, setExtendedState | Frame properties. |
Toolkit.getDefaultToolkit().getScreenSize() | Primary screen size. |
GraphicsEnvironment.isHeadless(), getMaximumWindowBounds(), getScreenDevices() | Display environment. |
JComponent.paintComponent(Graphics) | Override to draw; called by Swing. |
Component.repaint() | Request a redraw. |
Component.getPreferredSize() | Override to report a preferred size. |
Summary
- The AWT wraps native widgets; Swing paints its own components on top of AWT windows and events; JavaFX is a separate, modern toolkit distributed as OpenJFX. Applets are history (API removed in Java 26).
- Create and change Swing components only on the event dispatch thread; start the UI with
EventQueue.invokeLater, and keep slow work off the EDT. - A
JFramestarts invisible; choose a close operation, set its properties, add components to the content pane, callpack(), thensetVisible(true). - Draw by overriding
paintComponentin aJComponentsubclass; never call it yourself, callrepaint()instead. Report sizes withgetPreferredSize. - In headless mode, windows are unavailable but components and drawing work, which is how servers render images.
Practice Questions
1. A program builds its JFrame directly in main, without invokeLater, and works fine on the developer's machine. Why should it still be changed?
Swing components are not thread-safe and must be created and accessed only on the event dispatch thread. Building the UI on the main thread while the EDT may already be delivering events (for example, the first paint) creates a race. It usually works, but it can cause rare, timing-dependent failures on other machines. Wrapping the construction in EventQueue.invokeLater removes the race at no cost.
2. A user closes the only window of an application and the process keeps running in the background. What is the likely cause, and what are two fixes?
The default close operation is HIDE_ON_CLOSE, which only makes the frame invisible; the window stays displayable, so the AWT keeps the JVM alive. Fix it with setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE), or with DISPOSE_ON_CLOSE, which releases the window so that the JVM can exit once no displayable windows and no other non-daemon threads remain.
3. Why does a component need to redraw everything in paintComponent every time, instead of just drawing what changed?
The windowing system does not keep a copy of the window's pixels. When the window is resized, uncovered or restored, the affected area is blank and Swing calls paintComponent to fill it in again. The method therefore has to be able to reproduce the entire appearance from the component's state. To show a change, update the state and call repaint().
4. What is the difference between setSize(400, 300) and pack() for a frame?
setSize fixes the outer size of the frame in pixels, including the title bar and border, regardless of what is inside; on another platform or font size the content may be cut off or have empty space. pack() asks the layout managers for the preferred sizes of the components and sizes the frame to fit them exactly, adding whatever the decorations need. Prefer pack() and have components report their preferred sizes.
5. A server process renders PNG charts with Java 2D and crashes with HeadlessException after moving into a container. What happened, and what should it do?
The code (or a library it uses) touches something that needs a display, such as creating a JFrame or a dialog, or querying the screen size. In a container there is no display, so the AWT runs headless and such calls throw. Server-side rendering should draw into a BufferedImage using Graphics2D and lightweight components only, never windows, and run with -Djava.awt.headless=true so the behavior is the same on every machine.
Previous: Public Key Encryption in Java: RSA, Hybrid Encryption and ML-KEM
Next: Drawing with Java 2D: Shapes, Colors, Fonts and Images
Related reading
- Public Key Encryption in Java: RSA, Hybrid Encryption and ML-KEM
- Symmetric Encryption in Java: AES-GCM, Key Generation and Cipher Streams
- Certificates in Java: keytool, Certificate Chains and Signing JAR Files
- Digital Signatures in Java: Signing and Verifying with RSA, EdDSA and ML-DSA
- Message Digests and Password Hashing in Java: SHA-2, SHA-3 and PBKDF2

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.