繁体   English   中英

初学者Java Applet-无法使摆动计时器起作用

[英]Beginner Java Applet — Cannot get swing timer to function

我正在开发一个简单的Java小程序,我想不断增加秒数(因此会有一个g.drawString加上1秒不间断的时间。我在小程序中加入了一个摆动计时器,我认为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();
}
}

有什么帮助吗?

需要启动javax.swing.Timer才能“单击”

在分配的ActionListeneractionPerformed方法中触发“点击”

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM