Changing a JLabel's Value from a JSlider's Value

爱⌒轻易说出口 提交于 2019-11-28 14:07:05

You don't listen for ChangeEvents on a JLabel. You listen for ChangeEvents on the JSlider and then in the stateChanged() method you simply use

label.setText("Time: " + scaleSlider.getValue());

No need to fire any event from the ChangeLisetner either.

You don't need to add a change listener to the JLabel. If your JLabel is a member field of the class that contains the code, you can refer to the JLabel within the JSlider's change listener, like so:

public class Test() {
    private JLabel label;

    private void setup() {
        label = new JLabel();
        JSlider scaleSlider = new JSlider();
        scaleSlider.addChangeListener(new ChangeListener() {

            public void stateChanged(ChangeEvent event) {
                int currentTime = ((JSlider)event.getSource()).getValue();
                label.setText(currentTime);
            }
        }
    }
}

You can refer to any outer class's field within any inner-class, even the anonymous inner-class ChangeListener you've declared on the scaleSlider.

What you need to do is add the change listener to the slider.

Then in the change method that you have to implement, change the value of the text in the JLabel.

Regarding your code, all the doSomething(int) method needs to do is:

label.setText(currentTime + "");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!