Reputation: 1453
How to read the value of a JSlider?
I am using sliders in my program, something I have not used before but I am struggling to display the changes made to it!
The problem is, the JLabel
displays the value of the slider when you open the program (50) but when you change the value the label does not.
Here is the code:
Setting up the slider (in setUpMenuItems class):
sensitivitySlider2 = new JSlider();//direction , min , max , current
sensitivitySlider2.setFont(new Font("Calibri",Font.BOLD,10));
sensitivitySlider2.setMajorTickSpacing(10);
sensitivitySlider2.setMinorTickSpacing(1);
sensitivitySlider2.setPaintLabels(true);
sensitivitySlider2.setPaintTicks(true);
sensitivitySlider2.setPaintTrack(true);
sensitivitySlider2.setAutoscrolls(true);
sensitivitySlider2.setBackground(Color.WHITE);
sensitivitySlider2.setBounds (15,200,250,100);
propertiesPanel.add(sensitivitySlider2);
establishing the listener:
private void registerComponentsForEvents()
{
// Register all the JButton objects for action events
miniButton.addActionListener (this);
applyButton.addActionListener (this);
exitButton.addActionListener (this);
sensitivitySlider2.addChangeListener(this);
}
Window listener and declaring methods to make concrete:
void addWindowListener(Window w) {
w.addWindowListener(this);
}
//React to window events.
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
ChangeEvent:
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider)e.getSource();
if (!source.getValueIsAdjusting()) {
int sleepSense = (int)source.getValue();
}
}
and then this line to set a JLabel as the value:
sleepSense2 = String.valueOf(sleepSense);
Upvotes: 0
Views: 13372
Reputation: 31
This is an old topic, but, i will share my thoughts on it.
I believe you do not need to have the following code written like this just to get the value. (Using if statement)
if (!source.getValueIsAdjusting()) {
int sleepSense = (int)source.getValue();
you can just be well of with the following
JSlider mySlider= new JSlider();
mySlider.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e) {
int sleepSense = mySlider.getValue();
}
then you can use the value "sleepSense" anywhere in your program.
Upvotes: 2