下面的解决方案适用于 SWT,也许它也可以为 AWT 解决问题......
由于它在当前 shell 的左上角显示对话框,一个快速而简单的解决方案是创建一个新的、定位良好且不可见的 shell 并从中打开 FileDialog。我使用以下代码得到了可接受的结果:
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
public class CenteredFileDialog extends Dialog {
protected Shell shell;
public FileDialog dialog;
private int width = 560; // WinXP default
private int height = 420;
public CenteredFileDialog(Shell parent, int style) {
super(parent, style);
shell = new Shell(getParent(), SWT.APPLICATION_MODAL);
dialog = new FileDialog(shell, style);
}
public Object open() {
shell.setSize(width, height);
Rectangle parentBounds = getParent().getBounds();
shell.setLocation(
parentBounds.x + (parentBounds.width - width) / 2,
parentBounds.y + (parentBounds.height - height) / 2);
Object result = dialog.open();
shell.dispose();
return result;
}
}
该类可以这样使用:
CenteredFileDialog saveDialog = new CenteredFileDialog(getShell(), SWT.SAVE);
saveDialog.dialog.setFilterExtensions(new String[] { "*.txt" });
saveDialog.dialog.setFilterNames(new String[] { "Text (*.txt)" });
...
String f = (String)saveDialog.open();
if ( f != null ) {
name = f;
recentPath = saveDialog.dialog.getFilterPath();
}
该类仅部分解决了 Windows 平台的问题(在 MacOS 上,对话框无论如何都是以屏幕为中心的;在 Linux 上我没有测试) - 第一次对话框相对于父 shell 出现居中(这是我们需要的),并且“记住”它在屏幕上的绝对位置。通过后续调用,即使主应用程序窗口移动,它也会始终在同一个位置弹出。
尽管有些奇怪,但从我的角度来看,新的行为肯定比默认的不专业的对话框左上角停靠要好。