How to use Java JSlider Example

By | 2017-11-28T02:02:57+00:00 November 28th, 2017|java|0 Comments

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 :

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) {
        g.fillRect(10, 10, diameter, diameter);

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

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

    public Dimension getMinDimensions() {
        return getDimensions();

public class JSliderDemo extends JFrame{
    private JSlider jSlider;
    private MyRect myRectPanel;
        super("JSlider Demo");
        myRectPanel = new MyRect();
        jSlider = new JSlider(SwingConstants.HORIZONTAL,0,200,10);
        jSlider.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent arg0) {
    public static void main(String[] args) {
        JSliderDemo sliderDemo = new JSliderDemo();
        sliderDemo.setSize(300, 350);

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 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment