我有一个主应用程序框架(MainFrame class
)。在JButton
的动作执行事件上,JPanel (MyJPanel class)
通过放置在JDialog
中打开。我不扩展JDialog
来创建MyJPanel
类,因为我也可能需要其他用途的MyJPanel。以编程方式关闭在JDialog中显示的JPanel
我的问题是我不能以编程方式关闭显示在JDialog
中的MyJPanel
。有什么我失踪?你能把它弄清楚吗?
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;
}
}
UPDATE 我能解决这个利用霍华德的答案:
...
if (isShownInJDialog) {
Window w = SwingUtilities.getWindowAncestor(MyJPanel.this);
w.setVisible(false);
}
...
'关闭面板'DYM'关闭对话框'?面板本身既可以显示也可以隐藏,也可以换成CardLayout。 –
[请阅读此主题,尤其是评论由@missingfaktor](http://stackoverflow.com/questions/10933968/design-or-class-component-hierarchy-to-be-followed-for-the-wizard-application ) – mKorbel
@AndrewThompson,我修改了我的代码,实际上会有'Boolean'来决定'MyJPanel'当前是否显示在'JDialog'中(或者任何延伸'Window'的东西)或者在另一个'Container'中。我能够在霍华德的回答帮助下解决这个问题。 – gtiwari333