How to change the position of a JSlider to horizontal/vertical programmatically in Java?


A JSlider is a subclass of JComponent class and it is similar to scroll bar which allows the user to select a numeric value from a specified range of integer values. It has a knob which can slide on a range of values and can be used to select a particular value. A JSlider can generate a ChangeListener interface and the important methods of JSlider are getMaximum(), getMinimum(), getOrientation(), getValue() and setValue(). The default position of a JSlider is horizontal and we can also set the position to vertical programmatically by selecting a menu item from a menu bar. It can generate an ActionListener interface for these menu items and set the orientation by using the setOrientation() method of JSlider class in the actionPerformed() method.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JSliderVerticalHorizontalTest extends JFrame implements ActionListener {
   private JSlider slider;
   private JMenuBar menuBar;
   private JMenu menu;
   private JMenuItem menuItem1, menuItem2;
   public JSliderVerticalHorizontalTest() {
      setTitle("JSliderVerticalHorizontal Test");
      setLayout(new FlowLayout());
      menuBar = new JMenuBar();
      menu = new JMenu("JSlider Orientation");
      menuItem1 = new JMenuItem("HORIZONTAL");
      menuItem2 = new JMenuItem("VERTICAL");
      menu.add(menuItem1);
      menu.add(menuItem2);
      menuItem1.addActionListener(this);
      menuItem2.addActionListener(this);
      menuBar.add(menu);
      setJMenuBar(menuBar);
      slider = new JSlider(JSlider.HORIZONTAL, 0, 30, 15);
      add(slider);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new JSliderVerticalHorizontalTest();
   }
   public void actionPerformed(ActionEvent ae) {
      if (ae.getActionCommand().equals("HORIZONTAL"))
         slider.setOrientation(JSlider.HORIZONTAL);
      else if (ae.getActionCommand().equals("VERTICAL"))
         slider.setOrientation(JSlider.VERTICAL);
   }
}

Output

Updated on: 10-Feb-2020

280 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements