user1050755 user1050755 - 4 months ago 17
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

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);
jDialog.setVisible(true);

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:
        LOG.info("yes pressed");
        break;
    case JOptionPane.NO_OPTION:
        LOG.info("no pressed");
        break;
    case JOptionPane.CLOSED_OPTION:
        LOG.info("closed");
        break;
    default:
}
Comments