- 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 create a JSlider that snap to the closest tick mark in Java?
At first, let us first create a slider in Java −
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 40); slider.setMinorTickSpacing(10); slider.setMajorTickSpacing(20); slider.setPaintTicks(true); slider.setPaintLabels(true);
Now, we will snap closest tick mark value as shown below −
slider.setSnapToTicks(true);
The following is an example to create a JSlider that snap to the closest tick mark −
Example
package my; import java.awt.Color; import java.awt.Font; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.WindowConstants; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame("Frame with Slider"); JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 40); slider.setMinorTickSpacing(10); slider.setMajorTickSpacing(20); slider.setPaintTicks(true); slider.setPaintLabels(true); slider.setBackground(Color.CYAN); slider.setForeground(Color.black); slider.setSnapToTicks(true); Font font = new Font("Serif", Font.BOLD, 13); slider.setFont(font); JPanel panel = new JPanel(); panel.add(slider); frame.add(panel); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setSize(600, 300); frame.setVisible(true); } }
Output
Advertisements