我遵循了Java Hub关于在JFrame上绘制图像的教程。一切都很完美,除了JFrame基本上截取其背后的任何内容;例如:Eclipse。然后它无缘无故地成为背景。
这就是我得到的:
有什么想法吗?
Main.java:
package Package;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
public class Main extends JFrame {
BufferedImage sprite;
public Main(){
setSize(800, 600);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
init();
}
private void init(){
BufferedImageLoader loader = new BufferedImageLoader();
BufferedImage spriteSheet = null;
try {
spriteSheet = loader.loadImage("sprites2.png");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SpriteSheet ss = new SpriteSheet(spriteSheet);
sprite = ss.grabSprite(0, 0, 20, 32);
}
@Override
public void paint(Graphics g){
g.drawImage(sprite, 100, 100, null);
repaint();
}
public static void main(String[] args){
Main main = new Main();
}
}
SpriteSheet.java:
package Package;
import java.awt.image.BufferedImage;
public class SpriteSheet {
public BufferedImage spriteSheet;
public SpriteSheet(BufferedImage ss){
this.spriteSheet = ss;
}
public BufferedImage grabSprite(int x, int y, int width, int height){
BufferedImage sprite = spriteSheet.getSubimage(x, y, width, height);
return sprite;
}
}
BufferedImageLoader.java:
package Package;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class BufferedImageLoader {
public BufferedImage loadImage(String pathRelativeToThis) throws IOException{
URL url = this.getClass().getResource(pathRelativeToThis);
BufferedImage img = ImageIO.read(url);
return img;
}
}
没有例外被抛出......
答案 0 :(得分:1)
由于repaint()
方法中的paint()
调用,您的应用程序会挂起。这是一种递归调用,因为repaint()
调用paint()
。
您需要删除它,您的应用程序将不再挂起。
<小时/> 如果您只是从
repaint()
方法移除paint()
调用,则不会绘制图形,因为您在不调用超类的情况下覆盖了paint()
方法。它应该是这样的:
@Override
public void paint(Graphics g){
super.paint(g);
g.drawImage(sprite, 100, 100, null);
}
但是,它不会显示图像,因为在将其设置为可见后调用init()
方法。在设置框架可见之前调用它,它将起作用。
但是,这不是在JFrame
中放置背景图片的正确方法,您应该使用JPanel
代替:
class ImagePanel extends JPanel {
private Image image;
int x, y;
public ImagePanel(Image image, int x, int y) {
this.image = image;
this.x = x;
this.y = y;
}
@Override
protected void paintComponent(Graphics g) {
g.drawImage(image, x, y, null);
}
}
要打电话:
SpriteSheet ss = new SpriteSheet(spriteSheet);
sprite = ss.grabSprite(0, 0, 20, 32);
ImagePanel backgroundImagePanel = new ImagePanel(sprite, 100, 100);
setContentPane(backgroundImagePanel);
此外,移除paint()
替换JFrame
并调用init()
方法,然后设置框架可见