Reputation: 2074
Please, I tried to add a changeHandler event but I don't think I got it right. I am looking at the following statements..
pickNum.addChangeListener(new ChangeHandler());
@Override
public void stateChanged(changeEvent e)
{
JSlider s = (JSlider)e.getSource();
index = s.getValue();
}
Is there something I could have done better because because, it's not working..
import javax.swing.*;
public class Slider extends JFrame{
public static int index;
JSlider pickNum = new JSlider(JSlider.HORIZONTAL,0,30,5);
public Slider()
{
super("Slider");
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pickNum.setMajorTickSpacing(10);
pickNum.setMinorTickSpacing(1);
pickNum.setPaintTicks(true);
pickNum.setPaintLabels(true);
pickNum.addChangeListener(new ChangeHandler());
@Override
public void stateChanged(changeEvent e)
{
JSlider s = (JSlider)e.getSource();
index = s.getValue();
}
getPointedValue();
this.add(pickNum);
this.setVisible(true);
}
public final int getPointedValue()
{
int value;
value = pickNum.getValue();
return value;
}
public static void main(String[] args) {
Slider frame = new Slider();
System.out.println("value is :"+Slider.index);
}
}
[/CODE]
Upvotes: 0
Views: 1727
Reputation: 36601
What is that ChangeHandler
class you are talking about ? It is not part of the JDK. Did you mix up the ChangeHandler
class from GWT with the ChangeListener
from the JDK ?
Further, I would suggest you take a look at the Swing slider for sample code working with sliders. For example a nice sample implementation of such a ChangeListener
attached to the slider
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 = 1000 / fps;
timer.setDelay(delay);
timer.setInitialDelay(delay * 10);
if (frozen) startAnimation();
}
}
}
Note the getValueIsAdjusting()
call which you misses in your code snippet
Upvotes: 2
Reputation: 35011
What is your ChangeHandler? You haven't posted that code
Here is an example of using a change listener
JSlider s = new JSlider();
s.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
System.out.println("Changed: " + e);
}
});
Upvotes: 3
Reputation: 3209
What is the implementation of your ChangeHandler
? You don't really need an separate file for it, the ChangeListener interface only has one method so you can quickly provide an implementation while declaring it inline
pickNum.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent arg0) {
JSlider s = (JSlider) arg0.getSource();
index = s.getValue();
}
});
Upvotes: 2