java实现倒计时界面有开始和暂停,时间格式是05:00,秒和毫秒当时间为00:00是,没按下暂停键,显示你输了
1个回答
展开全部
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Sample{
private static int sec, ms;
private static boolean flag = true;
private static JTextField txt;
static class Timer extends Thread{
@Override
public void run() {
while(flag){
if(ms == 0){
ms = 99;
sec--;
}else{
ms--;
}
txt.setText(String.format("%2d:%2d", sec, ms));
if(txt.getText().equals("00:00")){
flag = false;
}
try {
Thread.sleep(10);
} catch (InterruptedException e1) {
}
}
}
}
public static void main(String[] args) {
final JFrame w = new JFrame();
w.setSize(200, 100);
w.setTitle("小程序");
w.setLocationByPlatform(true);
w.setLayout(new FlowLayout());
txt = new JTextField(12);
txt.setText("05:00");
w.add(txt);
JButton start = new JButton("开始");
start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
sec = Integer.parseInt(txt.getText().split(":")[0]);
ms = Integer.parseInt(txt.getText().split(":")[1]);
new Timer().start();
}
});
w.add(start);
JButton stop = new JButton("暂停");
stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
flag = false;
String msg = null;
if(txt.getText().equals("00:00")){
msg = "胜利!";
}else{
msg = "你输了";
}
JOptionPane.showConfirmDialog(w, msg, "提示", 0);
}
});
w.add(stop);
w.setVisible(true);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询