该代码实现了一个时钟动画,用于显示倒计时剩余时间。具体实现方法是在 run() 方法中不断计算剩余时间并重绘界面,直到剩余时间为 0 时弹出一个窗口。该类继承了 JPanel 类,并实现了 Runnable 接口,因此可以在 Swing 中使用。其中,start() 方法用于启动时钟动画线程,stop() 方法用于停止线程,getUsedTime() 方法用于获取已使用的时间。

package lianliankan;

import java.awt.*;
import javax.swing.*;


public class ClockAnimate extends JPanel
    implements Runnable {

  private volatile Thread thread;
  long startTime = 0l;
  long restTime = 0l;

  Color color = new Color(0, 0, 0);
  //Color jfcBlue = new Color(255, 255, 0);
  //Color jfcBlue = new Color(55, 77, 118);
  Font font48 = new Font('serif', Font.PLAIN, 20);
  java.text.DecimalFormat df = new java.text.DecimalFormat('000');
 

  public ClockAnimate() {
    this.setMinimumSize(new Dimension(156, 48));
    this.setPreferredSize(new Dimension(156, 48));
  }

  
  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    Dimension d = getSize();
    g2.setBackground(new Color(255, 255, 255));
    g2.clearRect(0, 0, d.width, d.height);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setColor(color);
    g2.setFont(font48);

    g2.drawString('剩余时间:' + getTime(), 16, 40);
  }

  
  String getTime() {
    int sec, ms;
    long time;
    time = restTime;
    sec = Math.round(time);//算时
    time -= sec * 1000;
    
    return (df.format(sec));
  }

  public void start() {
    startTime = System.currentTimeMillis();
    thread = new Thread(this);
    thread.start();
  }

  public void run() {
    Thread currentThread = Thread.currentThread();

    while (thread == currentThread) {
      long time = System.currentTimeMillis();
      restTime = startTime/1000-time/1000+200;  //设置剩余时间
      if(restTime==0){
        TimeOut frame=new TimeOut(); 
    
        frame.setTitle('TimeOut');
        frame.setSize(620,393);
        Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
        int screenWidth = screenSize.width;
        int screenHeight =screenSize.height;
        int x=(screenWidth-frame.getWidth())/2;
        int y=(screenHeight-frame.getHeight())/2;
        frame.setLocation(x+78,y+21);
        frame.setVisible(true);
        
        break;
      }
      try {
        repaint();
        thread.sleep(100l);
      } catch (InterruptedException ex) {
      }
    }
    
  }

  //线程停止
  public void stop() {
    if (thread != null) {
      thread = null;
    }
  }

  
  public int getUsedTime() {
    return Math.round(restTime);
  }

}
Java Swing 倒计时动画实现 - ClockAnimate 类

原文地址: https://www.cveoy.top/t/topic/n5ko 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录