该JSlider的setSnapToTicks()方法调用是用来移动JSlider'从您定位旋钮小号旋钮最近的刻度标记。此属性的默认值为false。要使其贴近最近的刻度,请将此属性设置为true。
package org.nhooo.example.swing; import javax.swing.*; import java.awt.*; public class SnapToTickJSlider extends JPanel { public SnapToTickJSlider() { initializeUI(); } 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); // 捕捉到用户旁边最近的刻度线 // 定位旋钮。 slider.setSnapToTicks(true); add(slider, BorderLayout.CENTER); } 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(new Runnable() { public void run() { SnapToTickJSlider.showFrame(); } }); } }
上面的代码片段的结果的屏幕截图是: