Java › Swing

Build Swing light and dark themes from Figma tokens

Use Figma color tokens in Swing’s built-in controls and custom buttons. Compare both palettes with a design snapshot and render them side by side.

Build Swing light and dark themes from Figma tokens

I mapped Figma’s color tokens to a Swing palette for each theme. Standard controls read shared defaults from UIManager, and custom controls use the palette when they paint.

These examples use Java 17, Metal, and the palette from the RSIS refactor-v2 branch.

Keep color roles stable across themes

In the light theme, a primary button and a focus border both use #176346. The dark theme uses #21825b for the button fill and #4ac991 for focus. I gave each role its own token so a change to the focus border doesn’t also change the button. Figma values checked into RSIS

Figma variableJava accessorLightDark
color/surface/canvassurface().canvas()#f4f6f2#101915
color/text/primarytext().primary()#162820#eef4f0
color/border/focusborder().focus()#176346#4ac991
color/action/primaryaction().primary()#176346#21825b

AppPalette groups related values in records, such as Surface, Text, and Border. A component can ask for palette.border().focus() without knowing which theme it is rendering. AppTheme.of() selects the palette and adds typography, elevation, and the translucent focus ring. The ring derives its RGB channels from the focus border and sets the alpha channel to 0x3d. AppPalette · AppTheme.of

Install defaults for standard Swing controls

AppThemeDefaults.install() writes roles to the keys read by Swing’s UI delegates. For example, it sets Panel.background from the canvas color and uses the panel surface for text-field and list backgrounds. List and table selection backgrounds get their own token. I use the same Metal Look and Feel on each platform so those keys reach a consistent set of delegates. Check the keys and component states again if you install a different Look and Feel. AppThemeDefaults

I wrap colors and fonts in ColorUIResource and FontUIResource. Both classes implement UIResource, which marks a value the UI delegate can replace when it installs its defaults. A color set directly on a component can persist as an override. Once I’ve set the new defaults, I call SwingUtilities.updateComponentTreeUI(...) to refresh the delegates in the existing window. A custom component that stores a palette in a field needs to receive the new palette separately. JDK 17 UIManager · JDK 17 UIResource

Pass the same palette to custom paint code

RsisButton computes its style from the button tone and ButtonModel. A primary button pulls its normal fill from action().primary() and its rollover or pressed fill from action().hover(). A disabled button uses the disabled surface and muted text colors. Keyboard focus adds an outline and a ring. Swing still manages the button state, and the paint method uses that state to choose the colors. RsisButton style and paint methods

Control or requirementWhere I apply the palette
A stock field or list drawn by a Swing delegateSet the relevant UIManager keys
A custom control with its own shapes and focus ringPass the palette to the control and repaint it
A utility where native appearance is the priorityStart with the system Look and Feel

Save this demo as PaletteDemo.java and run java PaletteDemo.java on a machine with a display. Use Switch theme to see how the standard text field and the painted button get their colors. Press Tab until Apply has focus to inspect its outline.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.metal.MetalLookAndFeel;

public class PaletteDemo {
    record Palette(Color canvas, Color panel, Color text, Color action, Color focus) {}

    static final Palette LIGHT = palette(0xf4f6f2, 0xffffff, 0x162820, 0x176346, 0x176346);
    static final Palette DARK = palette(0x101915, 0x17241e, 0xeef4f0, 0x21825b, 0x4ac991);

    public static void main(String[] args) {
        SwingUtilities.invokeLater(PaletteDemo::open);
    }

    private static void open() {
        try {
            UIManager.setLookAndFeel(new MetalLookAndFeel());
        } catch (UnsupportedLookAndFeelException e) {
            throw new IllegalStateException(e);
        }
        install(LIGHT);

        JButton toggle = new JButton("Switch theme");
        JTextField field = new JTextField("Restaurant name", 16);
        PaintedButton button = new PaintedButton();
        JFrame frame = new JFrame("Swing palette demo");
        JPanel root = new JPanel(new FlowLayout(FlowLayout.LEFT, 12, 12));
        root.add(new JLabel("Search"));
        root.add(field);
        root.add(button);
        root.add(toggle);

        frame.setContentPane(root);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        toggle.addActionListener(e -> {
            Palette palette = button.palette == LIGHT ? DARK : LIGHT;
            install(palette);
            SwingUtilities.updateComponentTreeUI(frame);
            button.apply(palette);
        });

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    static void install(Palette palette) {
        UIManager.put("Panel.background", new ColorUIResource(palette.canvas()));
        UIManager.put("Label.foreground", new ColorUIResource(palette.text()));
        UIManager.put("TextField.background", new ColorUIResource(palette.panel()));
        UIManager.put("TextField.foreground", new ColorUIResource(palette.text()));
        UIManager.put("TextField.caretForeground", new ColorUIResource(palette.text()));
    }

    private static Palette palette(int canvas, int panel, int text, int action, int focus) {
        return new Palette(new Color(canvas), new Color(panel), new Color(text),
                new Color(action), new Color(focus));
    }

    static final class PaintedButton extends JButton {
        private Palette palette = LIGHT;

        PaintedButton() {
            super("Apply");
            setBorder(BorderFactory.createEmptyBorder(8, 14, 8, 14));
            setContentAreaFilled(false);
            setOpaque(false);
            setFocusPainted(false);
            addActionListener(e -> setText("Applied"));
            apply(LIGHT);
        }

        void apply(Palette next) {
            palette = next;
            setForeground(Color.WHITE);
            repaint();
        }

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D copy = (Graphics2D) g.create();
            try {
                copy.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
                copy.setColor(palette.action());
                copy.fillRoundRect(1, 1, getWidth() - 2, getHeight() - 2, 10, 10);
                if (isFocusOwner()) {
                    copy.setColor(palette.focus());
                    copy.setStroke(new BasicStroke(2));
                    copy.drawRoundRect(2, 2, getWidth() - 4, getHeight() - 4, 10, 10);
                }
            } finally {
                copy.dispose();
            }
            super.paintComponent(g);
        }
    }
}

The demo lets you switch themes while the window is open so you can see both updates. In this RSIS revision, the app reads -Drsis.theme=LIGHT|DARK|SYSTEM before it creates the window. The OS theme detection article shows how RSIS selects a palette at startup. RSIS startup

Compare 37 tokens and both rendered screens

The Figma snapshot is a TSV with one row per token and a column for each theme. AppPaletteFigmaSyncTest expects 37 roles. For each role it finds the matching Java accessor and compares both colors, including the alpha channel for translucent overlays. On a mismatch, the assertion reports the variable, theme, expected color, and actual color. Palette snapshot test

I also check the rendered screen, where it’s easier to spot a selected row using the wrong token. The Explore gallery draws both themes with the same data at 1440×920. That puts the cards, search field, and list controls in the same places for comparison. I use these PNGs again in the GitHub screenshot article. Explore gallery

1
2
./gradlew test --tests org.example.rsis.ui.theme.AppPaletteFigmaSyncTest
./gradlew exploreGallery

The RSIS Explore gallery in the light palette Figure 1. Explore in the light theme, with white result cards and a pale green selection.

The same RSIS Explore gallery with the dark palette applied Figure 2. The same Explore screen in the dark theme. The search field and list are darker, and a lighter border marks the selected row.

Before updating a theme

  • Compare roles with the design snapshot in both modes.
  • Update the Swing defaults and pass the new palette to custom controls on the EDT.
  • Check a selected row, a focused button, and a disabled input in each mode.
  • Recheck the UI delegate mappings when changing the base Look and Feel.
This post is licensed under CC BY 4.0 by the author.