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

Marco Leung picture Marco Leung · Aug 6, 2009 · Viewed 9.7k times · Source

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.

Answer

camickr picture camickr · Aug 6, 2009

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.