What is JSlider - Java Swing

Java examples for Swing:JSlider

Introduction

JSlider selects a value from a set of values between two integers by sliding a knob.

JSlider has four important properties: an orientation, a minimum value, a maximum value, and a current value.

The orientation sets whether it is displayed horizontally or vertically.

You can use SwingConstants.VERTICAL and SwingConstants.HORIZONTAL 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 mySlider = new JSlider(0, 10, 5);

To get the current value of a JSlider using its getValue() method.

To set the interval at which these ticks need to be displayed, and call its method to enable the tick paintings.

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

The following code shows how to create a JSlider with custom labels.

import java.util.Hashtable;

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

public class Main {

  public static void main(String[] args) {
    // Create the value-label pairs in a Hashtable
    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"));

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

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

Related Tutorials