Search code examples
javaswingjpanelcomponentsjprogressbar

Why is it that JProgressBar should not be changed once added to a JPanel?


Straight and Simple: Imagine we're on a class that extends JPanel

JProgressBar bar = new JProgressBar(0,0,10);
add(bar);

bar.setValue(5); //Works - You can visually see the change
bar = new JProgressBar(0,0,10);
bar.setValue(10); //Works - You can NOT visually see the change

Why's that?

And no, I couldn't find it anywhere that I looked. I searched for this specific question far and wide.


Solution

  • Java variables act (in effect) like pointers.

    You create a JProgressBar and add it to your JPanel - and store a pointer to this in the variable bar. When you call bar = new JProgressBar(0, 0, 10); you change what your pointer is pointing to, but do not change the original JProgressBar (the one which was added to your JPanel), you now have a new, different JProgressBar (which is not added to your JPanel), and so setting the value on it does not modify the one which is visible on your JPanel.

    This is the same reason that:

    String name = "Billy";
    String otherName = name;
    name = "Jimmy";
    System.out.println(otherName);
    

    will print Billy.