0

I am attempting to add a "health bar" to a game in java. I have a painted background and am wondering how I would draw a smaller rectangle on top of that. Do I need to create a new Graphics member variable? All the examples I have looked at require me to create an entire class and are using somewhat foreign java utilities (at least to me). In my class that extends JPanel, I have the function:

public void paintComponent(Graphics g)
{ 
   // This draws the background
   g.setColor(Color.RED);
   g.fillRect(0, 0, this.getWidth(), this.getHeight());

   // This draws the health bar
   ...

Is there an easy way to do this?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Ryan
  • 35
  • 1
  • 5
  • No, just paint...graphics actions are compounding, just like painting on a real world canvas – MadProgrammer Feb 11 '17 at 04:13
  • Wait, what's wrong with the code you have? Please consider posting a valid [mcve] so we can test it ourselves. – Hovercraft Full Of Eels Feb 11 '17 at 04:13
  • [Conceptually, something like this](http://stackoverflow.com/questions/26618566/when-i-paint-a-background-image-onto-a-jpanel-it-behaves-different-under-window/26620302#26620302) – MadProgrammer Feb 11 '17 at 04:15
  • *"All the examples I have looked at require me to create an entire class"* - You could compartmentalize the concept, so the "actual" rendering is done by separate methods or classes, but your `paintComponent` method is what will be calling them and it will be passing the `Graphics` context it received to them so they can perform their work. This is actually a good idea, if you could come up with a concept of "layer", you could have the `paintComponent` simply loop through the layers and paint them, allowing you the freedom to add/remove /change layers as you wanted to – MadProgrammer Feb 11 '17 at 04:29

0 Answers0