I'm writing a small JAVA applet.

Which gets a random number between 1 to 6 and prints them on APPLET screen. What i want to do is.. Loop 50 times on screen and print various randdom numbers. [Each time clearing the previous number].

And after that loop.. It prints any 1 final random number on applet..

My problem is: The loop. It is printing all numbers over each ither and screen is not getting cleared. What is wrong? I have tried many methods of clearing applet screen like drawing rectangle or using clearRect() function. Nothing is working. Here's the code.

import java.applet.Applet;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.util.Random;



public class Shapes extends Applet{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    Random r = new Random();
    Dimension d = getSize();
    Font f = new Font("TimesRoman", Font.BOLD, 96);
    public void paint(Graphics g)
    {
        for(int m=0;m<=50;m++){     
                int k = Math.abs((r.nextInt()) % 6) + 1;
                g.setFont(f);
                g.setColor(Color.BLACK);
                g.drawString(String.valueOf(k) , 70, 100);  
                g.setColor(Color.WHITE);
                g.drawRect(0, 0, d.width, d.height);
                try{Thread.sleep(70);}catch(Exception e){}
        }



    }

}
有帮助吗?

解决方案

The matter is that at object creation time, the applet hasn't got size, so you must wait to get the dimension of the applet. For example, at render time, like this:

public void paint(Graphics g)
{
    d = getSize();
    for(int m=0;m<=50;m++){
        g.clearRect(0, 0, (int) d.getWidth(), (int) d.getHeight());

        int k = Math.abs((r.nextInt()) % 6) + 1;
        g.setFont(f);
        g.setColor(Color.BLACK);
        g.drawString(String.valueOf(k) , 70, 100);
        try{Thread.currentThread().sleep(70);}(Exception e){}
    }
}

其他提示

Remember that paint(Graphics) is on the event dispatch thread so sleeping it will freeze the entire UI. You need to use asynchronous repaints like this:

public void init(){
    Timer t=new Timer(70, new ActionListener(){
        public void actionPerformed(ActionEvent e){repaint();}
    });
    t.setCoalesce(true);
    t.setRepeats(true);
    t.start();
}
public void paint(Graphics g){...}
public void paint(Graphics g)
{
    // ..

Should be:

public void paint(Graphics g)
{
    super.paint(g); // VERY IMPORTANT! Draw BG and borders etc.  
    // ..
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top