Graphics2D.drawImage not working
I'm trying to come up with my own game using Java AWT after watching a few video tutorials. However, I encountered a problem where I cannot draw an external image file that I loaded using the BufferedImage object.
The problem seems to be on the method that I'm using to draw the image on the screen, where I'm using Graphics2D.drawImage() method to draw.
Here is part of my code (I modified and skipped parts that seemed irrelevant to the topic):
Window Class
public class Window extends JPanel{
public Window(int width, int height) {
JFrame frame = new JFrame("Zerro's Game");
frame.setPreferredSize(new Dimension(width, height));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
frame.pack();
}
}
Game Class
public class Game extends JFrame implements Runnable {
// Dimension for Main Frame
private static final int WIDTH = 640;
private static final int HEIGHT = 480;
// Image
private BufferedImage image;
private Graphics2D g;
public void run() {
this.requestFocus();
// For rendering purposes
image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
g = (Graphics2D) image.getGraphics();
//Game Loop
long now;
long updateTime;
long wait;
final int TARGET_FPS = 60;
final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;
while (isRunning) {
now = System.nanoTime();
update();
render();
updateTime = now - System.nanoTime();
wait = (OPTIMAL_TIME - updateTime) / 1000000;
try {
Thread.sleep(wait);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void render() {
if(gameState == STATE.GAME) {
handler.render(g);
} else if(gameState == STATE.MENU) {
menu.render(g);
}
}
Menu Class
public class Menu extends KeyAdapter{
private BufferedImage image;
public void render(Graphics2D g) {
try {
image = ImageIO.read(getClass().getResource("/Pixel_Background.png"));
g.drawImage(image, 0, 0, null);
} catch(Exception e) {
e.printStackTrace();
}
}
}
This code results in making empty frame without any content inside. I confirmed that it properly loads an image by using System.out.println(image.getHeight()) which prints out the exact height of an image that I'm using.
I've seen some comments in the internet that I need to use paintComponent() method. However, I'm just wondering if it's not a good idea to use paintComponent() in game development as the video tutorials (3 of them) that I watched didn't use such method to draw images.
Also, I'm wondering about the reason why we pass in the Graphics2D object as parameter in all the render() methods.