简体   繁体   中英

How to have an integer variable update as a result of a ChangeListener added to a JSlider

Im having a bit of bother with a JSlider at the moment, Im fairly new to java so this may be easily rectified.

I have a JSlider that looks like this here: JSlider Gui Image

What I want to be able to do is have the "0" constantly update to the value of the JSlider. I have a ChangeListener added with .getValue() called upon the JSlider and set equal to an int variable as seen in this image: JSlider Code

This int variable has been declared in the class so its not local to any methods, the System.out.println() proves that the ChangeListener is working as the value of the JSlider is constantly updated and printed in the console however the int variable does not seem to hold its value outside of this ChangeListener and therefore will not display the current value in the border where I want it to.

Does anyone have any clue on how to resolve this?

All Relevant code is here:

JPanel sectorSlider = new JPanel();

sectorSlider.setLayout(new BorderLayout());
TitledBorder sectorSliderBorder;

final int sectorNumberMin = 0;
final int sectorNumberMax = 50;
final int sectorNumberInitial = 12;
        JSlider sectorNumberSlider = new JSlider(JSlider.HORIZONTAL,
        sectorNumberMin, sectorNumberMax, sectorNumberInitial);
       sectorNumberSlider.setMajorTickSpacing(10);
sectorNumberSlider.setMinorTickSpacing(5);
sectorNumberSlider.setPaintTicks(true);
sectorNumberSlider.setPaintLabels(true);

sectorNumberSlider.addChangeListener(new ChangeListener() {
    @Override
    public void stateChanged(ChangeEvent event) {
        sectorValue = sectorNumberSlider.getValue();
        System.out.println(sectorValue);
    }
});

sectorSliderBorder = BorderFactory.createTitledBorder(blackline, "Number of Sectors: " +sectorValue);

sectorSliderBorder.setTitleJustification(TitledBorder.CENTER);
sectorSlider.setBorder(sectorSliderBorder);
sectorSlider.add(sectorNumberSlider);

will not display the current value in the border where I want it to.

That is because you have not changed a property of the Border.

All you have done is change the value of the variable. That variable is in no way associated with the Border. You just used the value of the variable to initially set the title of the Border when you created the Border.

The code in the ChangeListener should be:

sectorSliderBorder.setTitle( ... );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM