我在另一个类中有一个滑块,每次滑块的值发生变化时,我想将它所具有的值赋值给变量。我有这个代码
public double setSliderValue() {
double myVariable;
sliders.mySlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
myVariable = Sliders.variableSlider.getValue();
System.out.println(myVariable); //returns 0 each time
}
});
return myVariable;
}
我错过了什么/我需要添加什么才能将滑块上当前的值分配给myVariable?感谢
答案 0 :(得分:0)
这可能不是最好的方法,但你可以给包含JSlider的类提供对外部类的引用。
import java.lang.Object;
import java.lang.String;
import java.lang.System;
import javax.swing.*;
import javax.swing.event.*;
包含JSlider的类,例如:
class Window extends JFrame {
private JSlider slider;
// a reference to the other class needs to be final
private final Test testClass;
public Window(Test incomingReference) {
// set the reference
this.testClass = incomingReference;
// JSlider stuff
slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 1);
slider.addChangeListener(new ChangeListener() {
@Override public void stateChanged(ChangeEvent e) {
JSlider src = (JSlider) e.getSource();
if (src.getValueIsAdjusting()) return;
testClass.setSomeVariable(src.getValue());
System.out.println(testClass.getSomeVariable());
}
});
// window stuff
JFrame window = new JFrame("JSlider Test");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(800, 600);
window.add(slider);
window.setVisible(true);
}
}
“外层阶级”:
public class Test extends Object {
public int someVariable = 0;
public void setSomeVariable(int value) { someVariable = value; }
public int getSomeVariable() { return someVariable; }
public static void main(String ... args) {
// give the window a reference to this object
Test foo = new Test();
Window window = new Window(foo);
}
}
另请注意ChangeListener
:if (!src.getValueIsAdjusting()) return;
中不在您的代码段中的行。这可以防止ChangeListener
在滑块运动时设置值。