初学Java Applet - 无法获得swing定时器功能

时间:2013-04-30 20:23:28

标签: java swing timer applet

我正在研究一个简单的java小程序,我想继续无限地添加秒数(所以会有一个g.drawString,它会不停地增加1秒。我已经在我的小程序中添加了一个swing计时器,而我想想applet将每1秒重新绘制一次(因为我已经在我的applet中将计时器设置为1秒)。我尝试了它,但applet每秒打印数千,而不是每秒。

import java.awt.*;
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

public class guitarGame extends Applet implements ActionListener, KeyListener {

Timer timer = new Timer (1000, this);
int amount;

public void init(){
    amount = 0;
    addKeyListener(this);
}

public void keyReleased(KeyEvent ae){}

public void keyPressed(KeyEvent ae){

    repaint();
}

public void keyTyped(KeyEvent ae){}

public void actionPerformed (ActionEvent ae){}
public void paint (Graphics g)
{
    amount += 1;
    g.drawString(amount+"Seconds",400,400);
    repaint();
}
}

任何帮助?

1 个答案:

答案 0 :(得分:1)

需要启动

javax.swing.Timer才能“点击”

“点击次数”在指定的actionPerformed

内的ActionListener方法内触发
public class guitarGame extends Applet implements ActionListener, KeyListener {

    Timer timer = new Timer (1000, this);
    int amount;

    public void init(){
        amount = 0;
        //addKeyListener(this);
        timer.setRepeats(true);
        timer.starts();
    }

    public void keyReleased(KeyEvent ae){}

    public void keyPressed(KeyEvent ae){

        repaint();
    }

    public void keyTyped(KeyEvent ae){}

    public void actionPerformed (ActionEvent ae){
        amount++;
        repaint();
    }
    public void paint (Graphics g)
    {
        // Do this or suffer increasingly bad paint artefacts
        super.paint(g);
        // This is the wrong place for this...
        //amount += 1;
        g.drawString(amount+"Seconds",400,400);
        // This is an incredibly bad idea
        //repaint();
    }
}