当我关闭JFrame时,如何防止JDialog在JFrame前面弹出?

时间:2014-12-31 13:44:03

标签: java swing jframe jdialog

代码说明:

我有一个名为class的{​​{1}} GUI extends JFrameboolean中有一个closable变量class。我向WindowListener添加了JFrame,并向setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);添加了JFrame。这可以防止JFrame关闭。一切都按预期工作。

GUI prog=new GUI()来自另一个main的{​​{1}},并使用class显示JFrame。我还制作一个名为prog.setVisible(true);的{​​{1}}并将其显示在JDialog后面。关闭d后,JFrame也可以关闭。

问题:

我的代码有效。唯一的问题是,当我按下d标题栏中的 X (关闭按钮)而不关闭其背后的JFrame时,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); } }

class

问题:

当我关闭extends JFrame时,如何防止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前弹出?

1 个答案:

答案 0 :(得分:3)

通常在创建JDialog时,您将JFrame指定为所有者。这样,当您单击任务栏上的框架图标时,可以使用JFrame显示所有子对话框,否则除非您最小化桌面上的所有其他活动窗口,否则无法激活对话框。

如果您真的想要一个独立的JDialog,那么您需要将对话框指定为另一个框架的子对象:

//JDialog d=new JDialog(); //The problematic JDialog
JDialog d=new JDialog(new JFrame()); //The problematic JDialog