java - 从 JFileChooser 打开按钮关闭上一个窗口

标签 java swing jbutton jfilechooser

我正在制作一个文件打开向导,并且 JFileChooser 是从初始窗口上的浏览按钮打开的。我目前已将其设置为浏览按钮处理第一个窗口并同时打开 JFileChooser 窗口。我宁愿在用户选择文件后处理该窗口,以防他们想要取消并返回到初始窗口 - 目前这是不可能的。

相关代码如下:

class BrowseButton extends JButton {

    public BrowseButton(String name, final JPanel pane) {

        super(name);
        addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                JFileChooser fileopen = new JFileChooser();             
                FileFilter filter = new FileNameExtensionFilter("dwg files", "dwg");
                fileopen.addChoosableFileFilter(filter);

                int ret = fileopen.showDialog(pane, "Open");

                if (ret == JFileChooser.APPROVE_OPTION) {
                    File file = fileopen.getSelectedFile();
                    String[] layers = getFileLayers(file.getPath());
                    openLayerWindow(layers);
                }

            }
        });
        addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                dispose();
            }
        });
    }

当按钮被实例化时......

//Bottom Panel
    final JPanel bottom = new JPanel(new FlowLayout(FlowLayout.RIGHT));

    BrowseButton browse = new BrowseButton("Browse...", bottom);
    browse.setMnemonic(KeyEvent.VK_B);
    CloseButton close = new CloseButton("Close");
    close.setMnemonic(KeyEvent.VK_C);

    bottom.add(close);
    bottom.add(browse);
    basic.add(bottom);

最佳答案

您可以利用 SwingUtilities.getWindowAncestor 检索 BrowseButton 的包含窗口,并仅在用户选择 APPROVE_OPTION 时才将其处置.

class BrowseButton extends JButton {

    public BrowseButton(String name, final JPanel pane) {

        super(name);
        addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                JFileChooser fileopen = new JFileChooser();             
                FileFilter filter = new FileNameExtensionFilter("dwg files", "dwg");
                fileopen.addChoosableFileFilter(filter);

                int ret = fileopen.showDialog(pane, "Open");

                if (ret == JFileChooser.APPROVE_OPTION) {
                    SwingUtilities.getWindowAncestor(BrowsButton.this).dispose();
                    File file = fileopen.getSelectedFile();
                    String[] layers = getFileLayers(file.getPath());
                    openLayerWindow(layers);
                }

            }
        });
    }

关于java - 从 JFileChooser 打开按钮关闭上一个窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17531702/

相关文章:

java - 使用 GridBagLayout 用按钮填充框架

Java 在网格布局中获取错误数量的 jbutton

java - 如何从 JButton 外部调用 JTable Action ?

java - 如何在java中更好地编写开关代码(精确数字的平滑移动)

JavaFX 事件过滤器实现

java - 在主类之外使用 Java 的 2d 图形

java - 为什么我的 keyListener 在全屏时停止工作?

java - 在 OSX 10.5 上运行/编译 jdbc-sqlite

java - 同步代码块 - 练习 13-2

java - 有没有 NO MOTION 鼠标监听器?