[英]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.