[英]How do you add a JPanel onto another JPanel that has graphics?
基本上,我想做的就是使用paintComponent()方法將一個JPanel添加到另一個在其上繪制了圖形的JPanel上。 但是我試圖添加的JPanel沒有顯示,因為它被帶有圖形的JPanel所掩蓋。
如何做到這一點,以便在將JPanel添加到一個帶有圖形的JPanel時,它將在前面顯示JPanel而不是被Graphics遮蓋?
感謝所有答案! :)
如果您需要代碼,請告訴我,我很樂意將其放在此處。
好了,這里是代碼:
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); } }
這是我要添加到游戲JPanel中的JPanel的代碼
public class Inventory extends JPanel { public Inventory() { setLayout(null); setSize(400, 300); setBackground(Color.BLACK); addKeyListener(this); setFocusable(true); } }
提醒一下:java.awt和javax.swing混合不好。 當您在一個面板上繪畫東西並嘗試向其添加JPanel時,您肯定會在某個地方遇到問題。 更好的解決方案是擁有2個不同的JPanel,一個用於圖形,另一個用於庫存。
像這樣:
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);
這將使您的揮桿和awt組件不會混合,並為您節省很多麻煩。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.