我遵循了 Java Hub 上关于在 JFrame 上绘制图像的教程。一切都完美无缺,除了 JFrame 基本上会截取其背后的任何内容;例如:日食。然后它无缘无故地成为背景。
这就是我得到的:
有任何想法吗?
主.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;
}
}
没有异常被抛出...