如何判定 JSlider 当前是否在 Java 中捕捉刻度
首先,我们将创建一个滑块并设置它捕捉刻度标记
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 40); slider.setMinorTickSpacing(10); slider.setMajorTickSpacing(20); slider.setPaintTicks(true); slider.setPaintLabels(true); slider.setSnapToTicks(true);
然后,我们将检查滑块当前是否捕捉刻度标记。结果将以 TRUE/FALSE 布尔值显示
slider.getSnapToTicks()
将结果显示在控制台,如下所示
System.out.println("Snapping to tick marks? = "+slider.getSnapToTicks());
以下是如何确定滑块当前是否捕捉刻度标记的示例
示例
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); System.out.println("Snapping to tick marks? = "+slider.getSnapToTicks()); 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); } }
输出
控制台会显示滑块是否捕捉刻度标记
广告