这可能不是最好的方法,但您可以为包含 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
滑块运动时设置值。