我试图在java swt应用程序中创建一个shell作为对话框Shell。有两个按钮'接受'并且'拒绝'。我希望如果用户在30秒内没有点击任何按钮,那么shell将自动处理。为此,我正在尝试遵循代码,但它不起作用。请帮助我使用任何想法或建议
public class ServiceRequestDialog extends Dialog {
public ServiceRequestDialog(Shell parent,String nameofrequestor) {
// Pass the default styles here
this(parent,SWT.NO_TRIM|SWT.ON_TOP|SWT.DIALOG_TRIM|SWT.APPLICATION_MODAL);
this.parent=parent;
nameofRequester=nameofrequestor;
}
public ServiceRequestDialog(Shell parent, int style) {
// Let users override the default styles
super(parent, style);
}
public Shell open() {
shell = new Shell(getParent(), getStyle());
shell.setText(getText());
shell.setLocation(parent.getLocation().x+190, parent.getLocation().y+215);
shell.setSize(279, 181);
shell.setLayout(new FormLayout());
......
shell.open();
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
// Return the entered value, or null
try {
System.out.println("Thread Sleep");
Thread.sleep(15000);
dispose();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return shell;
}
public void dispose(){
try {
if (shell != null) {
if (shell.isDisposed()==false) {
shell.dispose();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
答案 0 :(得分:3)
我自己实施了一些应该给你一个起点的东西。当您按下Dialog
时,它基本上会打开JFace Button
。此Dialog
将在指定的秒数(示例中为5)后自行关闭:
public static void main(String[] args)
{
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
shell.setText("StackOverflow");
Button button = new Button(shell, SWT.PUSH);
button.setText("Open dialog");
button.addListener(SWT.Selection, new Listener()
{
@Override
public void handleEvent(Event arg0)
{
new MyDialog(shell, 5).open();
}
});
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
private static class MyDialog extends Dialog
{
private int counter = 0;
private int maxSeconds;
public MyDialog(Shell parentShell, int maxSeconds)
{
super(parentShell);
this.maxSeconds = maxSeconds;
setShellStyle(SWT.APPLICATION_MODAL | SWT.CLOSE);
setBlockOnOpen(true);
}
@Override
protected Control createDialogArea(Composite parent)
{
Composite composite = (Composite) super.createDialogArea(parent);
composite.setLayout(new GridLayout(1, false));
final Display display = composite.getShell().getDisplay();
final Label label = new Label(composite, SWT.NONE);
label.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));
/* Set up the timer here */
final Runnable timer = new Runnable()
{
public void run()
{
if(!label.isDisposed())
{
label.setText("" + counter++);
label.pack();
if(counter <= maxSeconds)
display.timerExec(1000, this);
else
MyDialog.this.close();
}
}
};
/* And start it */
display.timerExec(0, timer);
return composite;
}
@Override
protected void configureShell(Shell newShell)
{
super.configureShell(newShell);
newShell.setText("Dialog");
}
}