Runnable的run()方法无法正常工作

时间:2014-06-03 17:28:50

标签: java android runnable

我正在尝试建立一个游戏,而我正在借助教程来做这件事。我的问题是,我在下面显示的run()方法不起作用。我尝试了教程的示例代码,它是完全相同的run()方法,它的工作原理。 在我的代码中,run()永远不会被调用,我不明白为什么。

package thisproject;

public class StartingClass extends Applet implements Runnable, KeyListener,
        MouseListener {
    private Builder builder;
    private Image image,currentSprite, character,characterWalk, background;
    private Graphics second;
    private URL base;
    private static Background bg1;

    @Override
    public void init() {
        setSize(800, 400);
        setBackground(Color.BLACK);
        setFocusable(true);
        addKeyListener(this);
        Frame frame = (Frame) this.getParent().getParent();
        frame.setTitle("Castle Fight");


        try {
            base = getDocumentBase();
        } catch (Exception e) {
            // TODO: handle exception
        }

        // Image Setups
        background = getImage(base, "data/background2.png");
        character = getImage(base, "data/builder.png");
        currentSprite = character;
    }

    @Override
    public void start() {
        bg1 = new Background(0, 0);    
        builder = new Builder();   

        Thread thread = new Thread();
        thread.start();

    }

    @Override
    public void stop() {
        // TODO Auto-generated method stub
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    @Override
    public void run() {
        while (true) {
            System.out.println("this thing");
            builder.update();
            bg1.update();
            repaint();

            try {
                Thread.sleep(17);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }
    }

    @Override
    public void update(Graphics g) {
        if (image == null) {
            image = createImage(this.getWidth(), this.getHeight());
            second = image.getGraphics();
        }


        second.setColor(getBackground());
        second.fillRect(0, 0, getWidth(), getHeight());
        second.setColor(getForeground());
        paint(second);


        g.drawImage(image, 0, 0, this);
    }

    @Override
    public void paint(Graphics g) {
        g.drawImage(background, bg1.getBgX(), bg1.getBgY(), this);
        g.drawImage(currentSprite, builder.getCenterX() - 61, builder.getCenterY() - 63, this);
    }

    }
}

请记住,我拿出了导入和关键事件,因此代码没有占用太多空间,但我确实需要进行所有导入。 希望有人能给我一些启示。

1 个答案:

答案 0 :(得分:5)

您永远不会提供Runnable。变化

Thread thread = new Thread();
thread.start();

Thread thread = new Thread(this);
thread.start();