Java小应用程序双缓冲区故障(和循环故障)


0

由于某些原因,当我尝试对我的Java小应用程序进行双缓冲时,即使我没有告诉它,它也会显示一个白色方块。另外,如果我尝试在start()中放置一个循环,即使重新绘制()结束,我也只会获得一个白色屏幕。

/** 
* @(#)vo4k.java 
* 
* vo4k Applet application 
* 
* @author William Starkovich 
* @version 1.00 2009/2/21 
*/ 

import java.awt.*; 
import java.applet.*; 
import java.awt.event.*; 
import java.awt.image.*; 

public class vo4k extends Applet implements KeyListener 
{ 
obj p1, e1; 
boolean[] keys; 
boolean end = false; 
Graphics g2d; 
Dimension size; 
Image buf; 

public void init() 
{ 
    keys = new boolean[256]; 

    for(int i = 0; i < 256; i++) 
     keys[i] = false; 

    addKeyListener(this); 
    p1 = new obj(); 
    p1.x = 0; 

    size = getSize(); 
    buf = createImage(size.width,size.height); 
    g2d = buf.getGraphics(); 
} 

public void keyTyped(KeyEvent e) {} 
public void keyPressed(KeyEvent e) {keys[e.getKeyCode()] = true;} 
public void keyReleased(KeyEvent e) {keys[e.getKeyCode()] = false;} 
public void controls() 
{ 
    if(keys[KeyEvent.VK_SPACE]) 
     end = true; 

    if(keys[KeyEvent.VK_W]) 
     p1.x += 10; 

} 

public void start() 
{ 
// while(!end) 
// { 


// } 
} 

public void paint(Graphics g) 
{ 

    controls(); 
    //g2d = (Graphics2D) g; 
    g2d.setColor(Color.RED); 
    g2d.fillRect(0,0,size.width,size.height); 
    g2d.setColor(Color.BLUE); 
    g2d.drawString("Welcome 2 Java!!", (int) 50, 60); 
    //g2d.drawString("Welcome to Java!!", (int) p1.x, 60); 


    g.drawImage(buf, 0, 0, this); 
    repaint(); 
} 
} 

class obj 
{ 
    double x,y,l,a,s; 
} 
1

在paint方法中检查大小。如果尺寸已更改,请创建一个新图像,然后绘制并保存新尺寸信息。另外,不要打电话重画,因为你只需递归调用绘画。

如果您在启动方法中放置了一个无止境的循环,那么线程永远不会退出启动方法。

public void paint(Graphics g) 
{ 

     controls(); 
     Dimension currentSize = getSize(); 
     if (! currentSize.equals(size)) { 
      size = currentSize; 
      buf = createImage(size.width,size.height); 
      g2d = buf.getGraphics(); 
     } 
     //g2d = (Graphics2D) g; 
     g2d.setColor(Color.RED); 
     g2d.fillRect(0,0,size.width,size.height); 
     g2d.setColor(Color.BLUE); 
     g2d.drawString("Welcome 2 Java!!", (int) 50, 60); 
     //g2d.drawString("Welcome to Java!!", (int) p1.x, 60); 


     g.drawImage(buf, 0, 0, this); 

}