我正在研究一个简单的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();
}
}
任何帮助?
答案 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();
}
}