开发者

How do you add a JPanel onto another JPanel that has graphics?

Basically what im trying to do is to add a JPanel onto another JPanel that has painted graphics on it using the paintComponent() method. But the JPanel I am trying to add is not shown because it is covered up by the JPanel w/ Graphics on it.

How can I make it so that when I add the JPanel to the one w/ graphics it will show the JPanel in the front instead of being covered up by the Graphics?

All answers are appreciated! :)

If you need the code just tell me and I 开发者_高级运维will gladly put it on here.

Alright here is the code:

package javavideogame;
public class Game extends JPanel implements ActionListener, Runnable
{

 public Game(MainCharacter character)
 {
     setLayout(null);
     setFocusable(true);

 }


 public void paintComponent(Graphics g)
 {
     super.paintComponent(g);
     g.drawImage(ground, 0, 0, this);
     g.drawImage(character.getImage(), character.getX(), character.getY(), this);
     g.setColor(Color.RED);
     g.drawRect(10, 10, character.getMaxHealth(), 10);
     g.fillRect(10, 10, character.getHealth(), 10);
     g.dispose();
 }

 public void getInventoryScreen()
 {
     Main.inv = new Inventory();
     Main.game.add(Main.inv);
 }
}

And here is the code for the JPanel that I'm adding to the Game JPanel

public class Inventory extends JPanel
{
     public Inventory()
     {
         setLayout(null);
         setSize(400, 300);
         setBackground(Color.BLACK);
         addKeyListener(this);
         setFocusable(true);
     }
}


Custom painting is done by overriding the paintComponent(...) method. My guess is that you are overriding the paint() method.

Read this section from the Swing tutorial on Custom Painting. Because you are overriding the wrong method, you end up painting the children first and then the custom painting is done on top.

If you need more help than post your SSCCE demonstrating the problem.


Just a reminder: java.awt and javax.swing don't mix well. When you're painting stuff on one panel AND trying to add a JPanel to it, you are bound to run into problems somewhere. A far better solution is to have 2 different JPanels, one for your graphics, and one for your inventory.

Something like this:

JPanel mainPanel = new JPanel(); //will hold BOTH panels
JPanel gamePanel = new Game(myCharacter); //declare game panel
JPanel inventoryPanel = new Inventory(); //declare inventory panel

//set up some layout
mainPanel.setLayout(new GridLayout(2, 1));

//add the graphics panel, then add the inventory
mainPanel.add(gamePanel);
mainPanel.add(inventoryPanel);

This will keep your swing and awt components from mixing and save you a lot of headaches.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜