How to change the color of a JSeparator?

11,131

Solution 1

have to change ’Background’ instead of ’Foreground’

logics could be different for Nimbus Look and Feel

Metal L&F

enter image description here

import javax.swing.*;
import java.awt.*;

public class GridBagSeparator1 {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Laying Out Components in a Grid");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JSeparator sep = new JSeparator(SwingConstants.HORIZONTAL);
        sep.setBackground(Color.black);
        JSeparator sep1 = new JSeparator(SwingConstants.HORIZONTAL);
        sep1.setBackground(Color.blue);
        JSeparator sep2 = new JSeparator(SwingConstants.HORIZONTAL);
        sep2.setBackground(Color.green);
        JSeparator sep3 = new JSeparator(SwingConstants.HORIZONTAL);
        sep3.setBackground(Color.red);

        frame.setLayout(new GridLayout(4, 0));
        frame.add(sep);
        frame.add(sep1);
        frame.add(sep2);
        frame.add(sep3);
        frame.pack();
        frame.setVisible(true);
    }
}

Solution 2

The JSeparator has 2 colors, one for the line, one for the shadow. You can change both, setting colors to the Background and the Foreground respectively.

JSeparator sep = new JSeparator();
sep.setForeground(Color.green); // top line color
sep.setBackground(Color.green.brighter()); // bottom line color
Share:
11,131
nathan
Author by

nathan

Updated on June 25, 2022

Comments

  • nathan
    nathan almost 2 years

    The question is in the title.

    I'm currently doing something like:

    jSperator = new JSeparator();
    jSeparator1.setForeground(new java.awt.Color(255, 51, 51));
    

    But the separator keep his default color, something like 212,212,212.

  • nathan
    nathan over 11 years
    Changing the background does not solve it. I'm using Matiss, the Netbeans GUI builder to build the interface on mac. Maybe it's a restriction of the look and feel.
  • trashgod
    trashgod over 11 years
    May need to use UIManager and change Separator.foreground
  • Béatrice Cassistat
    Béatrice Cassistat almost 11 years
    With Sythetica Look And Feel, I had to change the background AND set opaque property to true.