Search code examples
javaswingcolorscustom-componentuimanager

Extend swing colors to custom components


Implementing swing applications, often you realize class of components that should have a coherent look.
Example: Mypanel that extends JPanel and represents an applicative object and thus having a yellow background with a darker yellow border line.
Is it possible to leverage the swing color management?
My idea is to put my colors into UIManager.getLookAndFeelDefaults map and then bind them to the component somehow.
This "somehow" is the question: how to do that in the simplest form?


Solution

  • Something like this should work if you want to customise just a few components:

    // Specify the colors
    UIDefaults uiDef = new UIDefaults();
    uiDef.put("Panel.background", Color.BLUE);
    
    // Use the colors on a specific component
    JPanel panel = new JPanel();
    panel.putClientProperty("Nimbus.Overrides", uiDef);
    SwingUtilities.updateComponentTreeUI(panel);
    

    See the Nimbus defaults for key-names and default colors and painters.