JFrame 在关闭 JOptionPane 后失去焦点并且无法将其重新设置

JFrame loses focus after closing a JOptionPane and can't set it back

我有一个 JOptionPane 显示带有 JTextField 的输入对话框。关闭此对话框时,它 returns 插入了文本。

但是当按下任何按钮 (Confirm/Cancel) 并关闭对话框时,主 window 失去焦点,我无法再次设置它。

String menuName = (String) JOptionPane.showInputDialog (
    new JFrame(), 
    "Insert new Menu Name"
);

当此对话框关闭时,如何将焦点设置在主要 window 上?

您应该将父组件作为第一个参数传递,而不是您创建的一些随机新框架。

假设您从 JFrame 方法中启动它,您可以 运行

String menuName = (String) JOptionPane.showInputDialog (
    this, // parent component is the JFrame you are launching this from
    "Insert new Menu Name"
);

在某些情况下,例如,当从 FocusListeneronLostFocus 实现中 运行 执行此操作时,您需要在处理完所有当前事件后 运行 此操作。这可以通过在事件队列的末尾发布一个事件来完成。使用 SwingUtilities.invokeLater 来做到这一点。

因此,如果您遇到这种情况,请按如下方式启动对话框。假设您 运行 从中 class 的帧称为 MyFrame:

SwingUtilities.invokeLater(new Runnable(){
    @Override
    public void run() {
        String menuName = (String) JOptionPane.showInputDialog (
            MyFrame.this, // parent component is the JFrame you are launching this from
            "Insert new Menu Name"
        );
        // do stuff with menuName
    }
});