Java Swing How to - Change Thumb Icon for JSlider








Question

We would like to know how to change Thumb Icon for JSlider.

Answer

/*from ww w. ja  v a 2  s  . c  om*/
import java.awt.BorderLayout;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.UIDefaults;
import javax.swing.UIManager;

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Tick Slider");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // No Ticks
    JSlider jSliderOne = new JSlider();
    Icon icon = new ImageIcon("yourFile.gif");
    UIDefaults defaults = UIManager.getDefaults();
    defaults.put("Slider.horizontalThumbIcon", icon);

    frame.add(jSliderOne, BorderLayout.NORTH);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}