-1

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.

  • 1
    *"I searched for this specific question far and wide."* It's the same with any component & setting the original variable to point to it. Instantiating a new component is not the same as actually adding that component on screen and making it visible. But then, what is the purpose of doing what you seem to be trying to do? – Andrew Thompson Jun 12 '18 at 17:20
  • It is assumed/suggested that you do your own research and look far and wide, so saying as much does not need to be part of the question. It does not help. Perhaps you could be more specific in your actual question. If someone else were asking you this question, how would they word it in a way that you best understood what they are asking? – SunSparc Jun 12 '18 at 17:37

1 Answers1

0

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.

BeUndead
  • 3,463
  • 2
  • 17
  • 21
  • Thank you, clarified. I know that about pointers, but I thought components added would store the component, so if it points to a different thing, the same happens to the one in the componentPane. – João Mendonça Jun 12 '18 at 23:41