JSlider Class
Package: javax.swing
The JSlider
class creates a slider control, which lets a user pick a value from a set range (say, from 0 to 50) by moving a knob. A slider is a convenient way to get numeric input from the user when the input falls within a set range of values. Figure 5-10 shows a typical slider.
Figure 5-10
Constructors
Constructor |
Description |
|
Creates a new slider. The minimum and maximum values default to |
|
Creates a new slider with the specified minimum and maximum values. The initial value is halfway between the minimum and maximum. |
|
Creates a new slider with the specified minimum, maximum, and initial values. |
|
Creates a new slider with the specified minimum, maximum, and initial values. The orientation can be |
Methods
Method |
Description |
|
Adds a |
|
Gets the value indicated by the current position of the knob. |
|
Sets the font of the text associated with the slider. |
|
If |
|
Sets the interval for major tick marks. The marks aren’t shown unless |
|
Sets the minimum value. |
|
Sets the maximum value. |
|
Sets the interval for minor tick marks. The marks aren’t shown unless |
|
Sets the orientation. Allowed values are |
|
If |
|
If |
|
Sets the tooltip text that’s displayed if the user ( |
To create a bare-bones slider with default settings (range from 0
to 100
, initial value of 50
), just call the JSlider
constructor:
slider = new JSlider();
If you want to specify the minimum and maximum values, use this constructor:
slider = new JSlider(0, 50);
The slider lets the user choose a value from 0
to 50
. The initial position of the knob is 25
, midway between the minimum and maximum values.
To set a different initial value, use this constructor:
slider = new JSlider(0, 0, 50);
Here, the slider ranges from 0
to 50
, and the initial value is 0
.
You usually want to add at least some adornments to the slider to make it more usable. The slider shown in Figure 5-10 has minimum and maximum tick-mark values with labels visible. Here’s the code used to create it:
slider = new JSlider(0, 50, 0);
slider.setMajorTickSpacing(10);
slider.setMinorTickSpacing(1);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
panel1.add(slider);
To get the value of the slider, you use the getValue
method. Here’s the actionPerformed
method for the action listener attached to the OK button in Figure 5-10:
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == buttonOK)
{
int level = slider.getValue();
JOptionPane.showMessageDialog(slider,
“Remember, this is for posterity.
”
+ “Tell me...how do you feel?”,
“Level “ + level,
JOptionPane.INFORMATION_MESSAGE);
}
}
Here, a message box is displayed when the user clicks the OK button. The current setting of the slider
component is retrieved and stored in an int
variable named level
, which is then used to create the title for the message box.