Create JSlider with tick marks and labels in Java

Description

The following code shows how to create JSlider with tick marks and labels.

Example


/* w  ww. j  a v  a2 s  . c o  m*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JSlider;

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

  public Main() {
    Container content = getContentPane();
    content.setBackground(Color.white);

    JSlider slider1 = new JSlider();
    slider1.setBorder(BorderFactory.createTitledBorder("JSlider without Tick Marks"));

    content.add(slider1, BorderLayout.NORTH);

    JSlider slider2 = new JSlider();
    slider2.setBorder(BorderFactory.createTitledBorder("JSlider with Tick Marks"));

    slider2.setMajorTickSpacing(20);
    slider2.setMinorTickSpacing(5);
    slider2.setPaintTicks(true);
    content.add(slider2, BorderLayout.CENTER);

    JSlider slider3 = new JSlider();
    slider3.setBorder(BorderFactory.createTitledBorder("JSlider with Tick Marks & Labels"));

    slider3.setMajorTickSpacing(20);
    slider3.setMinorTickSpacing(5);
    slider3.setPaintTicks(true);
    slider3.setPaintLabels(true);
    content.add(slider3, BorderLayout.SOUTH);

    setSize(300,300);
    setVisible(true);
  }
}

The code above generates the following result.

Create JSlider with tick marks and labels in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer