2
我試圖使用2個面板堆棧彼此的遊戲,第一個面板是爲所有的瓷磚和所有的遊戲對象繪製在其上的畫布,第二個是用於頂部圖層框架,我有PNG具有透明背景和圖像將包含JTextBox
,JTabbedPanel
和JLabel
堆疊JPanel重新繪製不正確
我的問題是,當我重繪帆布,頂部框架的一部分變得覆蓋的畫布。
這是爲什麼?當我在畫布上添加JButton
時,JButton
在我的頂部框架面板上繪製。
編輯:
我一直在使用JLayeredPane的嘗試,但還是給了我同樣的結果。
// initComponent from MyGame
private void initComponent() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("My Game");
this.setSize(320, 240);
this.setLayout(null);
this.setUndecorated(true);
this.setResizable(false);
JLayeredPane layered = this.getLayeredPane();
layered.add(new Canvas(), 0);
layered.add(new TopFrame(), 1);
}
這種頂部框架和我的畫布:
我得到|我想
主要
@SuppressWarnings("serial")
public class MyGame extends JFrame {
public MyGame() {
this.initComponent();
}
private void initComponent() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("My Game");
this.setSize(320, 240);
this.setLayout(null);
this.setUndecorated(true);
this.setResizable(false);
this.add(new TopFrame());
this.add(new Canvas());
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame game = new MyGame();
game.setVisible(true);
}
});
}
}
TopFrame
@SuppressWarnings("serial")
public class TopFrame extends JPanel {
private static final int FRAME_WIDTH = 320;
private static final int FRAME_HEIGHT = 240;
private BufferedImage bgImage;
public TopFrame() {
this.initComponent();
}
private void initComponent() {
this.setLayout(null);
this.setBounds(0, 0, FRAME_WIDTH, FRAME_HEIGHT);
bgImage = new BufferedImage(FRAME_WIDTH, FRAME_HEIGHT, BufferedImage.TYPE_4BYTE_ABGR_PRE);
try {
bgImage = ImageIO.read(new File("FRAME.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bgImage, 0, 0, this);
}
}
帆布
@SuppressWarnings("serial")
public class Canvas extends JPanel {
private static final int CANVAS_WIDTH = 227;
private static final int CANVAS_HEIGHT = 240;
BufferedImage image;
BufferedImage imgBuffer;
Graphics2D g2d;
public Canvas() {
this.initComponent();
}
private void initComponent() {
Timer timer = new Timer();
this.setBounds(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
imgBuffer = new BufferedImage(CANVAS_WIDTH, CANVAS_HEIGHT, BufferedImage.TYPE_4BYTE_ABGR_PRE);
g2d = imgBuffer.createGraphics();
try {
image = ImageIO.read(new File("tile.png"));
} catch (IOException e) {
e.printStackTrace();
}
timer.schedule(new TimerTask(){
@Override
public void run() {
drawComponent();
repaint();
}
}, 0, 100);
}
public void drawComponent() {
/* will do tile drawing */
g2d.drawImage(image, 0, 0, this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(imgBuffer, 0, 0, this);
}
}
是否可以讓我的畫布在底部繪製所有包含的對象?
請不要在標題中添加_ [已解決] _等標籤。而是發表一個答案(就像你做的那樣),並接受它。 –