简体   繁体   中英

Runnable java applet works only when resizing

This small applet is supposed to move a String from the bottom to the top of applet frame, when it reaches top it should start from the bottom again. Problem is it's only moving when I resize the applet window. It doesn't move itself, why does it works that way?

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

public class Zad1 extends Applet implements Runnable {

    Thread runner;
    int yPos = 500;

    public void start() {
        if (runner == null) {
            runner = new Thread(this);
        }
    }

    public void stop() {
        if (runner != null) {
            runner = null;
        }
    }

    public void run() {
        while (true) {
            repaint();
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }

    public void paint(Graphics g) {
        g.drawString("Hello java", 50, yPos);
        yPos--;
        if (yPos < -30)
            yPos = 500;
    }
}

The thread is not started

        runner = new Thread(this);
        runner.start(); // <----------- Insert this!

But note that the style of this applet is bad in many ways (eg there should be no logic in "paint", you should probably not overwrite "paint" of an Applet at all, you should consider a JApplet, etc...). You should probably read http://docs.oracle.com/javase/tutorial/uiswing/components/applet.html and other examples.

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