[英]How to bring an image to the foreground in Java?
I'm trying to create a Pacman game in Java, and so far I've displayed the background image (the blue and black maze), but I'm having trouble showing the image of Pacman. 我正在尝试用Java创建Pacman游戏,到目前为止,我已经显示了背景图像(蓝色和黑色迷宫),但是在显示Pacman图像时遇到了麻烦。 When I try to display him in the same method with which I displayed the background, he doesn't appear unless I slightly manually alter the size of the Jframe. 当我尝试以与显示背景相同的方法来显示他时,除非我稍微手动更改Jframe的大小,否则他不会出现。 And even then when he appears there's a small white square in the bottom right corner of his image. 即使这样,当他出现时,他的图像的右下角仍然有一个白色小方块。 What can I do to fix this? 我该怎么做才能解决此问题? Is there any other way I can insert the pacman image in that works? 还有其他方法可以插入pacman图片吗?
This is the code: 这是代码:
JFrame window = new JFrame();
ImageImplement pacman = new ImageImplement(new ImageIcon("C:\\Users\\16ayoubc\\Desktop\\Pacman-moving.gif").getImage());
ImageImplement panel = new ImageImplement(new ImageIcon("C:\\Users\\16ayoubc\\Desktop\\background.png").getImage());
pacman.setLocation(255, 255);
pacman.setVisible(true);
pacman.setOpaque(true);
window.add(pacman);
window.add(panel);
window.setVisible(true);
window.setSize(576,655);
window.setName("Pacman");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
将窗口直接插入的JLayeredPane用作容器,并在添加组件时指定组件的深度 (z顺序)。
window.add(pacman);
window.add(panel);
You're adding pacman before you add the background, so it is drawing over the pacman sprite and you are not seeing it. 您在添加背景之前先添加了pacman,所以它在pacman精灵上绘制,您看不到它。 Make sure you draw your items in the game in reverse order, so draw the background first, then pacman. 确保以相反的顺序绘制游戏中的物品,因此先绘制背景,然后绘制pacman。
window.add(pacman);
window.add(panel);
You can't add two components to the CENTER of a BorderLayout. 您不能将两个组件添加到BorderLayout的CENTER中。
If you want the pacman to appear on the panel then you add the pacman to the window: 如果要让吃豆人出现在面板上,则将吃豆人添加到窗口中:
//window.add(pacman);
panel.add(packman)
window.add(panel);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.