I’m doing a simple grid which each square is highlighted by the cursor:
They are a couple of JPanels, mapgrid and overlay inside a JLayeredPane, with mapgrid on the bottom. Mapgrid just draws on initialization the grid, its paint metodh is:
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
g2d.setColor(new Color(128, 128, 128, 255));
g2d.drawRect(tileSize * j, i * tileSize, tileSize, tileSize);
}
}
In the overlay JPanel is where the highlighting occurs, this is what is repainted when the mouse is moved:
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(new Color(255, 255, 128, 255));
g2d.drawRect((pointerX/tileSize)*tileSize,(pointerY/ tileSize)*tileSize, tileSize, tileSize);
}
I noticed that even though the base layer (mapgrid) is NOT repainted when the mouse moves, just the transparent overlay layer, the performance is lacking. If i give the overlay JPanel a background, its way faster. If i remove the mapgrid Antialiasing, its a bit faster too.
I don’t know why giving a background to the overlay layer (and thus, hiding the mapgrid) or disabling antialiasing in the mapgrid leads to much better performance.
Is there a better way to do this? Why does this happen?
Instead of
drawRectyour coulddrawLine. You should get the same visual result but I think it will be much faster.Also, if the background is always the same I would recommend drawing to a buffered image at initialization (or when the frame is resized) and then just draw that image. That should speed up the drawing.