Your application hangs due to the repaint()
call in the paint()
method. It is a recursive call, as repaint()
calls paint()
.
You need to remove it, and your application won't hang anymore.
If you simply remove the
repaint()
call from the paint()
method, your graphics won't be drawn, because you are overriding the paint()
method without calling the superclass one. It should be like this:
@Override
public void paint(Graphics g){
super.paint(g);
g.drawImage(sprite, 100, 100, null);
}
However, it will not display the image, because you call the init()
method after setting it visible. Call it before setting the frame visible and it will work.
However, this is not the correct way to put a background image in your JFrame
, you should use a JPanel
instead:
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);
}
}
To call it:
SpriteSheet ss = new SpriteSheet(spriteSheet);
sprite = ss.grabSprite(0, 0, 20, 32);
ImagePanel backgroundImagePanel = new ImagePanel(sprite, 100, 100);
setContentPane(backgroundImagePanel);
Also, Remove the paint()
override to the JFrame
and call the init()
method before setting the frame visible