簡體   English   中英

從JFileChooser打開按鈕關閉上一個窗口

[英]Closing previous window from JFileChooser Open button

我正在創建一個文件打開向導,並從初始窗口的瀏覽按鈕打開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);
                }

            }
        });
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM