Java repaint is slow under certain conditions.

Posted by Gabriel A. Zorrilla on Stack Overflow See other posts from Stack Overflow or by Gabriel A. Zorrilla
Published on 2010-03-26T02:15:32Z Indexed on 2010/03/26 2:23 UTC
Read the original article Hit count: 450

Filed under:
|
|

I'm doing a simple grid which each square is highlighted by the cursor: alt text

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about repaint