在使用多个显示器时设置对话框位置

4

通常我使用 setLocationRelativeTo(null) 在屏幕中心显示我的对话框,但最近我买了第二个显示器,这种方法总是把我的对话框放在主监视器的中心位置,即使主窗口在第二个监视器上。

我知道这是一件小事,但它让我很烦恼,有没有其他解决方案?我从来没试过相对于主屏幕设置位置。


您可以查看此处引用的 API 示例 链接 - trashgod
1个回答

2

我知道这个问题很老了...但对于像我一样的疯狂程序员:

创建自己的类,扩展JDialog并使用super(Frame,Modal)。

这对我起作用了:

import java.io.File;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

public class GFileChooserDialog extends JDialog {

    private JFileChooser fileChooser;   
    private File file;

    public GFileChooserDialog(JFrame relativeTo) {
        super(relativeTo, true); 
        this.setAlwaysOnTop(true);
        this.fileChooser = new JFileChooser();
        this.getContentPane().setSize(450, 300);
        int returnVal = fileChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = fileChooser.getSelectedFile();            
        } 
    }

    public File getFile() {
        return file;
    }
    public void setFile(File file) {
        this.file = file;
    }   
}

通过使用 单例模式 用于主框架,您可以像这样调用对话框:

new GFileChooserDialog(Singelton.getInstance());

如果您想完美地在屏幕中央显示JDialog,请勿使用setLocationRelativeTo。相反,覆盖其paint方法并设置位置:
@Override
public void paint(Graphics g) {
    super.paint(g);
    Rectangle screen = this.getGraphicsConfiguration().getBounds();
    this.setLocation(
        screen.x + (screen.width - this.getWidth()) / 2,
        screen.y + (screen.height - this.getHeight()) / 2
    );
}

1
我知道这个问题很旧了,但在 Stack Overflow 上回答旧问题也是可以的 ;) - dorukayhan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接