0

我正在开发一个简单的java小程序,我想无限地增加秒数(所以会有一个g.drawString不间断地增加1秒。我已经在我的小程序中放入了一个摆动计时器,我认为小程序将每 1 秒重新绘制一次(因为我在我的小程序中将计时器设置为一秒)。我试过了,但小程序每秒打印数千次,而不是一个。

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();
}
}

有什么帮助吗?

4

1 回答 1

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();
    }
}
于 2013-04-30T20:35:03.127 回答