In this tutorials, I am going to show you how to create Java JSlider and how do we use.

Java JSlider is a swing component that lets the user to select value by sliding a knob with in a bounded interval.

Java JSlider Example :

[java]

package com.onlinetutorialspoint.swing;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

class MyRect extends JPanel {
    private int diameter = 10;

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.fillRect(10, 10, diameter, diameter);
    }

    public void setDiameter(int diameter) {
        this.diameter = (diameter >= 0 ? diameter : 10);
        repaint();
    }

    public Dimension getDimensions() {
        return new Dimension(200, 200);
    }

    public Dimension getMinDimensions() {
        return getDimensions();
    }
}

public class JSliderDemo extends JFrame{
    private JSlider jSlider;
    private MyRect myRectPanel;
    JSliderDemo(){
        super("JSlider Demo");
        myRectPanel = new MyRect();
        myRectPanel.setBackground(Color.GRAY);
        myRectPanel.setForeground(Color.GREEN);
        
        jSlider = new JSlider(SwingConstants.HORIZONTAL,0,200,10);
        jSlider.setMajorTickSpacing(10);
        jSlider.setPaintTicks(true);
        
        jSlider.addChangeListener(new ChangeListener() {
            
            @Override
            public void stateChanged(ChangeEvent arg0) {
                myRectPanel.setDiameter(jSlider.getValue());
            }
        });
        
        add(jSlider,BorderLayout.SOUTH);
        add(myRectPanel,BorderLayout.CENTER);
    }
    public static void main(String[] args) {
        JSliderDemo sliderDemo = new JSliderDemo();
        sliderDemo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        sliderDemo.setSize(300, 350);
        sliderDemo.setVisible(true);
    }
}

[/java]

setMajorTickSpacing() : This method is used to set the major tick spacing.
setPaintTicks() : It Determines whether tick marks are painted on the slider or not. If it set to true the tick marks will appear on slider.

Output :

Java JSlider Example

Increasing Dimensions  :

Java JSlider Example 2

Increasing Dimensions  :

Java JSlider Example 3

Happy Learning 🙂