I created a 600 x 600 grid for a TicTacToe game, but every time I try to get the image(Using the getImg()
method), it shows a white screen. The JPanel's background is darkGray, it neither draws the grid, nor does it show the JPanel background.
This is the code, I haven't tried anything
PanelManager.java
package TicTacToe.display.panel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class PanelManager extends JPanel implements Runnable{
Thread t;
BufferedImage grid;
public PanelManager() {
this.setPreferredSize(new Dimension(600,600));
this.setBackground(Color.darkGray);
this.setDoubleBuffered(true);
this.startThread();
}
public void getImg() {
try {
grid = ImageIO.read(getClass().getResourceAsStream("/TicTacToe/grid/grid.png"));
}
catch (IOException e) {
e.printStackTrace();
}
}
public void startThread() {
t = new Thread(this);
t.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.drawImage(grid,300,300,600,600,null);
g2.dispose();
}
public void update() {
}
public void run() {
while(t != null) {
update();
try {
Thread.sleep(10);
}
catch (Exception e) {}
repaint();
}
}
}
FrameManager.java
package TicTacToe.display;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import TicTacToe.display.panel.PanelManager;
public class FrameManager {
public static void main(String[] args) {
JFrame f = new JFrame();
PanelManager pm = new PanelManager();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setTitle("TicTacToe Windowed Edition");
f.setResizable(false);
f.setVisible(true);
f.setSize(600,600);
f.setLocationRelativeTo(null);
f.add(pm);
}
}