如下程序,在窗口添加了个按钮,点击按钮弹出打开文件对话框。但在运行时,第一次点击打开文件对话框在窗口上方,以后再点击对话框出现在窗口下方,十分不解,请高手指点。谢谢!
import java.awt.FileDialog;
import java.awt.Frame;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class dialogtest {
public static void main(String[] args) {
Shell shell;
Display display=Display.getDefault();
shell = new Shell(display,SWT.CLOSE | SWT.MIN);
shell.setSize(860, 622);
shell.setLayout(new FormLayout());
Composite composite = new Composite(shell, SWT.NONE);
FormData fd_composite = new FormData();
fd_composite.top = new FormAttachment(0, 1);
fd_composite.bottom = new FormAttachment(0, 439);
fd_composite.right = new FormAttachment(0, 128);
fd_composite.left = new FormAttachment(0, 1);
composite.setLayoutData(fd_composite);
composite.setLayout(new FillLayout(SWT.VERTICAL));
Button AnalyseAlarmFromOSS_BT = new Button(composite, SWT.NONE);
AnalyseAlarmFromOSS_BT.setText("打开文件");
AnalyseAlarmFromOSS_BT.addSelectionListener(new SelectionAdapter(){
public void widgetSelected(SelectionEvent e){
Frame f = new Frame("对话框");
FileDialog d2 = new FileDialog(f, "打开文件" , FileDialog.LOAD);
d2.setVisible(true);
String ossalarm_file_path=d2.getDirectory() + d2.getFile();
System.out.println(ossalarm_file_path);
}
});
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}
------解决方案--------------------
swt中混杂了swing,FileDialog应该是这个org.eclipse.swt.widgets.FileDialog
Frame f = new Frame("对话框");//这行不要
FileDialog d2 = new FileDialog(f, "打开文件" , FileDialog.LOAD);//swt的dialog参数构造和swing有些区别,稍微改改,f再改成getShell()
d2.setVisible(true);//swt中显示dialog是用d2.open()