在SWT的Label中点击实现倒计时,当倒计时结束时再次点击Label框再次开始倒计时,当倒计时没有结束时再次点击Label框会在控制面板输出'请等待'
时间: 2024-05-01 14:17:07 浏览: 49
这是一个可能的实现方式:
```java
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
public class CountDownLabel {
private static final int COUNTDOWN_SECONDS = 10;
private static final Color COLOR_DEFAULT = Display.getDefault().getSystemColor(SWT.COLOR_BLACK);
private static final Color COLOR_WAITING = Display.getDefault().getSystemColor(SWT.COLOR_GRAY);
private static final Font FONT_DEFAULT = new Font(Display.getDefault(), new FontData("Arial", 24, SWT.BOLD));
private static final Font FONT_WAITING = new Font(Display.getDefault(), new FontData("Arial", 24, SWT.NORMAL));
private Display display;
private Shell shell;
private Label label;
private int countdownSeconds;
private boolean isCountingDown;
public CountDownLabel() {
display = new Display();
shell = new Shell(display);
shell.setText("CountDown Label");
shell.setLayout(new GridLayout());
label = new Label(shell, SWT.CENTER);
label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
label.setForeground(COLOR_DEFAULT);
label.setFont(FONT_DEFAULT);
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
if (isCountingDown) {
System.out.println("请等待");
} else {
startCountdown();
}
}
});
countdownSeconds = 0;
isCountingDown = false;
}
public void open() {
shell.setSize(300, 200);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
FONT_DEFAULT.dispose();
FONT_WAITING.dispose();
display.dispose();
}
private void startCountdown() {
countdownSeconds = COUNTDOWN_SECONDS;
isCountingDown = true;
label.setForeground(COLOR_WAITING);
label.setFont(FONT_WAITING);
updateLabel();
new Thread(() -> {
while (countdownSeconds > 0) {
countdownSeconds--;
display.asyncExec(this::updateLabel);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
display.asyncExec(this::resetLabel);
}).start();
}
private void updateLabel() {
label.setText(String.valueOf(countdownSeconds));
}
private void resetLabel() {
isCountingDown = false;
label.setForeground(COLOR_DEFAULT);
label.setFont(FONT_DEFAULT);
label.setText("Click to start countdown");
}
public static void main(String[] args) {
CountDownLabel countDownLabel = new CountDownLabel();
countDownLabel.open();
}
}
```
这个程序创建了一个窗口,其中包含一个Label控件。当用户点击Label时,如果倒计时正在进行,则控制面板输出“请等待”,否则开始倒计时。倒计时从10秒开始,每秒更新Label的文本,直到计时结束。在计时结束后,Label会回到初始状态,等待下一次点击开始新的倒计时。在计时过程中,Label的前景色变为灰色,字体变为普通,以表示当前不可用。
阅读全文