我有一个名为class
的{{1}} GUI
extends JFrame
,boolean
中有一个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
前弹出?
答案 0 :(得分:3)
通常在创建JDialog时,您将JFrame指定为所有者。这样,当您单击任务栏上的框架图标时,可以使用JFrame显示所有子对话框,否则除非您最小化桌面上的所有其他活动窗口,否则无法激活对话框。
如果您真的想要一个独立的JDialog,那么您需要将对话框指定为另一个框架的子对象:
//JDialog d=new JDialog(); //The problematic JDialog
JDialog d=new JDialog(new JFrame()); //The problematic JDialog