简体   繁体   中英

Java applet double buffer trouble (and loop trouble)

For some reason when I try to double buffer my Java applet it shows up a white square even though I'm not telling it to. Also if I try to put a loop in start() I get only a white screen even if repaint() is at the end.

/**
* @(#)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;
}

Put a check for size in the paint method. If the size has changed, create a new image and then draw to it, and store the new size information. Also, don't call repaint as you are just have a recursive call to paint.

If you put an unending loop in the start method then the thread never exits the start method.

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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM