gpt4 book ai didi

java - 如何使 java.awt.FileDialog 在屏幕上居中

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:18:14 25 4
gpt4 key购买 nike

我一直没弄清楚这个问题;通常的嫌疑人不起作用。

给定:

FileDialog                  dlg=null;

dlg=new FileDialog(owner,"Select File to Load",FileDialog.LOAD);
dlg.setFile(null);
dlg.setVisible(true);

有什么方法可以让对话框居中吗?

一个关键点是在 setVisible() 处,调用线程被阻塞,直到对话框被关闭;在此之前的任何定位似乎都被忽略了。

最佳答案

下面的解决方案适用于 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 居中(这是我们需要的) , 并“记住”它在屏幕上的绝对位置。通过后续调用,它总是在同一个地方弹出,即使主应用程序窗口移动了也是如此。

尽管很奇怪,但从我的角度来看,新行为肯定比默认的看起来不专业的对话框左上角停靠要好。

关于java - 如何使 java.awt.FileDialog 在屏幕上居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2467180/

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