1

我在另一个类中有一个滑块,我想在每次滑块的值发生变化时将它所具有的值分配给变量的值。我有这个代码

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?谢谢

4

1 回答 1

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滑块运动时设置值。

于 2013-02-11T17:43:44.993 回答