Swing JSlider Class



Swing JSlider Class

package com.c4learn.swing;

import java.awt.FlowLayout;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class JSliderDemo {

  private JFrame mainFrame;
  private JLabel headLabel;
  private JLabel msgLabel;
  private JPanel mainPanel;
  
  public JSliderDemo() {
    mainFrame = new JFrame("Java Swing Examples");
    mainFrame.setSize(400, 400);
    mainFrame.setLayout(new GridLayout(3, 1));

    headLabel = new JLabel("Slider Demo", JLabel.CENTER);
    msgLabel = new JLabel("", JLabel.CENTER);
    mainPanel = new JPanel();
    mainPanel.setLayout(new FlowLayout());

    mainFrame.add(headLabel);
    mainFrame.add(mainPanel);
    mainFrame.add(msgLabel);
    mainFrame.setVisible(true);
  }

  public static void main(String[] args) {
    JSliderDemo swingControlDemo = new JSliderDemo();
    swingControlDemo.showSliderDemo();
  }

  private void showSliderDemo() {

    JSlider slider= new 
        JSlider(JSlider.HORIZONTAL,0,100,10);
    msgLabel.setText("Value : 10");
    
    slider.addChangeListener(new ChangeListener() {
           public void stateChanged(ChangeEvent e) {
             msgLabel.setText("Value : " 
              + ((JSlider) e.getSource()).getValue());
           }
        });
    
    mainPanel.add(slider);
    mainFrame.setVisible(true);
  }
}

Output :

Swing JSlider Class