![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to detect the value change of a JSlider in Java?
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
Advertisements