有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用多个监视器时的java设置对话框位置

我通常依靠setLocationRelativeTo(null)将对话框放在屏幕的中心位置,但最近我得到了第二个监视器,并且这种方法总是在主监视器上设置对话框中心,即使主窗口在第二个监视器上

我知道这是一件愚蠢的事情,但我很恼火地问。除了设置相对于主屏幕的位置外,还有其他解决方案吗?我从来没有这样做过


共 (1) 个答案

  1. # 1 楼答案

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

    创建自己的类,扩展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;
        }   
    }
    

    使用Singelton-Pattern作为主框架,可以如下方式调用对话框:

    new GFileChooserDialog(Singelton.getInstance());
    

    如果要在屏幕中央完美显示JDialog,请不要使用setLocationRelativeTo。而是替代其绘制方法并设置位置:

    @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
        );
    }