How to best position Swing GUIs?

前端 未结 2 657
面向向阳花
面向向阳花 2020-11-21 06:07

In another thread I stated that I liked to center my GUIs by doing something like this:

JFrame frame = new JFrame(\"Foo\");
frame.setDefaultCloseOperation(JF         


        
2条回答
  •  遥遥无期
    2020-11-21 06:33

    I totally agree that setLocationByPlatform(true) is the nicest way to specify a new JFrame's position but on a dual-monitor setup you can get into issues. In my case, the child JFrame is spawned on 'the other' monitor. Example: I have my main GUI on Screen 2, I start a new JFrame with setLocationByPlatform(true) and it opens on Screen 1. So here is a more complete solution, I think:

    ...
    // Let the OS try to handle the positioning!
    f.setLocationByPlatform(true);
    if (!f.getBounds().intersects(MyApp.getMainFrame().getBounds())) {
        // non-cascading, but centered on the Main GUI
        f.setLocationRelativeTo(MyApp.getMainFrame()); 
    }
    f.setVisible(true);
    

提交回复
热议问题