![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e799. Constraining JSlider Component Values to Tick MarksBy default, the slider can take on any value from the minimum to the maximum. It is possible to configure the slider to allow only values at tick marks (see e797 Showing Tick Marks on a JSlider Component). This is done by callingJSlider.setSnapToTicks(true) .
The slider's minimum and minor tick-mark spacing determines what values are possible. For example, if the minimum is 3 and the minor tick-mark spacing is 10, only the values, 3, 13, 23, and so forth, are allowed. If a minor tick-mark spacing has not been set, the major tick-mark spacing is used. If neither a minor nor a major tick mark spacing has been set, a tick-mark spacing of 1 is assumed. Calling // Create a horizontal slider that moves left-to-right JSlider slider = new JSlider(); // Set major tick marks every 25 units int tickSpacing = 25; slider.setMajorTickSpacing(tickSpacing); // Set minor tick marks every 5 units tickSpacing = 5; slider.setMinorTickSpacing(tickSpacing); // Show tick marks slider.setPaintTicks(true); // Determine if currently snapping to tick marks boolean b = slider.getSnapToTicks(); // false // Snap to tick marks slider.setSnapToTicks(true); // Set to a spot between tick marks; the value moves to closest tick mark slider.setValue(27); int value = slider.getValue(); // 25
e795. Getting and Setting the Values of a JSlider Component e796. Setting the Orientation of a JSlider Component e797. Showing Tick Marks on a JSlider Component e798. Showing Tick-Mark Labels on a JSlider Component e800. Listening for Value Changes in a JSlider Component © 2002 Addison-Wesley. |