The JSlider
‘s setSnapToTicks()
method call is used to move JSlider
‘s knob to the nearest tick mark from where you positioned the knob. The default value of this property is false
. To make it snap to the closest tick set this property to true
.
package org.kodejava.swing;
import javax.swing.*;
import java.awt.*;
public class SnapToTickJSlider extends JPanel {
public SnapToTickJSlider() {
initializeUI();
}
public static void showFrame() {
JPanel panel = new SnapToTickJSlider();
JFrame frame = new JFrame("JSlider - Snap to Tick");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(SnapToTickJSlider::showFrame);
}
private void initializeUI() {
setLayout(new BorderLayout());
setPreferredSize(new Dimension(500, 200));
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 30, 0);
slider.setMinorTickSpacing(5);
slider.setMajorTickSpacing(10);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
// Snaps to the closest tick mark next to where the user
// positioned the knob.
slider.setSnapToTicks(true);
add(slider, BorderLayout.CENTER);
}
}
The screen capture of the result of the code snippet above is:
Latest posts by Wayan (see all)
- How do I add an object to the beginning of Stream? - February 7, 2025
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024