关闭JFileChooser和JDialog后禁用JFrame

问题描述 投票:0回答:1

我真的需要您的帮助,因为我正在努力。我创建了一个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);

Building 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;
    }
}

java swing jframe jfilechooser jdialog
1个回答
0
投票

找到解决方案:

在EditColumnsDialog(JDialog)中设置“ setModal(true)”之前(!!!)“ setVisible(true)”

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

© www.soinside.com 2019 - 2024. All rights reserved.