Center JDialog over parent

前端 未结 5 660
借酒劲吻你
借酒劲吻你 2020-11-30 09:39

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

相关标签:
5条回答
  • 2020-11-30 10:05

    Window#setLocationRelativeTo

    0 讨论(0)
  • 2020-11-30 10:10

    You could try passing the coordinates of the parent window and its size to the new window and adding the coordinates + 1/2 parent frame size in each axis - 1/2 of the popups x/y to center upon center.

    Or..If you extend you could use setLocationRelativeTo(owner)

    Hope this helps

    0 讨论(0)
  • 2020-11-30 10:16

    On the JDialog you've created you should call pack() first, then setLocationRelativeTo(parentFrame), and then setVisible(true). With that order the JDialog should appear centered on the parent frame.

    If you don't call pack() first, then setting the location relative to the parent doesn't work properly because the JDialog doesn't know what size it is at that point. It appears to take the size as 0 by 0, which results in the "top left pixel of the popup over the center pixel of the parent" positioning mentioned in a comment to one of the other answers.

    0 讨论(0)
  • 2020-11-30 10:16

    You can utilize event e to get parent window. Use getWindowAncestor and e.getSource().

    dialog.setLocationRelativeTo(SwingUtilities.getWindowAncestor((Component) e.getSource()))

    0 讨论(0)
  • 2020-11-30 10:20

    setLocationRelativeTo ..this sets the top left pixel of the popup over the center pixel of the parent. ..

    No it does not!

    Centered Dialog

    Each of the 3 dialogs popped by this simple example appears to be centered as far as I can see. I can only guess that the code is calling setLocationRelativeTo at the wrong time.

    import javax.swing.*;
    
    class CenterTheDialog {
    
        CenterTheDialog() {
            for (int ii=1; ii<4; ii++) {
                JFrame f = new JFrame("Frame " + ii);
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    
                f.setSize(400,300);
                f.setLocationByPlatform(true);
                f.setVisible(true);
    
                JDialog d = new JDialog(f);
                d.setSize(300,200);
                d.setLocationRelativeTo(f);
                d.setVisible(true);
            }
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> {
                new CenterTheDialog();
            });
        }
    }
    
    0 讨论(0)
提交回复
热议问题