How to detect the value change of a JSlider in Java?

JavaObject Oriented ProgrammingProgramming

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. A JSlider has a knob which can slide on a range of values and can be used to select a particular value. and it can generate a ChangeListener interface.

We can detect the value changed when the slider is moved horizontally using the Graphics2D class and override paint() method.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ValueChangeJSliderTest extends JFrame {
   private JSlider slider;
   public ValueChangeJSliderTest() {
      setTitle("ValueChangeJSlider Test");
      slider = new JSlider(JSlider.HORIZONTAL, 0, 20, 1);
      slider.addChangeListener(new ChangeListener() {
         public void stateChanged(ChangeEvent ce) {
            repaint();
         }
      });
      setLayout(new BorderLayout());
      slider.setBackground(Color.white);
      slider.setMajorTickSpacing(1);
      slider.setPaintTicks(true);
      slider.setPaintLabels(true);
      add(slider, BorderLayout.NORTH);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public void paint(Graphics g) {
      super.paint(g);
      Graphics2D g2d = (Graphics2D) g;
      g2d.setFont(new Font("Serif", Font.ITALIC, 25));
      g2d.drawString(""+slider.getValue(), 200, 130);
   }
   public static void main(String[] args) {
      new ValueChangeJSliderTest();
   }
}

Output

raja
Published on 16-Aug-2019 14:51:18
Advertisements