Question

My problem is the flickering produced while moving the circle in the frame. When i move it with keys, the circle disappears.

I need double buffer, but i dont know how to use it. Help my friends, i need your knowledge for this project!

solutions?

import javax.swing.JFrame; public class PruebaGraphics extends JFrame{ int x=130, y=130; public static void main(String[] args) { new PruebaGraphics(); } public PruebaGraphics() { this.setTitle("Dibujando sobre lienzo en java"); this.setSize(300,300); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); KeyListener pulsa = new KeyListener() { @Override public void keyTyped(KeyEvent ke) { throw new UnsupportedOperationException("Not supported yet."); @Override public void keyPressed(KeyEvent ke) { if(ke.getKeyCode()==39 && x+60<size().width) //derecha { x = x+10; } if(ke.getKeyCode()==40 && y+60<size().height) //abajo { y= y+10; } if(ke.getKeyCode()==38 && y-30>0) //Arriba { y = y-10; } if(ke.getKeyCode()==37 && x-10 > 0) //izquierda { x= x-10; } repaint(); } @Override public void keyReleased(KeyEvent ke) { } }; addKeyListener(pulsa); } @Override public void paint(Graphics g) { super.paint(g); g.fillOval(x, y, 50, 50); } }

Was it helpful?

Solution

You are drawing directly in the JFame, and if you read any of the Swing graphics answers on this site, you'll see that this is something that should not be done. Instead draw in the paintComponent method of a JPanel that is displayed by the JFrame. This will give your graphics automatic double buffering which will lead to smoother animation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top