I am coding a 2d game using Java. I have created 2 classes: Main class and Game Panel class. paintComponenet() method is not invoked as expected. Below is the code.
package main;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
window.setTitle("2D Adventure");
GamePanel gamePanel = new GamePanel();
window.add(gamePanel);
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
gamePanel.startGameThread();
}
}
package main;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class GamePanel extends JPanel implements Runnable {
//SCREEN SETTINGS
final int originalTileSize = 16; //16x16 Tile
final int scale = 3;
final int tileSize = originalTileSize * scale; //48x48 Tile
final int maxScreenCol = 16;
final int maxScreenRow = 12;
final int screenWidth = tileSize * maxScreenCol; //768 pixels
final int screenHeight = tileSize * maxScreenRow; //576 pixels
Thread gameThread;
public GamePanel() {
this.setPreferredSize(new Dimension(screenWidth, screenHeight));
this.setBackground(Color.black);
this.setDoubleBuffered(true);
}
public void startGameThread() {
gameThread = new Thread(this);
gameThread.start();
}
@Override
public void run() {
while (gameThread != null) {
System.out.println("The game thread is running");
// 1. UPDATE: update character information
update();
// 2. DRAW: draw the character at fps
repaint();
}
}
public void update() {
System.out.println("Update method called");
}
public void paintComponenet(Graphics2D g) {
System.out.println("paintComponent method called");
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.white);
g2.fillRect(100, 100, tileSize, tileSize);
g2.dispose();
}
}
While the thread is running, I get,
The game thread is running
Update method called.
I am expecting a window with a black background and a white color square at 100, 100.
>Solution :
When overriding it, you misspelled it. It should be paintComponent(Graphics g)
It is also takes a Graphics instance.
@Override
public void paintComponent(Graphics g) {
System.out.println("paintComponent method called");
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.white);
g2.fillRect(100, 100, tileSize, tileSize);
}
To ensure you override the proper method, use that @Override annotation as I did above. Then if you misspell it, the compiler will complain. This is true for overriding any method.