Search code examples
javaswingjframejbutton

Bakckground gets drawn over Buttons


I have GUI(JFrame) with some Buttons. I also juse the paint(Graphics G) methode to draw a shape (for the game I am woarking on).

I want to draw a background so I put that first in the paint methode:

 public void paint(Graphics g){
    super.paintComponents(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.drawImage(img,0,20,null);
    
    //167,230      288,409
    g2.dispose();
    }

But the Image gets drawn over the Buttons but not over the first(the on with the lower X coordinate) and when I hover over the place where the other Buttons are placed then they get Drawn too but till then they are "Invisibil".

How can I draw the Image really as Bakckground so it dosend get Painted over other Objeckts?

First I tryed put the Buttons on FocusPainted = true but that doesend worked.

Then I tryed to draw the Image only the first Time the paint Component gets Called so it only overlays the Buttons at first loading but then stays behind them.

public void paint(Graphics g){
    super.paintComponents(g);
    Graphics2D g2 = (Graphics2D) g;
    
    tower1.draw(g2);
    tower2.draw(g2);
    tower3.draw(g2);
    
    if (firstPaint == false) {
      g2.drawImage(img,0,0,null);
      firstPaint = true;
    } // end of if
    
    
    g2.dispose();
    }

But when the it gets repainted the Image disappers....

Then I tryed use the JFrame own Graphis : this.getContentPane().getGraphics().drawImage(img,0,0,null); then the the GUI dosend even load.


Solution

  • I found a solution. There is a methode UpdateUI which I can call after drawing the image. This makes the JPannel drawn them after the Image.

    THX alot for your help with you coments I found out a lot more then I needed which will help me on my journy!