【发布时间】:2019-11-21 19:08:31
【问题描述】:
这里的问题是我的倒数计时器只是减去我点击“开始”按钮时输入的数字。我真的不知道在这里使用什么样的循环来让它像一个真正的倒数计时器......它是这样做的..while 吗?循环?还是while循环? 顺便说一句,我们必须只依赖线程和 GUI。
我尝试了for循环,但我不知道之后该使用什么。
package com.countdown;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
public class CountDown extends WindowAdapter implements ActionListener, Runnable {
@Override
public void run() {
}
public void stop() {
f.dispose();
}
JLabel l1, l2, l3;
JTextField tf1, tf2, tf3;
JButton btn1, btn2, btn3;
JFrame f;
JPanel p1, p2;
public CountDown() {
l1 = new JLabel("hrs:");
l2 = new JLabel("mins:");
l3 = new JLabel("sec:");
tf1 = new JTextField("", 5);
tf2 = new JTextField("", 5);
tf3 = new JTextField("", 5);
btn1 = new JButton("START");
btn2 = new JButton("STOP");
btn3 = new JButton("BACK");
p1 = new JPanel();
p2 = new JPanel();
f = new JFrame("Countdown Timer");
}
public void setLaunch() {
f.add(p1);
f.add(p2);
p1.add(l1);
p1.add(tf1);
p1.add(l2);
p1.add(tf2);
p1.add(l3);
p1.add(tf3);
p2.add(btn1);
p2.add(btn2);
p2.add(btn3);
f.setLayout(new GridLayout(2,1));
f.pack();
f.setSize(440,150);
f.setVisible(true);
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
f.addWindowListener(this);
}
public static void main(String[] args) {
CountDown cd = new CountDown();
cd.setLaunch();
Thread t1 = new Thread(cd); //hrs
Thread t2 = new Thread(cd); //mins
Thread t3 = new Thread(cd); //sec
Thread t4 = new Thread(cd); //stop
t1.start();
try {
t1.join();
}
catch(Exception e) {
System.out.println(e);
}
t2.start();
try {
t2.join();
}
catch(Exception e) {
System.out.println(e);
}
t3.start();
try {
t3.join();
}
catch(Exception e) {
System.out.println(e);
}
t4.stop();
}
@Override
public void actionPerformed(ActionEvent e) {
int hrs = Integer.parseInt(tf1.getText());
int mins = Integer.parseInt(tf2.getText());
int secs = Integer.parseInt(tf3.getText());;
if (hrs < 60) {
try {
Thread.sleep(1000);
hrs--;
}
catch (InterruptedException e1) {
e1.printStackTrace();
}
}
tf1.setText(Integer.toString(hrs));
if (mins < 60) {
try {
Thread.sleep(1000);
mins--;
}
catch (InterruptedException e1) {
e1.printStackTrace();
}
}
tf2.setText(Integer.toString(mins));
if (secs < 60) {
try {
Thread.sleep(1000);
secs--;
}
catch (InterruptedException e1) {
e1.printStackTrace();
}
}
tf3.setText(Integer.toString(secs));
}
public void windowClosing(WindowEvent e) {
f.dispose();
}
}
该程序的目标是:当我在小时、分钟和/或秒中输入一个数字时,它会在文本字段中倒计时。
【问题讨论】:
标签: java multithreading swing user-interface countdown