My Swing application has to show a modal dialog to the user. Sorry for not posting SSCCE.
topContainer might be JFrame or JApplet.
private class NewGameDialog extends JDialog {
public NewGameDialog () {
super(SwingUtilities.windowForComponent(topContainer), "NEW GAME", ModalityType.APPLICATION_MODAL);
//add components here
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
//TODO:
setSize(new Dimension(250, 200));
setLocation(650, 300);
}
}
I start the dialog like this on network event
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
NewGameDialog dialog = new NewGameDialog();
dialog.setVisible(true);
}
});
The problem is to set optimal location for my dialog.
1) If it is set as absolute value, and I move the app frame to the second screen, then dialog is shown on the first screen which is weird.
2) If it is set a relative value to JFrame, it might appear that user moved the app frame outside of the screen and the dialog being relatively located would not be visible to the user. And because it is modal, the game would be stuck.
What is the best solution considering two above mentioned issues?
This reminded me of a very favourite post of mine, using Window.setLocationByPlatform(true), on StackOverflow.
How to best position Swing GUIs
EDIT 1 :
You can add a
FocusListenerto yourJDialogand onfocusGained(...)method, you can usesetLocationRelativeTo(null)for both theJFrameand theJDialog, so that they both come to the center of the screen no matter where they are before.EDIT 2 :
I searched a bit here and there, and it turns out, in my opinion, that actually on which
Monitor Screenyour application comes at the first instance, will determine it’s GraphicsConfiguration. Though as I roamed through the API, there is only a getter method for the saidGraphicsConfigurationthingy and no setter methods for the same (Still You can specify one through the constructor of any top level Window i.e. JFrame(…)/JDialog(…)).Now you can occupy your head with this code, which can be used to determine the appropriate location, that you want to set, again, you might have to use
focusGain()method in my opinion, to satisfy condition 2 of your question. Have a look at the code attached, though no need to create anew JFrame/JDialog, just watch how to get coordinates for the screen (that you can add in thefocusGain()method to determine the location of the whole Application.)EDIT 3 :
Try to change this :
to just :
To test the above thingy, I used my
FrameFocusClass as is, though I had added your changes to myCustomDialogmethod, as shown in this modifiedCustomDialogClass.