JOptionPane.showMessageDialog(null, ...) 始终在主屏幕上显示对话框

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

有什么解决办法吗?我可能会使用任何替代库在鼠标指针的屏幕上显示对话框(不能使用 parent )?或者是否有任何 api 可以更改对话框的屏幕?

我什至尝试在所需屏幕上使用不可见的父 JFrame,但如果在调用对话框时它是可见的,它只会对对话框的屏幕定位产生任何影响。我的 "special case" 是我没有应用程序 window 或 JFrame 我想在其周围粘贴对话框。它应该始终出现在用户当前使用的屏幕中央。

我建议您不要使用 JOptionPane,而是使用 JDialog

这是一个例子:

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

然后要在特定屏幕上显示它,您可以获取所需屏幕的边界,然后将对话框放在它的中央,例如:

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);

检查结果:

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:
}