gpt4 book ai didi

java - 初级 Java Applet — 无法让 Swing 计时器运行

转载 作者:行者123 更新时间:2023-12-01 14:37:55 24 4
gpt4 key购买 nike

我正在开发一个简单的java小程序,我想无限地增加秒数(所以会有一个g.drawString不停地增加1秒。我已经在我的小程序中放入了一个 Swing 计时器,并且我计算出小程序将每 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();
}
}

有什么帮助吗?

最佳答案

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

“点击”在分配的 ActionListener 内的 actionPerformed 方法中触发

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

关于java - 初级 Java Applet — 无法让 Swing 计时器运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16308376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com