Hey, I’m trying to make a simple program that renders a bunch of squares on a JPanel. It isn’t a game in of itself, but more of a base for some game stuff I want to do. Unfortunately, I’m having some really weird graphical glitches when I run it, and I was wondering if yalls had any suggestions.
Here is the relevant code I have:
public class Game
{
public static GUILayer GUI;
public static DataLayer data;
public static LogicLayer logic;
public static void main(String[] args)
{
GUI = new GUILayer();
data = new DataLayer();
logic = new LogicLayer();
}
}
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class GUILayer extends JPanel
{
public static final int TILE_WIDTH = 20;
public static final int GAP_WIDTH = 2;
public static final Color GAP_COLOR = new Color(61, 131, 196);
public GUILayer()
{
this(800,600);
}
public GUILayer(int width, int height)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width, height);
frame.setVisible(true);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.add(this);
}
public void draw(Graphics g) //I think this is the function that is acting up.
{
//Draw the tiles
Graphics2D g2d = (Graphics2D)g.create();
//Calculate the dimensions of the tile
int rectWidth = TILE_WIDTH + 2 * GAP_WIDTH;
//Render the grid of tiles
for(int i = 0; i < Game.data.getTileArray().length; i++)
{
for(int q = 0; q < Game.data.getTileArray()[0].length; q++)
{
g2d.setColor(GAP_COLOR);
g2d.drawRect(i * rectWidth, q * rectWidth, rectWidth, rectWidth);
g2d.setColor(Game.data.getTileArray()[i][q].getColor());
g2d.drawRect(i * rectWidth + GAP_WIDTH, q * rectWidth + GAP_WIDTH, TILE_WIDTH, TILE_WIDTH);
}
}
}
}
public class LogicLayer
{
public LogicLayer()
{
//I think that this bit may be part of the problem.
//Tell the GUI layer to draw the tiles.
Game.GUI.draw(Game.GUI.getGraphics().create());
}
}
At the moment, all this program does is create a blank screen. I’m pretty sure that the problem is either in the LogicLayer’s constructor, or in the GUILayer.draw() function. At one point I was able to get the entire grid to render, and occasionally I get part of it, so I don’t think that it is the code that actually does the rendering or that sets up the JFrame.
I think it could be where I create the graphics object and call draw(), but I’m not sure. Graphics/Graphics2D objects are still a bit of a mystery to me. At any rate, I’d really appreciate any advice you may have.
: you should think of Graphics as a tools/way to draw/paint on an object and not as the recipient to receive draw/paint