Saturday, August 24, 2013

JSlider

JSlider is a component that allows you select a value graphically from a range of values. JSlider component generates an change event when the user drags the slider' knob. So you need to implement the ChangeListner interface to receive the event.

Constructors of the JSlider class:
-JSlider()
creates a horizontal slider with the range 0 to 100 and initial value 50.
-JSlider(int orientation)
creates a slider with the specified orientation and the range 0 to 100 and initial value 50.
-JSlider(int min,int max)
creates a slider with the specified min and max values.
-JSlider(int min,int max,int value)
creates a slider with the specified min,max, and initial values.
-JSlider(int orientation,int min,int max,int value)
creates a slider with the specified orientation, min, max, and initial values.

Useful methods of the JSlidder class:
-getValue():int
returns the current value of the slidder.
-setMaximum(int n):void
sets the maximum value to n.
-setMinimum(int n):void
sets the minimum value to n.
-setValue(int n):void
sets the current value to n.

In the example program below, we construct a integer slider that allows the user to selection an integer value graphically. The current value of slide is 0. The min and max values of the slider are 0 and 1000 respectively. The stateChanged method is overridden to get the value of the slider and this value will be used to construct the color object to be applied to the background of the window.
You can set a background color of the JFrame window by using the setBackground method.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

class JSlidderShow extends JFrame implements ChangeListener{
JPanel p;
JSlidderShow(String title){
setTitle(title);
setSize(500,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
contpane.setLayout(new BorderLayout());
JSlider slider=new JSlider(JSlider.HORIZONTAL,0,1000,0);
slider.addChangeListener(this);
p=new JPanel();
p.add(slider);
contpane.add(p,BorderLayout.CENTER);
setVisible(true);

}

public void stateChanged(ChangeEvent e){
JSlider sl=(JSlider)e.getSource();
p.setBackground(new Color(sl.getValue()));

}


}

public class JFrameSwing {
public static void main(String[] args){
new JSlidderShow("JSlider");
}
}

JSlider Swing

No comments:

Post a Comment