繁体   English   中英

关闭 JFileChooser 和 JDialog 后禁用 JFrame

[英]JFrame is disabled after closing JFileChooser and JDialog

我真的需要你的帮助,因为我正在为此苦苦挣扎。 我已经创建了一个 JFrame,我可以在其中打开一个 JDialog,例如更改设置。 在 JDialog 中有一个用于启动 JFileChooser 的按钮。 我可以选择一个文件,一切正常。 但是如果我只是关闭 JFileChooser 和 JDialog,JFrame 将禁用并最小化。

有谁知道如何解决这个问题?

构建 JFrame:

frame = new JFrame("My first JFrame");

frame.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent e) {
        closeWindow();
    }
});

frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "Cancel");
frame.getRootPane().getActionMap().put("Cancel", new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
        closeWindow();
    }
});

frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

[...]

frame.getContentPane().setLayout(null);

frame.setVisible(true);

构建 JDialog:

final EditColumnsDialog editColumnsDialog = new EditColumnsDialog(frame, ...);
editColumnsDialog.editPicPath();

...

class EditColumnsDialog extends JDialog {

EditColumnsDialog(final JFrame owner, ...) throws Exception {
    super(owner, owner.getTitle());
    [...]
}

...

protected void editPicPath() {
    [...]

    JButton searchButton = new JButton("Search");
    searchButton.setVisible(true);
    searchButton.addActionListener(e -> {
        File folder = WindowBuilder.fileChooser(JFileChooser.DIRECTORIES_ONLY, picPath.getText());
        if (folder != null) {
            picPath.setText(folder.getAbsolutePath());
        }
    });

    [...]

    pack();
    setVisible(true);
    setModal(true);
}
}

构建 JFileChooser:


static File fileChooser(final int fileSelectionMode, final String dir) {

    JFileChooser jFileChooser = new JFileChooser();
    jFileChooser.setFileSelectionMode(fileSelectionMode);
    jFileChooser.setCurrentDirectory(new File(dir));
    Action details = jFileChooser.getActionMap().get("viewTypeDetails");
    details.actionPerformed(null);
    if (jFileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
        return jFileChooser.getSelectedFile();
    } else {
        return null;
    }
}

找到了解决办法:

在 EditColumnsDialog (JDialog) 中设置 "setModal(true)" BEFORE (!!!) "setVisible(true)"

这将确保在 JFrame 中打开的新窗口 (JDialog) 阻塞旧窗口,然后 JFileChooser 窗口阻塞 JDialog 并且在关闭它后另一个将获得焦点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM