从 JSlider 的值更改 JLabel 的值
我有一个包含 JSlider 和 JLabel 的 JPanel。 我想对其进行配置,以便当用户更改 JSlider 的值时,JLabel 会反映该新值。
我知道我可以使用 Slider 触发 ChangeEvents,但我不知道如何向 JLabel 添加 ChangeListener。 这是我的代码片段。
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 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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不会监听 JLabel 上的 ChangeEvents。 您在 JSlider 上侦听 ChangeEvents,然后在 stateChanged() 方法中,您只需使用
也不需要从 ChangeLisetner 触发任何事件。
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
No need to fire any event from the ChangeLisetner either.
您不需要向 JLabel 添加更改侦听器。 如果您的 JLabel 是包含代码的类的成员字段,您可以在 JSlider 的更改侦听器中引用 JLabel,如下所示:
您可以在任何内部类(甚至是匿名内部类)中引用任何外部类的字段您在scaleSlider上声明的ChangeListener。
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:
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.
您需要做的是将更改侦听器添加到滑块。
然后在您必须实现的更改方法中,更改
JLabel
中的文本值。关于您的代码,所有
doSomething(int)
方法需要做的是: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: