Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 310
Marco Leung Avatar asked Dec 28 '25 22:12

Marco Leung


2 Answers

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.

like image 185
camickr Avatar answered Dec 31 '25 12:12

camickr


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.

like image 32
Peter Avatar answered Dec 31 '25 12:12

Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!