4

I usually rely on setLocationRelativeTo(null) to position my dialogs centered on the screen, but recently I have been given a second monitor, and this method always sets my dialogs centeres on the primary monitor, even if the main window is on the second monitor.

I know it's a silly thing, but it annoys me enough to ask. Any solution apart from setting location relative to main screen? I haven't done that ever.

Roman Rdgz
  • 12,836
  • 41
  • 131
  • 207

1 Answers1

2

I know this question is old... but for other mad programmer like me:

Create own class, extend JDialog and use super(Frame, Modal).

This worked for me:

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

With the use of Singelton-Pattern for the main frame, you can call the dialog like this:

new GFileChooserDialog(Singelton.getInstance());

If you want to display the JDialog perfectly in the center of the screen, dont use setLocationRelativeTo. Instead override its paint method and set location:

@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
    );
}
asdf
  • 246
  • 3
  • 12