在SWT的Label中点击实现倒计时,当倒计时结束时再次点击Label框再次开始倒计时,当倒计时没结束时点击时不做任何操作
时间: 2024-05-02 15:21:52 浏览: 77
以下是一个基于SWT的Label实现的倒计时示例代码,可以参考:
```java
public class CountDownLabel {
private Label label;
private int timeLeft;
private Timer timer;
public CountDownLabel(Composite parent, int style) {
label = new Label(parent, style);
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
startCountDown();
}
});
}
public void setTimeLeft(int timeLeft) {
this.timeLeft = timeLeft;
updateText();
}
private void updateText() {
label.setText(String.format("%02d:%02d", timeLeft / 60, timeLeft % 60));
}
private void startCountDown() {
if (timer != null) {
return; // 已经在倒计时中,不做任何操作
}
timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
timeLeft--;
if (timeLeft <= 0) {
stopCountDown();
} else {
Display.getDefault().asyncExec(() -> updateText());
}
}
};
timer.scheduleAtFixedRate(task, 0, 1000);
}
private void stopCountDown() {
if (timer != null) {
timer.cancel();
timer = null;
Display.getDefault().asyncExec(() -> updateText());
}
}
}
```
使用时可以创建一个CountDownLabel对象,设置初始倒计时时间,添加到界面中即可:
```java
CountDownLabel label = new CountDownLabel(shell, SWT.NONE);
label.setTimeLeft(60); // 初始倒计时时间为60秒
```
阅读全文