applet如何使用java为测验系统制作秒表
多亏了我的大学,我真的卡住了。
我需要Java中的代码来有一个Stopwatch
,它以00:00:00(mm:ss:msms)
格式显示时间。我想使用按键事件来运行、暂停和重置计时器。比如,如果我按下S,秒表启动,P暂停,R重置。
问题是,我还想为团队添加数字上的关键事件,比如如果我按1,“团队1”会闪烁,最好是发出哔哔声,以此类推,用2
{
我写这篇文章是为了以秒打印时间,只是为了尝试
import java.awt.event.*;
import javax.swing.*;
public class StopWatch2 extends JLabel
implements KeyListener, ActionListener {
private long startTime;
private boolean running;
private Timer timer;
public StopWatch2() {
super(" Press S ", JLabel.CENTER);
addKeyListener(this);
}
public void actionPerformed(ActionEvent evt) {
long time = (System.currentTimeMillis() - startTime) / 1000;
setText(Long.toString(time));
}
public void keyPressed(KeyEvent e) {
int keyCode=e.getKeyCode();
if (keyCode==KeyEvent.VK_S) {
running = true;
startTime = e.getWhen();
setText("Running: 0 seconds");
if (timer == null) {
timer = new Timer(100,this);
timer.start();
}
else
timer.restart();
}
if(keyCode==KeyEvent.VK_P)
{
timer.stop();
running = false;
long endTime = e.getWhen();
double seconds = (endTime - startTime) / 1000.0;
setText("Time: " + seconds + " sec.");
}
}
public void keyTyped(KeyEvent e)
{}
public void keyReleased(KeyEvent e)
{}
}
import java.awt.*;
import javax.swing.*;
public class Test2 extends JApplet {
public void init() {
StopWatch2 watch = new StopWatch2();
watch.setFont( new Font("SansSerif", Font.BOLD, 24) );
watch.setBackground(Color.white);
watch.setForeground( new Color(180,0,0) );
watch.setOpaque(true);
getContentPane().add(watch, BorderLayout.CENTER);
}
}
我自己在试东西,我几乎是自学成才,所以我无法理解到底出了什么问题
# 1 楼答案
你是说: