Java Swing How to - Set an arbitrary label at any particular major tick mark








Question

We would like to know how to set an arbitrary label at any particular major tick mark.

Answer

/*w w  w  .j  a va2s  . c  o  m*/

import java.util.Dictionary;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JSlider;

public class Main {
  public static void main(String[] argv) throws Exception {
    JSlider slider = new JSlider();
    
    Dictionary table = slider.getLabelTable();

    ImageIcon icon = new ImageIcon("icon.gif");
    JLabel label = new JLabel(icon);

    // Set at desired positions
    table.put(new Integer(slider.getMinimum()), label);
    table.put(new Integer(slider.getMaximum()), label);

    // Force the slider to use the new labels
    slider.setLabelTable(table);

  }
}