class AngleSlider开发者_Go百科 implements ChangeListener {
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
if (!source.getValueIsAdjusting()) {
double dAngle = (double)source.getValue();
pnlCannon.dCannonAngle=Math.toRadians(dAngle);
pnlCannon.repaint();
}
}
}
This is our current event listener. Is there a different listener required to do what I want?
No, you will only need to remove the getValueIsAdjusting()
check. So, this will repaint your cannon when you move your mouse:
class AngleSlider implements ChangeListener {
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
double dAngle = (double)source.getValue();
pnlCannon.dCannonAngle=Math.toRadians(dAngle);
pnlCannon.repaint();
}
}
This is another example that shows the same, it will print the value of the slider as you move it:
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
JSlider slider = new JSlider();
slider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent ce) {
System.out.println(((JSlider) ce.getSource()).getValue());
}
});
frame.add(slider);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}
The !source.getValueIsAdjusting()
is preventing the update code form executing.
Why do you think that condition is necessary?
精彩评论