關於WindowAdapter--windowClosing的疑惑程序設計的思路是在用戶點擊關閉按鈕的時候做一次JDialog確認,
如果提供的用戶名和密碼真確就退出。現在的問題是如果用戶點擊cancelButton退出JDialog時,主JFrame也關閉了。addWindowListener(new WindowAdapter() {            public void windowClosing(WindowEvent win)
            {
                if(Dialog==null){
                 Dialog =new ConfirmDialog(ReelUp.this);
                }
                Dialog.show();  
                               
                if(Dialog.getStatus()){
                 System.exit(0);
                }
            }        });
----------------
class ConfirmDialog extends JDialog{
public ConfirmDialog(JFrame Owner){
super(Owner,"confirmDialog",true);
Container contentPane =getContentPane();

JPanel Panel =new JPanel();
Panel.setLayout(new GridLayout(2,2));
Panel.add(new JLabel("User Name:"));
Panel.add(username =new JTextField(""));
Panel.add(new JLabel("Password:"));
Panel.add(password =new JPasswordField(""));
contentPane.add(Panel,BorderLayout.CENTER);

JButton okButton =new JButton("OK");
okButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent Event){
if((username.getText()).trim().equals("SYSTEM")&&(password.getText()).trim().equals("MANAGER")){
ok=true;
setVisible(false);
}
}
}
);

JButton cancelButton =new JButton("Cancel");
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent Event2){
   ConfirmDialog.this.setVisible(false);
}
});

JPanel buttonPanel =new JPanel();
buttonPanel.add(okButton);
buttonPanel.add(cancelButton);
contentPane.add(buttonPanel,BorderLayout.SOUTH);
setSize(200,100);
}
public boolean getStatus(){
return ok;
}

private boolean ok;
private JPasswordField password;
private JTextField username;

}試了一下好像使用了WindowAdapter後,即使是windowClosing不復蓋,也能關閉JFrame.----------
如果使用Button觸發JDialog能夠實現功能。
class plafFrame extends JFrame{
public plafFrame(){
JButton Button =new JButton("click");
Button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent win)
            {
                if(Dialog==null){
                 Dialog =new ConfirmDialog(plafFrame.this);
                
                }
                Dialog.show();
                if(Dialog.getStatus()){
                 System.exit(0);
                }
            }
});

JPanel Panel =new JPanel();
Panel.add(Button);
Container contentPane=getContentPane();
contentPane.add(Panel);
}
    private ConfirmDialog Dialog;
}

解决方案 »

  1.   

    在公司一小哥的幫助下已經解決需要為JFrame指定setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    來個人把貼結了
      

  2.   

    来晚一步,和我使用的方法一样http://community.csdn.net/Expert/topic/4672/4672789.xml?temp=.7412073
      

  3.   

    System.exit(0); 是根源
    只需要对dialog进行操作,可以使用dispose,也可以使用setvisible,但是setVisible会让dialog继续驻留在内存中。