Search code examples
javaswingnimbusjseparator

How to change the color of a JSeparator using the Nimbus L&F


Here is what I've tried in my attempt to change a vertical JSeparator's color from Nimbus default black to red based on the answer in How to change the color of a JSeparator?:

public class TestFrame extends JFrame {

    public static void main(String[] args) {

        TestFrame frame = new TestFrame();
        frame.setSize(200, 200);
        frame.setLayout(new GridBagLayout());

        for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                try {
                    UIManager.setLookAndFeel(info.getClassName());
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InstantiationException ex) {
                    Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnsupportedLookAndFeelException ex) {
                    Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                break;
            }
        }
        UIManager.put("Separator.background", Color.red);
        UIManager.put("Separator.foreground", Color.red);

        JSeparator separator = new JSeparator(JSeparator.VERTICAL);
        separator.setPreferredSize(new Dimension(2, 100));
        separator.setForeground(Color.red);
        separator.setBackground(Color.red);

        frame.add(separator, new GridBagConstraints());
        frame.setVisible(true);

    }

}

Yet the vertical separator remains black. What should I be doing?

Note: I know Nimbus is the issue, because I tried without setting the L&F to Nimbus and this worked fine. Also to note that setting the Separator[Enabled].backgroundPainter property seems to have affected the JSeperator but not in the way I intended (just changed the background color vs the separating line color)


Solution

  • I resolved this by changing the nimbusBlueGrey color that Nimbus uses to derive other colors. Setting the separator to opaque will only help change the background color, but JSeperator's have 2 colors, a foreground and a background, so setting to opaque and changing the background color fixed half the problem. nimbusBlueGrey seems to handle the foreground color, which doesn't seem to be overridable with setForegroundcolor() or the Separator.foreground property.

    The problem is that changing nimbusBlueGrey will affect the color of many other components. I'm not sure how to contain the color change to just the JSeperator.