Search code examples
javajlabel

When updating JLabel, previous text stays, and old text is placed on top of it


So, I'm making a program, and on the program, it displays your health in this format:

Health : 82/82

When you take Damage, I ask the program to update the JLabel, and it would display that you took damage like this

Health: 60/82

The JLabel is a public variable, and is only being created once,

public JLabel UIHealth = new JLabel();

and from then on is updated with the below code. Here is the code I use to update the UIHealth JLabel updating the text after an action occures:

UIHealth.setText("Health: "+Health+"/"+PlayerHealthBar.getMaximum()+"");

Is there a simpler way to display text that will be updated? Does it matter that my Frame and ALL panels are set to be transparent to see the image behind it that acts as a HUD? Here is the code I applied to everything that is transparent, but still interactive.

public Color Clear = new Color(0,0,0,0);

and I would of course call Clear when using the .setBackground component.

here is an image of after taking a bit of damage (4-5 hits) looks on the UI. (Take note of how the text just stacks on top of itself)

UI After taking a few hits

Thanks in advance for all your time. Please let me know and ask me if something seems unclear, or you need other snippets of my program.


Solution

  • You have a JPanel that you are adding your label to. You need to call myPanel.setOpaque(false); after creating it.