Sliders
Introduction.
Sliders are another of the many
controls available in Java. I am doing a webpage on them because I
have made use of them in several of my more research oriented projects. The following table contains a list of the constructors that are available for the JSlider class. |
Constructor | Description |
JSlider(int, int) | A slider with the specified minimum and maximum values |
JSlider(int, int, int) | A slider with the specified minimum and maximum values along with a starting value |
JSlider(int, int, int, int) | A slider with a specified orientation, minimum, maximum and starting value |
Notice that you need at least two values in a JSlider
constructor. There are also a variety of methods that the developer will need to use in order to configure JSliders aprropriately. Several of these methods are listed in the following table. |
Method | Description |
setMajorTickSpacing(int) | This sets the spacing between major tick marks on the slider. This spacing is not done in pixels but in in values between the specified minimum and maximum values on the slider. |
setMinorTickSpacing(int) | This sets the spacing between minor tick marks. Minor tick marks are half the length of major ones. |
setPaintTicks(boolean) | Determines whether the tick marks should be displayed. |
setPaintLabels(boolean) | Determines whether the numeric value on the tick marks should be displayed. |
These specifications must be invoked before the JSlider
is added to the GUI. Now, we will make use of ChangeListeners when sensing user inputs relative to our sliders. A brief discussion of these was given in the previous webpage. Finding the Sum. Now we present our first example, an applet called SliderSum.java. This is a modification of a program we did last semester where we develop a GUI and rather than getting user inputs from JOptionPanes, we have the user adjust a JSlider. |
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; public class SliderSum extends JApplet {
} // ends the program |
Since size impacts the display I am including the SliderSum.html file for the applet. |
<html> <applet code="SliderSum.class" width=500 height=200> </applet> </html> |
The following image represents the GUI with 12 selected on the JSlider. |
Nothing in the code is particularly new, other than it
creates its own class for handling ChangeEvents
implementing the ChangeListener. Notice that it is reasonably important to have the extra texfield to display the actual position of the slider. |