gpt4 book ai didi

java - 以编程方式关闭显示在 JDialog 中的 JPanel

转载 作者:行者123 更新时间:2023-11-29 06:41:46 25 4
gpt4 key购买 nike

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

我的问题是我无法以编程方式关闭显示在 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;

}

}

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

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

最佳答案

如果我对你的问题的理解正确,你想关闭你的 MyJPanel 所在的 JDialog 但没有对它的引用?

您可以使用 MyJPanel 的构造函数提供这样的引用,或者将 ActionListener 中的代码更改为

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

在没有直接引用的情况下查找面板的父窗口。

关于java - 以编程方式关闭显示在 JDialog 中的 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10936306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com