Java Swing Tutorial - Java Swing JSlider








A JSlider allows us to select a value from a list of values between two integers by sliding a knob along a track.

JSlider has four important properties:

  • an orientation
  • a minimum value
  • a maximum value
  • a current value

The orientation determines whether it is displayed horizontally or vertically. We can use SwingConstants.VERTICAL and SwingConstants.HORIZONTAL values for its orientation.

The following code creates a horizontal JSlider with the minimum value of 0, the maximum value of 10, and the current value set to 5:

JSlider points = new JSlider(0, 10,   5);

To get the current value of a JSlider, use its getValue() method. To set the current value, use its setValue(int value) method.

To display the minor and major ticks on a JSlider, set the interval at which these ticks need to be displayed, and call its method to enable the tick paintings, as the following code.

points.setMinorTickSpacing(1); 
points.setMajorTickSpacing(2); 
points.setPaintTicks(true);

To display the standard labels or custom labels showing values along the track in a JSlider.

The standard labels will display the integer values along the track, we can call its setPaintLabels(true) method to display the integer values at major tick spacing.

JSlider also support custom labels. A label on a JSlider is displayed using a JLabel component. we need to create a Hashtable with value-label pairs and use its setLabelTable() method to set the labels.

The following code sets the label Poor for value 0, Average for value 5, and Excellent for value 10.

Setting a label table does not display the labels. we must call the setPaintLabels(true) method to display them.

Hashtable labelTable  = new Hashtable(); 
labelTable.put(new Integer(0), new JLabel("Poor")); 
labelTable.put(new Integer(5), new JLabel("Average"));
labelTable.put(new Integer(10),  new JLabel("Excellent"));

// Set  the   labels for the   JSlider and  make them  visible points.setLabelTable(labelTable); 
points.setPaintLabels(true);




Change Listener

import java.awt.Dimension;
/*from  w  ww  .  ja  v a 2 s  .c o  m*/
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main {
  public static void main(String[] args) {
    JFrame f = new JFrame();
    final JSlider slider = new JSlider(0, 150, 0);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    slider.setPreferredSize(new Dimension(150, 30));
    slider.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent event) {
        int value = slider.getValue();
        if (value == 0) {
          System.out.println("0");
        } else if (value > 0 && value <= 30) {
          System.out.println("value > 0 && value <= 30");
        } else if (value > 30 && value < 80) {
          System.out.println("value > 30 && value < 80");
        } else {
          System.out.println("max");
        }
      }
    });
    f.add(slider);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}




Tick Style

The following code shows how to set the tick distance and style.

import java.awt.BorderLayout;
//from   w  w  w.  j a  va  2  s . co  m
import javax.swing.BoundedRangeModel;
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Tick Slider");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JSlider jSliderOne = new JSlider();

    // Major Tick 25 - Minor 5
    jSliderOne.setMinorTickSpacing(5);
    jSliderOne.setMajorTickSpacing(25);
    jSliderOne.setPaintTicks(true);
    jSliderOne.setSnapToTicks(true);

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

JSlider Label

The following code shows how to label JSlider Positions: use text to mark JSlider.

import java.awt.BorderLayout;
import java.util.Hashtable;
/*from   ww w .  j a  v a2  s .co  m*/
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSlider;

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Tick Slider");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JSlider jSliderOne = new JSlider();

    jSliderOne.setPaintLabels(true);
    
    Hashtable<Integer, JLabel> table = new Hashtable<Integer, JLabel>();
    table.put (0, new JLabel(new ImageIcon("yourFile.gif")));
    table.put (10, new JLabel("Ten"));
    table.put (25, new JLabel("Twenty-Five"));
    table.put (34, new JLabel("Thirty-Four"));
    table.put (52, new JLabel("Fifty-Two"));
    table.put (70, new JLabel("Seventy"));
    table.put (82, new JLabel("Eighty-Two"));
    jSliderOne.setLabelTable (table);
    
    frame.add(jSliderOne, BorderLayout.NORTH);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}

Thumb Icon

The following code shows how to set ThumbIcon for JSlider.

import java.awt.BorderLayout;
/*from   w  w  w . j  a  v a 2 s  .  co  m*/
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);
  }
}

AdjustmentListener and ChangeListener for JSlider

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
/* w  w w .ja v  a2 s  .com*/
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();

    JPanel main = new JPanel(new GridLayout(2, 1));
    JPanel scrollBarPanel = new JPanel();
    final JScrollBar scrollBar = new JScrollBar(JScrollBar.HORIZONTAL, 0, 48, 0, 255);
    int height = scrollBar.getPreferredSize().height;
    scrollBar.setPreferredSize(new Dimension(175, height));
    scrollBarPanel.add(scrollBar);
    main.add(scrollBarPanel);

    JPanel sliderPanel = new JPanel();
    final JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 255, 128);
    slider.setMajorTickSpacing(48);
    slider.setMinorTickSpacing(16);
    slider.setPaintTicks(true);
    sliderPanel.add(slider);
    main.add(sliderPanel);

    frame.add(main, BorderLayout.CENTER);

    scrollBar.addAdjustmentListener(new AdjustmentListener() {
      public void adjustmentValueChanged(AdjustmentEvent e) {
        System.out.println("JScrollBar's current value = " + scrollBar.getValue());
      }
    });

    slider.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent e) {
        System.out.println("JSlider's current value = " + slider.getValue());
      }
    });

    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
}