| JSlider |
|---|
Scrollbar class played double duty as a
control for interactively selecting numeric values and a widget used
to control scrolling. This was inconvenient, and resulted in poor
looking sliders. Swing gives you a "real" slider:
JSlider. You create a JSlider in a similar manner to
Scrollbar: the zero-argument constructor creates a
horizontal slider with a range from 0 to 100 and an initial value of
50. You can also supply the orientation (via
JSlider.HORIZONTAL or JSlider.VERTICAL) and
the range and initial value to the constructor. You handle events by
attaching a ChangeListener. Its stateChanged
method normally calls getValue to look up the current
JSlider value.
setPaintTicks(true), then specify the tick spacing via
setMajorTickSpacing and
setMinorTickSpacing. If you want users to only be able
to choose values that are at the tick marks, call
setSnapToTicks(true). Turn on labels via
setPaintLabels(true). This draws labels for the major
tick marks. You can also specify arbitrary labels (including
ImageIcons or other components) by creating a
Dictionary with Integers as keys and
Components as values, then associating that with the
slider via setLabelTable.
Other capabilities include: borders (as with all
JComponents), sliders that go from high to low instead of
low to high (setInverted(true)), and the ability to
determine that you are in the middle of a drag (when
getValueIsAdjusting() returns true) so that
you can postpone action until the drag finishes.
import java.awt.*;
import javax.swing.*;
public class JSliders extends JFrame {
public static void main(String[] args) {
new JSliders();
}
public JSliders() {
super("Using JSlider");
// Comment out next line for Java LAF
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.white);
JSlider slider1 = new JSlider();
slider1.setBorder(BorderFactory.createTitledBorder("JSlider without Tick Marks"));
content.add(slider1, BorderLayout.NORTH);
JSlider slider2 = new JSlider();
slider2.setBorder(BorderFactory.createTitledBorder("JSlider with Tick Marks"));
slider2.setMajorTickSpacing(20);
slider2.setMinorTickSpacing(5);
slider2.setPaintTicks(true);
content.add(slider2, BorderLayout.CENTER);
JSlider slider3 = new JSlider();
slider3.setBorder(BorderFactory.createTitledBorder("JSlider with Tick Marks & Labels"));
slider3.setMajorTickSpacing(20);
slider3.setMinorTickSpacing(5);
slider3.setPaintTicks(true);
slider3.setPaintLabels(true);
content.add(slider3, BorderLayout.SOUTH);
pack();
setVisible(true);
}
}
Note: also requires
WindowUtilities.java
and ExitListener.java,
shown earlier.