Yorrick Yorrick - 1 month ago 8
Java Question

Panel.repaint() doesn't seem to be refreshing panel

I'm having some issues repainting a JPanel on my GUI with default values.

The code I'm using right now is below, again, I'm not used to, nor really knowledgeable about java code, so forgive me for making rookie mistakes:

private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {
...

pnlWagens1 = new pnlWagens();
UpdateGUI();
}

private void UpdateGUI(){
pnlWagens1.repaint();
}


So far I've tried the above code, as well as setting the JPanel to null, repainting, inserting a new instance of the panel, repainting again.
Nothing so far has been fruitful, as in the end, I'm still stuck with the old panel (and it's values) being shown on my GUI.

Basically, I make a panel with a green background initially, make the background red, then resetting the panel to have a green background again. However in the end, after hitting Reset, it still shows the old panel with the red background.

Any insight as to what I may be doing wrong/overlooking would be greatly appreciated.

Answer

Assuming this is all the relevant code (and that UpdateGUI doesn't use add or remove with the panel reference you have there), then changing what object pnlWagens1 refers to in your local class won't change other references that still refer to the old object. The old object pnlWagens1 is still referenced by Swing in another location, from when you originally called add on some container.

What you need to do is to remove pnlWagens1 from the container, change pnlWagens1 like you are doing now, readd pnlWagens1 to the container, and call then call both revalidate() and repaint() on the container.