Magazine
 

Tips & Tricks

 

Output of the program:



3. JSlider Component of Java Swing

A Slider is a Swing tool that lets the user select a value within a bounded range by moving a knob. In this program, events on the JSlider component have also been shown.
If you increase or decrease the slider by selecting then the actual position of the slider will be displayed on a label. Some methods and APIs have been used to create a JSlider component and perform various tasks related
to the slider. Methods and APIs are as follows:

JSlider :
This class creates the slider for the swing application.

ChangeListener:

This is the interface of which is used to call stateChanged() method which receives the event generated by the slider using addChangeListener() method of the JSlider class.

ChangeEvent:

This is the class that handles the event generated by the JSlider component on change the state.
addChangeListener(object):

This is the method of the JSlider class which is used to handle event on change the selected state of the JSlider component.

 

Code of Program: SliderExample.java

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class SliderExample{
JSlider slider;
JLabel label;
public static void main(String[] args){
SliderExample cs = new SliderExample();
}
public SliderExample(){
JFrame frame = new JFrame(“Slider”);
slider = new JSlider();
slider.setValue(50);
slider.addChangeListener(new
MyChangeAction());
label = new JLabel(“JavaJazzUp”);
JPanel panel = new JPanel();
panel.add(slider);
panel.add(label);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 100);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyChangeAction implements
ChangeListener{
public void stateChanged(ChangeEvent
ce){
int value = slider.getValue();
String str = Integer.toString(value);
label.setText(str);
}
}
}

Output:

Jan 2007 | Java Jazz Up | 98
previous
index
next
 
View All Topics
All Pages of this Issue
Pages: 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, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59, 60, 61, 62, 63 , 64, 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 80 , 81 , 82 ,

83, 84 , 85 , 86, 87 , 88, 89 , 90 , 91 , 92 , 93 , 94 , 95 , 96 , 97 , 98 , 99 , 100 , 101 , 102 , 103, 104 , 105 ,

106, 107,

Download PDF