gpt4 book ai didi

java - 如何用SWT制作一个可自动关闭的定时对话框

转载 作者:行者123 更新时间:2023-11-30 02:11:11 25 4
gpt4 key购买 nike

如何制作以下一种带有自动倒计时的对话框:

enter image description here

目标是让框在 10 秒内需要执行操作(是或否),否则它将恢复为默认的“否”选项。我什至不知道从哪里开始为此编写计时器代码,或者如何使对话框自动倒计时

这是我到目前为止所拥有的:

    File g = new File(pa+"\\data.ini");
if(g.exists()) {
Shell shell = new Shell(display, SWT.SHELL_TRIM & (~SWT.RESIZE) & (~SWT.MAX));
MessageDialog dialog = new MessageDialog(shell, "Detected Recovery File", null,
"Old Schedule has been found. Recover?", MessageDialog.INFORMATION, new String[] {
"Yes", "No" }, 0);

while(true) {
if(dialog.open()==0) {
restart=true;
break;
}
break;
}
}

最佳答案

您可以扩展Dialog,然后添加倒计时逻辑。

这是一个带有倒计时器的简单示例。在美观方面,还有很多可以改进的地方,但它满足了您的要求:

public static void main(String[] args)
{
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
shell.setText("StackOverflow");

Button open = new Button(shell, SWT.PUSH);
open.setText("Open dialog");
open.addListener(SWT.Selection, e -> new CountdownDialog(shell).open());

shell.pack();
shell.open();

while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}

private static class CountdownDialog extends Dialog
{
private static final int COUNTDOWN = 10;

protected CountdownDialog(Shell parentShell)
{
super(parentShell);
}

@Override
protected Control createDialogArea(Composite parent)
{
Composite container = (Composite) super.createDialogArea(parent);
container.setLayout(new GridLayout());

Label label = new Label(container, SWT.NONE);
label.setText("Old Schedule has been found. Recover?");
label.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));

Label countdown = new Label(container, SWT.NONE);
countdown.setText(Integer.toString(COUNTDOWN));
countdown.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));

new Thread(() -> {
for (int i = COUNTDOWN - 1; i >= 0; i--)
{
try
{
Thread.sleep(1000);
}
catch (final InterruptedException e)
{
return;
}

if (parent.isDisposed()) // Stop thread when shell is closed
break;

final boolean close = i == 0;
final String newText = Integer.toString(i);
Display.getDefault().asyncExec(() -> {
if(!countdown.isDisposed())
countdown.setText(newText);

if (close)
CountdownDialog.this.buttonPressed(IDialogConstants.CANCEL_ID);
});
}
}).start();

return container;
}

@Override
protected void configureShell(Shell newShell)
{
super.configureShell(newShell);
newShell.setText("Detected Recovery File");
}

@Override
protected void createButtonsForButtonBar(Composite parent)
{
createButton(parent, IDialogConstants.OK_ID, "Yes", true);
createButton(parent, IDialogConstants.CANCEL_ID, "No", false);
}
}

关于java - 如何用SWT制作一个可自动关闭的定时对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50053759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com