Ok, so I have been working on trying to get together some simple 2D demos in Java. I have been looking at using a JFrame/JPanel combination.
I was using a Timer and implementing ActionListener and this was working well, but I saw that most people were using a Thread and implementing Runnable so that the animations would work correctly. I tried doing this myself and have got it mostly working.
What is odd is now that I have implemented double buffering I have some flicker, when without it I was getting no flicker at all. The entire image is not flickering, only when two different images are drawn on top of each other. My entire background doesn't flicker at all. But when I try to draw my character it flickers whether it is moving or not. Almost as if java is redrawing them, but out of z-order sometimes causing a flicker.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public void run() { bRunning = true; while (bRunning) { updateBoard(); renderBoard(); repaint(); } try { Thread.sleep(20); } catch(InterruptedException ie) { System.err.println("Error: Thread exception!"); } System.exit(0); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| private void renderBoard() { if (frameBuffer == null) { frameBuffer = createImage(WIDTH, HEIGHT); if (frameBuffer == null) { System.err.println("Error: frameBuffer is null"); } else gDevice = frameBuffer.getGraphics(); } gDevice.drawImage(background, bX[0], 0, null); gDevice.drawImage(background, bX[1], 0, null); gDevice.drawImage(background, bX[2], 0, null); gDevice.drawImage(background, bX[3], 0, null); gDevice.drawImage(gChar.getImage(), gChar.getX(), gChar.getY(), null); } |
1 2 3 4 5 6 7 8
| public void paintComponent(Graphics gDevice) { super.paintComponent(gDevice); if (frameBuffer != null) { gDevice.drawImage(frameBuffer, 0, 0, null); } } |
Anyone have any ideas?