3
Hello, I made a program that moves a ball with the arrow keys on the keyboard only that keeps blinking the screen when it moves. I’ve seen other programs in this kind of mine that don’t keep blinking. If anyone can help me... (the background is normal but the ball is moving and blinks)
code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Cobrinha extends JFrame implements Runnable {
private Thread th = new Thread(this);
private int posEsq = 300;
private int posTop = 300;
private int ultTecla = 37;
public Cobrinha() {
super("Cobrinha");
this.setSize(600,600);
this.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
mover(e.getKeyCode());
}
});
this.getContentPane().setBackground(Color.GREEN);
th.start();
this.setVisible(true);
}
public void mover(int tecla) {
ultTecla = tecla;
}
public void run() {
while (true) {
switch (ultTecla) {
case 38: posTop--; break;
case 40: posTop++; break;
case 37: posEsq--; break;
case 39: posEsq++; break;
}
try { th.sleep(6); } catch (InterruptedException e) { }
this.repaint();
}
}
public void paint(Graphics g) {
super.paint(g);
g.fillOval(posEsq, posTop, 20, 20);
}
public static void main(String [] args) {
new Cobrinha();
}
}
As you may notice you received votes to close as unclear. The reason is certainly that you do not correctly explain what is "blinked", do not describe how is such a "ball" and also do not offer an example image of what happens. If that’s what I imagine, that wink is called flickering and it occurs because the total replenishment is happening to every frame. Inher from
JComponent
instead ofJFrame
that should help because of double buffering. Give a read on my other answer (and on what it links) to understand the details: http://answall.com/a/14283/73– Luiz Vieira