javaswinglook-and-feeljslider

Painting the slider icon of JSlider


Would like to repaint the the marker or the thumb of the JSlider instead of the standard gray. How can I achieve this?


Solution

  • There are three ways:

    1. change Java Look and Feel, Preferred of Ways
    2. OverRide XxxSliderUI, but that would be Look and Feel sensitive, and not easy way
    3. learning The Synth Look and Feel

    Example using Synth

    Synth slider

    SynthSliderTest.java

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.plaf.synth.*;
    
    public class SynthSliderTest {
    
        private JFrame f = new JFrame();
    
        public SynthSliderTest() {
            try {
                SynthLookAndFeel laf = new SynthLookAndFeel();
                laf.load(SynthSliderTest.class.getResourceAsStream("yourPathTo/demo.xml"), SynthSliderTest.class);
                UIManager.setLookAndFeel(laf);
            } catch (Exception e) {
                e.printStackTrace();
            }
            f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            f.getContentPane().add(makeUI());
            f.setSize(320, 240);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        }
    
        public JComponent makeUI() {
            JSlider slider = new JSlider(0, 100);
            JPanel p = new JPanel();
            p.add(slider);
            return p;
        }
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    SynthSliderTest synthSliderTest = new SynthSliderTest();
                }
            });
        }
    }
    

    demo.xml file

    <?xml version="1.0" encoding="UTF-8"?>
    
    <synth>
        <style id="backingStyle">
            <opaque value="TRUE"/>
            <font name="Dialog" size="12"/>
            <state>
                <color value="WHITE" type="BACKGROUND"/>
                <color value="BLACK" type="FOREGROUND"/>
            </state>
        </style>
        <bind style="backingStyle" type="region" key=".*"/>
    
        <style id="SliderTrackStyle">
            <opaque value="TRUE"/>
            <state>
                <color type="BACKGROUND" value="ORANGE"/>
            </state>
        </style>
        <bind style="SliderTrackStyle" type="region" key="SliderTrack" />
    
        <style id="SliderThumbStyle">
            <opaque value="TRUE"/>
            <state>
                <color type="BACKGROUND" value="RED"/>
            </state>
            <state value="PRESSED">
                <color type="BACKGROUND" value="GREEN"/>
            </state>
        <!-- state value="MOUSE_OVER">
          <color type="BACKGROUND" value="BLUE"/>
        </state -->
        </style>
        <bind style="SliderThumbStyle" type="region" key="SliderThumb" />
    </synth>