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.swing;

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

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

    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(JSliderVertical::showFrame);
    }

    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);
    }
}

The screen capture of the code snippet above.

Vertical JSlider Demo

Wayan

Leave a Reply

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