[英]flickering with method paint java
我的問題是在框架中移動圓圈時產生的閃爍。 當我用鍵移動它時,圓圈消失了。
我需要雙緩沖區,但我不知道如何使用它。 幫助我的朋友,我需要你對這個項目的了解!
解決方案?
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);
}
}
您直接在 JFame 中繪圖,如果您閱讀了本網站上的任何 Swing 圖形答案,您會發現這是不應該做的事情。 而是在 JFrame 顯示的 JPanel 的paintComponent 方法中繪制。 這將使您的圖形自動雙緩沖,從而使動畫更流暢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.