views:

639

answers:

3

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.

+2  A: 

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 + "");
jjnguy
Perfect, thanks.
Marco Leung
You are welcome, glad to help!
jjnguy
+4  A: 

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.

camickr
Thanks. Def overthinking this one.
Marco Leung
don't forget to call repaint()
Stroboskop
`setText()` automatically repaints, if I remember correctly.
Michael Myers
+2  A: 

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.

Peter Nix