JSlider with ChangeListener

The listener that is appropriate for the JSlider control is as follows:

public void addChangeListener ( this);

The Changelistener interface provides the declaration for the following statechanged() method:

void statechanged ( changeEvent ev );

The getvalue() method returns the current value of the slider.

Program

w



 
 
 

Program Source

import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import java.awt.FlowLayout;

class JSliderTest extends JFrame implements ChangeListener{

    JSlider slider1,slider2;
    JButton jb1,jb2;
    
    JSliderTest()
    {
        setTitle("JSlider");
        setLayout(new FlowLayout());
        setJSlider();
        setSize(700, 250);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    private void setJSlider()
    {
        slider1 = new JSlider();
        slider1.addChangeListener(this);
        add(new JLabel("slider1"));
        add(slider1);
        add(jb1 = new JButton("DefaultValue"));
        
        slider2 = new JSlider(100,200);
        slider2.addChangeListener(this);
        add(new JLabel("slider2"));
        add(slider2);
        add(jb2 = new JButton("DefinedValue"));
    }
    
    public void stateChanged(ChangeEvent ev)
    {
        if(ev.getSource() == slider1)
        {
            jb1.setText(""+slider1.getValue());
        }
        if(ev.getSource() == slider2)
        {
            jb2.setText(""+slider2.getValue());
        }
    }
}

public class Javaapp {
   
    public static void main(String[] args) {
        
        JSliderTest js = new JSliderTest();
    }
}

One thought on “JSlider with ChangeListener

Leave a Comment