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

前端 未结 3 1738
Happy的楠姐
Happy的楠姐 2020-12-11 23:26

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 reflect

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-11 23:50

    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.

提交回复
热议问题