我想保持我的JSlider更改的值。 我的滑块的目标是更改画布中线条的粗细,我想从此滑块中保存值...
当我这样做时:
slider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent event) {
val = ((JSlider)event.getSource()).getValue();
System.out.println(val);
}
});
我获取移动滑块时已更改的所有值
8
6
13
但我想这样做:
slider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent event) {
val = ((JSlider)event.getSource()).getValue();
-> smth = val;
}
});
System.out.println(smth) // that I want : gives the last value changed.
System.out.println(smth) // that I don't want : print 0
然后我可以重复使用这个值。
我使用它将值放在JLabel上,当移动滑块时它会发生变化。
完整代码:
int initValue = 1;
int minimum = 1;
int maximum = 20;
JSlider slider = new JSlider(JSlider.VERTICAL, minimum, maximum, initValue);
slider.setInverted(true);
slider.setUI(new MySliderUI(slider) {
@Override
public TrackListener createTrackListener(JSlider slider) {
return new TrackListener() {
@Override
public void mousePressed(MouseEvent e) {
JSlider slider = (JSlider) e.getComponent();
slider.setValue(valueForYPosition(e.getY()));
labelSize.setText(slider.getValue()+"");
//TODO SAVE VALUE
super.mousePressed(e); // isDragging = true;
super.mouseDragged(e);
}
@Override
public boolean shouldScroll(int direction) {
return false;
}
};
}
});
slider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent event) {
val = ((JSlider)event.getSource()).getValue();
System.out.println(val); // 8 12 7 ...
}
});
System.out.println(val); // 0
slider.setBorder(BorderFactory.createTitledBorder("Size"));
slider.setPreferredSize(new Dimension(50, 600));
tailleColor.add(slider);
tailleColor.add(labelSize);
感谢。