How do I create a vertical JSlider?

To create a vertical JSlider set the orientation on the JSlider‘s constructor to JSlider.VERTICAL. If you do not pass JSlider.VERTICAL as a constructor parameter use the setOrientation() method instead.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;

public class JSliderVertical extends JPanel {
    public JSliderVertical() {
        initializeUI();
    }

    private void initializeUI() {
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(500, 200));

        // Creates a vertical JSlider that accept value in the
        // range between 0 and 20. The initial value is set to 4.
        JSlider slider = new JSlider(JSlider.VERTICAL, 0, 20, 4);
        slider.setPaintTicks(true);
        slider.setPaintLabels(true);
        slider.setMinorTickSpacing(1);
        slider.setMajorTickSpacing(4);

        add(slider, BorderLayout.CENTER);
    }

    public static void showFrame() {
        JPanel panel = new JSliderVertical();
        panel.setOpaque(true);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setTitle("Vertical JSlider");
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JSliderVertical.showFrame();
            }
        });
    }
}

The screen capture of the code snippet above.

Vertical JSlider Demo

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🙂.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.