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 create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023