[英]How to prevent JDialog from popping up in front of the JFrame when I close the JFrame?
我有一个名为GUI
的class
,它extends JFrame
并在class
有一个closable
的boolean
变量。 我在JFrame
添加了WindowListener
,并且还设置了setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
到JFrame
。 这样可以防止JFrame
关闭。 一切正常。
我从另一个class
main
中进行GUI prog=new GUI()
并使用prog.setVisible(true);
显示JFrame
prog.setVisible(true);
。 我还制作了一个名为d
的JDialog
并将其显示在JFrame
后面。 当d
关闭时, JFrame
也可以关闭。
我的代码有效。 唯一的问题是,当我按在标题栏中的X(关闭按钮) JFrame
,无需关闭JDialog
背后,则JDialog
在前面弹出JFrame
,当第一JOptionPane()
执行。
主班:
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JRadioButton;
import javax.swing.JOptionPane;
import javax.swing.JDialog;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent; //All these are used in my full program
public class ThirdProgram {
public static void main(String[] args)
{
final GUI prog=new GUI("My ThirdProgram in Java"); //Creating the JFrame
prog.setBounds(350,325,610,175);
prog.setResizable(false);
JDialog d=new JDialog(); //The problematic JDialog
d.setBounds(400,400,500,70);
d.add(new JLabel("I'm trying hard to stop you from closing the JFrame in front of you"));
d.setTitle("Unidentified JDialog");
d.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
d.setLayout(new FlowLayout(FlowLayout.CENTER));
d.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
prog.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //JFrame is now closable
prog.closable=false;
}
});
d.setVisible(true);
prog.setVisible(true);
}
}
extends JFrame
的class
:
class GUI extends JFrame implements ActionListener {
//some code here
boolean closable=true;
public GUI(String header)
{
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
if(closable) /*The problem occurs when the below JOptionPane() executes*/
JOptionPane.showMessageDialog(null,"You can't close this that easily! So try this program!","No way!",JOptionPane.ERROR_MESSAGE);
else
JOptionPane.showMessageDialog(null,"Eh...Where has the Guy preventing you from closing this gone?!?","Security Bypassed!",JOptionPane.ERROR_MESSAGE);
}});
/*Lots of code after this*/
关闭它时,如何防止JDialog
在JFrame
前面弹出?
通常,在创建JDialog时,将JFrame指定为所有者。 这样,当您单击任务栏上的框架图标时,所有子对话框都可以与JFrame一起显示,否则除非您最小化桌面上的所有其他活动窗口,否则无法激活该对话框。
如果您确实想要一个独立的JDialog,则需要将对话框指定为另一个框架的子对话框:
//JDialog d=new JDialog(); //The problematic JDialog
JDialog d=new JDialog(new JFrame()); //The problematic JDialog
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.