2

我有一个主应用程序框架 ( MainFrame class)。在 a 的 actionperformed 事件中JButton,a JPanel (MyJPanel class)通过将其放入来打开JDialog。我没有扩展JDialog到创建MyJPanel类,因为我可能也需要 MyJPanel 用于其他目的。

我的问题是我无法以编程方式关闭MyJPanel显示在JDialog. 有什么我想念的吗?你能弄清楚吗?

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;


    public class MainFrame extends JPanel {
        public MainFrame() {

            JButton btnOpenJdialog = new JButton("Open JDialog");
            add(btnOpenJdialog);
            btnOpenJdialog.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    JDialog jd = new JDialog();
                    MyJPanel mjp = new MyJPanel(true);//showing in JDialog
                    jd.setTitle("JDialog");
                    jd.add(mjp);
                    jd.pack();
                    jd.setVisible(true);

                }
            });
        }

        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {

                public void run() {
                    createAndShowGUI();
                }
            });
        }

        public static void createAndShowGUI() {

            JFrame frame = new JFrame("Test-JFrame");
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.getContentPane().add(new MainFrame());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }

    }

MyJPanel 类:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;
import javax.swing.JButton;

public class MyJPanel extends JPanel {
    private boolean isShownInJDialog = false;

    public MyJPanel() {
        JButton btnCloseMe = new JButton("Finish Action");
        add(btnCloseMe);
        btnCloseMe.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (isShownInJDialog) {
                    MyJPanel.this.setVisible(false);
                    //how to close the JDialog too.
                }
                else {
                    //just hide the content, 
                    MyJPanel.this.setVisible(false);
                }
            }
        });
    }

    public MyJPanel(boolean isShownInJDialog) {
        this();
        this.isShownInJDialog = isShownInJDialog;

    }

}

更新 我能够使用霍华德的回答来解决这个问题:

...     
if (isShownInJDialog) {
        Window w = SwingUtilities.getWindowAncestor(MyJPanel.this);
        w.setVisible(false);
}
...
4

1 回答 1

8

如果我正确理解了您的问题,您想关闭JDialog其中MyJPanel包含但没有参考的内容吗?

您可以使用的构造函数提供这样的参考,也可以将MyJPanel您的代码更改ActionListener

Window w = SwingUtilities.getWindowAncestor(MyJPanel.this);
w.setVisible(false);

它在没有直接参考的情况下查找面板的父窗口。

于 2012-06-07T17:01:30.207 回答