How do I center a JDialog on screen?

How do I go about positioning a JDialog at the center of the screen?

Asked by: Max213 | Posted: 23-01-2022

Answer 1

In Java 1.4+ you can do:

final JDialog d = new JDialog();

Or perhaps (pre 1.4):

final JDialog d = new JDialog();
d.setSize(200, 200);
final Toolkit toolkit = Toolkit.getDefaultToolkit();
final Dimension screenSize = toolkit.getScreenSize();
final int x = (screenSize.width - d.getWidth()) / 2;
final int y = (screenSize.height - d.getHeight()) / 2;
d.setLocation(x, y);

Answered by: Edgar642 | Posted: 24-02-2022

Answer 2

Use this line after the pack() method:

setLocation((Toolkit.getDefaultToolkit().getScreenSize().width)/2 - getWidth()/2, (Toolkit.getDefaultToolkit().getScreenSize().height)/2 - getHeight()/2);

Answered by: Daryl361 | Posted: 24-02-2022

Answer 3

Two helpers for centering within the screen or within the parent.

// Center on screen ( absolute true/false (exact center or 25% upper left) )
public void centerOnScreen(final Component c, final boolean absolute) {
    final int width = c.getWidth();
    final int height = c.getHeight();
    final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (screenSize.width / 2) - (width / 2);
    int y = (screenSize.height / 2) - (height / 2);
    if (!absolute) {
        x /= 2;
        y /= 2;
    c.setLocation(x, y);

// Center on parent ( absolute true/false (exact center or 25% upper left) )
public void centerOnParent(final Window child, final boolean absolute) {
    boolean useChildsOwner = child.getOwner() != null ? ((child.getOwner() instanceof JFrame) || (child.getOwner() instanceof JDialog)) : false;
    final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    final Dimension parentSize = useChildsOwner ? child.getOwner().getSize() : screenSize ;
    final Point parentLocationOnScreen = useChildsOwner ? child.getOwner().getLocationOnScreen() : new Point(0,0) ;
    final Dimension childSize = child.getSize();
    childSize.width = Math.min(childSize.width, screenSize.width);
    childSize.height = Math.min(childSize.height, screenSize.height);
    int x;
    int y;
    if ((child.getOwner() != null) && child.getOwner().isShowing()) {
        x = (parentSize.width - childSize.width) / 2;
        y = (parentSize.height - childSize.height) / 2;
        x += parentLocationOnScreen.x;
        y += parentLocationOnScreen.y;
    } else {
        x = (screenSize.width - childSize.width) / 2;
        y = (screenSize.height - childSize.height) / 2;
    if (!absolute) {
        x /= 2;
        y /= 2;
    child.setLocation(x, y);

Answered by: Sawyer522 | Posted: 24-02-2022

Answer 4

here's my solution to retrieve screen dimension with multiple monitors.

import java.awt.*;
import javax.swing.JFrame;

 * Méthodes statiques pour récupérer les informations d'un écran.
 * @author Jean-Claude Stritt
 * @version 1.0 / 24.2.2009
public class ScreenInfo {

   * Permet de récupérer le numéro de l'écran par rapport à la fenêtre affichée.
   * @return le numéro 1, 2, ... (ID) de l'écran
  public static int getScreenID( JFrame jf ) {
    int scrID = 1;
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice[] gd = ge.getScreenDevices();
    for (int i = 0; i < gd.length; i++) {
      GraphicsConfiguration gc = gd[i].getDefaultConfiguration();
      Rectangle r = gc.getBounds();
      if (r.contains(jf.getLocation())) {
        scrID = i+1;
    return scrID;

   * Permet de récupérer la dimension (largeur, hauteur) en px d'un écran spécifié.
   * @param scrID --> le n° d'écran
   * @return la dimension (largeur, hauteur) en pixels de l'écran spécifié
  public static Dimension getScreenDimension( int scrID ) {
    Dimension d = new Dimension(0, 0);
    if (scrID > 0) {
      GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
      DisplayMode mode = ge.getScreenDevices()[scrID - 1].getDisplayMode();
      d.setSize(mode.getWidth(), mode.getHeight());
    return d;

   * Permet de récupérer la largeur en pixels d'un écran spécifié.
   * @param scrID --> le n° d'écran
   * @return la largeur en px de l'écran spécifié
  public static int getScreenWidth( int scrID ) {
    Dimension d = getScreenDimension(scrID);
    return d.width;

   * Permet de récupérer la hauteur en pixels d'un écran spécifié.
   * @param scrID --> le n° d'écran
   * @return la hauteur en px de l'écran spécifié
  public static int getScreenHeight( int scrID ) {
    Dimension d = getScreenDimension(scrID);
    return d.height;


Answered by: Wilson218 | Posted: 24-02-2022

Answer 5

AFAIK you can pass a GraphicEnvironment to each JDialog/JFrame/JWindow constructor. This object describes the monitor to use.

Answered by: Arthur593 | Posted: 24-02-2022

Similar questions

java - Can't center jdialog in jframe

I can't center my jdialog in my jframe. I've tried to do this but it doesn't work: public void open(){ this.setVisible(true); this.setLocationRelativeTo(Main.instance.frame); } Tell me if you need any more code! Thanks for your help! Main: public class Main { public static Main instance; public JXFrame frame; public JXPanel panel; ...

java - Center JDialog over parent

I have a Java swing application with a button that produces a popup window when a certain action is performed. I'd like to align the center point of the popup window with the center point of the parent window when it is rendered. How can I calculate the x,y coordinates to plug into setLocation() for the popup window? Just to clarify. I do not want the behavior of setLocationRelativeTo() ...

java - Making a JDialog button respond to the Enter key

I have a JQueryDialog with a text field, an OK button and a cancel button. I want to be able to hit the enter key after filling in the text fields and have it do the same action as when I click the OK button.

java - Custom Cursor in a Swing JDialog

I have a Java Swing application, developed on Mac OS X 10.5 using Java 1.5. I'm trying to make a custom cursor appear when the user moves the mouse over some text in a dialog. The cursor never changes, though. When I don't use a JFrame instead of a JDialog, the cursor does change. But then I'll have to write all the dialog code myself. How can I get the cursor to appear? Here's the simplest...

java - Is there a way to change the owner of a JDialog?

I have a very specific problem, and I wanted to know if there is a way to change the owner of a JDialog (it can be set using the constructor). I suppose there is no "official" possibility (other than a hack), but I wanted to make sure I didn't miss something. Any ideas or hints on the topic would be helpful, thanks already...

java - JDialog cancel button

How can I set a cancel button in a Swing JDialog, i.e. a button whose action is performed automatically if the user presses the “Cancel” key on the keyboard? The counterpart is offered for a default action via the setDefaultButton method of the dialog's root pane. If that's helping, I'm searching for an analogue to the WinForms Form.CancelButton property.

java - How to close a modal JDialog when user clicks outside of JDialog?

I have a Undecorated Modal JDialog which I want to setVisible(false) when the user clicks outside of the modal dialog. Is this possible in Swing? What I am doing is popping up a custom editor for a text field like a date selector. Is there an easier way to do what I want? EDIT Remember that modal blocks on the call to setVisible(true), so you can't just say "don't use a mod...

java - how to ensure that JDialog always stays on top

I have a JDialog that takes a name from the user. Behind the JDialog, is an applet. I dont want the user to access that applet until he has entered the name. I tried JDialog.setAlwaysOnTop(true), but the applet throws an AccessException error. So what I did was keep a while loop that will execute JDialog.setVisible(true) till the JtextField(input...

java - How to bring JDialog to the top

This question already has answers here:

java - Hide JDialog window when the window lost focus

Hi I have only one JDialog box in my Java application.I want to make it invisible if it lost the focus. I've tried different method, But didn't able to trigger any of the window focus events. Here is my code: public void windowGainedFocus(WindowEvent e) { System.out.println("gained focus"); } public void windowLostFocus(WindowEvent e) { System.out.println("lost focus"); }

linux - java jdialog taskbar button

i'm traying a jdialog on linux, but it still appears in my taskbar. this is the code? what's wrong? import javax.swing.JDialog; public class Main { public static void main(String [] args) { new mydialog(); } private static class mydialog extends JDialog { public mydialog() { super(); setSize(200,200); setLocationByPlatform(true); ...

java - my custom JDialog appears, but is blank

At a point in my program, it opens a JDialog that displays information about what is going on as the program runs. It has several labels and a progress bar, but when the dialog window opens, it doesn't display anything. Here's the custom dialog and its constructor: public class DataMiner implements ActionListener { private Hashtable&lt;Integer, GISNode&gt; nodeTable; private Hashtable&lt;In...

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)