user1050755 user1050755 - 1 year ago 121
Java Question

JOptionPane.showMessageDialog(null, ...) always showing dialog on primary screen

Is there any solution to that? Any alternative library I might use to display the dialog on the mouse pointer's screen (can't use parent for that)? Or is there any api to change the dialog's screen?

I even tried using a non-visible parent JFrame on the desired screen, but it only has any effect on the dialog's screen positioning if it is visible when invoking the dialog. My "special case" is that I have no app window or JFrame around to which I want to stick the dialog. It should always appear in the center of the screen which the user is currently using.

Answer Source

Instead of using a JOptionPane I recommend instead you use a JDialog.

Here is an example:

JOptionPane jOptionPane = new JOptionPane("Really do this?", JOptionPane.PLAIN_MESSAGE, JOptionPane.YES_NO_OPTION);
JDialog jDialog = jOptionPane.createDialog("dialog title");

To then display this on a particular screen you can get the bounds of the screen you want and then place your dialog in the center of it, for example:

Rectangle screenBounds = MouseInfo.getPointerInfo().getDevice().getDefaultConfiguration().getBounds();

int x = (int) screenBounds.getCenterX() - (jDialog.getWidth() / 2);
int y = (int) screenBounds.getCenterY() - (jDialog.getHeight() / 2);

jDialog.setLocation(x, y);

Check results:

Object selectedValue = jOptionPane.getValue();
int dialogResult = JOptionPane.CLOSED_OPTION;
if (selectedValue != null) {
    dialogResult = Integer.parseInt(selectedValue.toString());

switch (dialogResult) {
    case JOptionPane.YES_OPTION:"yes pressed");
    case JOptionPane.NO_OPTION:"no pressed");
    case JOptionPane.CLOSED_OPTION:"closed");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download