How to use Sliders in Java?
Hi friends,
I am new to the Java. I want to use the Sliders instead of using the text field. I am fed up of text field because I am getting many input errors. So help me to explain how to use Sliders in Java.?? Since I am new to this forum, ignore my mistakes.!! Hoping that somebody can help me soon..!!
Re: How to use Sliders in Java?
You will have to put minimum and maximum value because the JSlider component is intended to let the user easily enter a numeric value. And this value should be bounded by a minimum and maximum value. A spinner is an another alternative to a slider if your space is limited. You were right because by using a slider instead of a text field, you eliminate input errors. The another good thing is that you can use a slider can be coupled with a formatted text field. So I would also like to suggest you to use the slider instead of text field.
Re: How to use Sliders in Java?
I think that it would be more useful for you if you see the coding that creates the slider. The following is the coding for same purpose :
Code:
static final int FPS_MIN = 0;
static final int FPS_MAX = 40;
static final int FPS_INIT = 25;
. . .
JSlider framesPerSecond = new JSlider(JSlider.HORIZONTAL,
FPS_MIN, FPS_MAX, FPS_INIT);
framesPerSecond.addChangeListener(this);
framesPerSecond.setMajorTickSpacing(15);
framesPerSecond.setMinorTickSpacing(5);
framesPerSecond.setPaintTicks(true);
framesPerSecond.setPaintLabels(true);
Re: How to use Sliders in Java?
You will also have to write the code for the listener so that it can be changed. Otherwise, your slider will not react accordingly. The code given below can be used for changing listener, so that it can react to slider value changes :
Code:
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider)e.getSource();
if (!source.getValueIsAdjusting()) {
int fps = (int)source.getValue();
if (fps == 0) {
if (!frozen) stopAnimation();
} else {
delay = 2000 / fps;
timer.setDelay(delay);
timer.setInitialDelay(delay * 5);
if (frozen) startAnimation();
}
}
}
Re: How to use Sliders in Java?
The labels that are presented on the Slider can be changed. You can set the label according to you. The following code creates the slider and changes its labels :
Code:
JSlider framesPerSecond = new JSlider(JSlider.VERTICAL,
FPS_MIN, FPS_MAX, FPS_INIT);
framesPerSecond.addChangeListener(this);
framesPerSecond.setMajorTickSpacing(20);
framesPerSecond.setPaintTicks(true);
//Create the label table
Hashtable labelTable = new Hashtable();
labelTable.put( new Integer( 0 ), new JLabel("Halt") );
labelTable.put( new Integer( FPS_MAX/20 ), new JLabel("Steady") );
labelTable.put( new Integer( FPS_MAX ), new JLabel("Speed") );
framesPerSecond.setLabelTable( labelTable );
framesPerSecond.setPaintLabels(true);