从JSlider的值改变JLabel的值 [英] Changing a JLabel's Value from a JSlider's Value

查看:105
本文介绍了从JSlider的值改变JLabel的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含JSlider和JLabel的JPanel。我想配置它,以便当用户更改JSlider的值时,新值将由JLabel反映。

I have a single JPanel that contains a JSlider and a JLabel. I want to configure it so that when the JSlider's value is being changed by the user, that new value is reflected by the JLabel.

我知道我可以使用以下命令触发ChangeEvents Slider,但我不知道如何将ChangeListener添加到JLabel。这是我的代码片段。

I understand that I can fire ChangeEvents with the Slider, but I don't know how to add a ChangeListener to the JLabel. Here's a snippet of my code.

scaleSlider.addChangeListener(new ChangeListener() {
    public void stateChanged(ChangeEvent event)
    {
        int currentTime = ((JSlider)event.getSource()).getValue();
        doSomething(currentTime);
        fireStateChanged(event);
    }

JLabel timeValue = new JLabel("Time: " + scaleSlider.getValue());
timeValue.add??? 

(我现在不知道该怎么做才能反映滑块的变化)

(I don't know what to do here now to reflect the changes in the slider)

我是否朝着正确的方向前进?提前感谢您的帮助。

Am I going in the right direction with this? Thanks in advance for your help.

推荐答案

您不会听取ChangeEvents一个JLabel。你在JSlider上监听ChangeEvents,然后在stateChanged()方法中你只需使用

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());

无需从ChangeLisetner ei触发任何事件那个。

No need to fire any event from the ChangeLisetner either.

这篇关于从JSlider的值改变JLabel的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆