Java 如何在JLabel中显示计时器
我想在JLabel中显示计时器。所以我构建了这段代码,它可以工作,但我不知道这段代码是否正确Java 如何在JLabel中显示计时器,java,swing,Java,Swing,我想在JLabel中显示计时器。所以我构建了这段代码,它可以工作,但我不知道这段代码是否正确 public void cswing(){ labelTempoGara = new TimeRefreshRace(); labelTempoGara.start(); } @SuppressWarnings("serial") class TimeRefreshRace extends JLabel implements Runnable { private boolean
public void cswing(){
labelTempoGara = new TimeRefreshRace();
labelTempoGara.start();
}
@SuppressWarnings("serial")
class TimeRefreshRace extends JLabel implements Runnable {
private boolean isAlive = false;
public void start() {
threadTempoCorsa = new Thread(this);
isAlive = true;
threadTempoCorsa.start();
}
public void run() {
int tempoInSecondi = programma.getTempoGara() % 60;
int minuti = programma.getTempoGara() / 60;
while (isAlive) {
try {
if (minuti <= 0 && tempoInSecondi<=1) {
isRun=false;
this.setText("00:00");
isAlive = false;
salvaDatiCorsa();
break;
}
if(tempoInSecondi<=1){
minuti--;
tempoInSecondi=60;
}
--tempoInSecondi;
this.setText(minuti+":"+ tempoInSecondi);
Thread.sleep(1000);
} catch (InterruptedException e) {
log.logStackTrace(e);
}
}
}
public void kill() {
isAlive = false;
isRun=false;
}
}//fine autoclass
public void cswing(){
labelTempoGara=新的TimeRefreshRace();
labelTempoGara.start();
}
@抑制警告(“串行”)
类TimeRefreshRace扩展JLabel实现可运行{
private boolean isAlive=false;
公开作废开始(){
threadTempoCorsa=新线程(此线程);
isAlive=真;
threadTempoCorsa.start();
}
公开募捐{
int tempoinsondi=programma.getTempoGara()%60;
int minuti=programma.getTempoGara()/60;
当(我活着){
试一试{
if(minuti这里是用javax.swing.Timer
因为您还没有提供一个可运行的示例,所以我无法测试它是否有效,但我希望您可以修复存在的问题
注意不要导入java.util.Timer
这是另一个类,它也需要与Swing线程同步(就像您示例中的线程)
类TimeRefreshRace扩展JLabel实现ActionListener{
私人定时器;
公开作废开始(){
定时器=新定时器(1000,此);
timer.start();
}
已执行的公共无效行动(行动事件ae){
int tempoinsondi=programma.getTempoGara()%60;
int minuti=programma.getTempoGara()/60;
if(minuti)使用javax.swingTimer Luke。在swing线程(事件调度程序线程)之外修改swing组件可能会产生无法解释的问题。
class TimeRefreshRace extends JLabel implements ActionListener {
private Timer timer;
public void start() {
timer = new Timer(1000, this);
timer.start();
}
public void actionPerformed(ActionEvent ae) {
int tempoInSecondi = programma.getTempoGara() % 60;
int minuti = programma.getTempoGara() / 60;
if (minuti <= 0 && tempoInSecondi<=1) {
this.setText("00:00");
salvaDatiCorsa();
break;
}
if(tempoInSecondi<=1){
minuti--;
tempoInSecondi=60;
}
--tempoInSecondi;
this.setText(minuti+":"+ tempoInSecondi);
}
public void kill() {
if (timer != null) {
timer.stop()
}
}
}//fine autoclass