Academic Java    Java Tutorial  >  Swing  >  JSlider

JSlider Example

Java JSlider EXAMPLE output This JSlider example shows two JSliders, a basic one, and one which shows 'ticks'. The horizontal one to the left does not show ticks.

The JSlider enables the user to select from continuous values. Each movement of a slider generates many events.

The calls to addChangeListener() enable the events to be acted upon.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// JSlider Example
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;

class JSliderExample {

   public static void main(String[] args) {

      final JSlider sa = new JSlider();
      final JSlider sb = new JSlider(JSlider.VERTICAL, 0, 100, 50);

      sa.addChangeListener (new ChangeListener() {
         public void stateChanged (ChangeEvent e) {
            System.out.println(sa.getValue());
         }
      });

      sb.addChangeListener (new ChangeListener() {
         public void stateChanged (ChangeEvent e) {
            System.out.println(sb.getValue());
         }
      });

      sb.setPaintTicks(true);
      sb.setMajorTickSpacing(25);
      sb.setMinorTickSpacing(5);
      sb.setPaintLabels(true);

      JFrame frame = new JFrame();
      Container cp = frame.getContentPane();
      cp.setLayout(new FlowLayout());
      cp.add(sa);
      cp.add(sb);

      frame.pack();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}

10-11 These are the two constructors. The possible constructors for JSlider are:
	JSlider() - creates a horizontal slider with the range 0 to 100
		and an initial value of 50.
	
	JSlider(BoundedRangeModel model) - creates a horizontal slider using the
		specified BoundedRangeModel.

	JSlider(int orientation) - creates a slider in the given orientation
		with the range 0 to 100 and an initial value of 50.

	JSlider(int min, int max) - creates a horizontal slider using the specified min
		and max with an initial value halfway between min and max.

	JSlider(int min, int max, int value) - creates a horizontal slider using the
		specified min, max and value.

	JSlider(int orientation, int min, int max, int value) - as above but with the
		given orientation.


25-28 Methods to control how ticks are displayed.