Search code examples
javaswingjtextfieldjslider

Java JSlider.getvalue returns good value to JTextField, wrong to toolTipText


I work with NetBeans 7.2.

I have a JSlider slider_random in my JPanel1, entered the value 100, minimum 0, maximum 1000. I set a toolTipText for slider_random via properties (custom code):

"<html>Range (0-" + String.valueOf(slider_random.getMaximum()) + ")<br>Current: " + String.valueOf(slider_random.getValue())

Also placed a JTextField text_current and set the text to 100, This displays the value of slider_random when I change it.

I set stateChanged event to slider_random:

private void slider_randomStateChanged(javax.swing.event.ChangeEvent evt) {
    slider_random.setToolTipText("<html>Range (0-" + String.valueOf(slider_random.getMaximum()) + ")<br>Current: " + String.valueOf(slider_random.getValue()));
    jTextField1.setText(String.valueOf(slider_random.getValue()));
}

My problem is when I start the program and point to the slider it shows:

Range (0-1000)

Current: 50

Then move the slider a little, and move back to the original position (meanwhile I can see changes in text_current) all data become correct, and the tooltip says:

Range (0-1000)

Current: 100

What can cause my problem?

Here's the screenshot, after I lauched it.


Solution

  • I was able to repro your issue.

    The problem is that jSlider's default value is 50. You modified the value to 100, but this was not reflected in jSlider's setToolTip() method where you access jSlider's value (thru the custom code). It would show the old value of 50.

    To correct this, one solution is to create a mouse hover event on the slider, so that when you run your application and hover the mouse pointer over the slider, jToolTip method picks the latest value and shows you the same. It worked for me, so i'm sure it'll work for you.

    If i can think of a better solution, i'll post the same.