Why? - Problem with JDialog
Hello to everyone!! I have these 2 classes:
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ActionEvent;
import java.awt.Dimension;
publicclass TestTheDialogimplements ActionListener{
JFrame mainFrame =null;
JButton myButton =null;
public TestTheDialog(){
mainFrame =new JFrame("TestTheDialog Tester");
mainFrame.addWindowListener(new WindowAdapter(){
publicvoid windowClosing(WindowEvent e){
CustomDialog cust =new CustomDialog(mainFrame, true,"Do u wanna leave?");
mainFrame.setVisible(cust.getAnswer());}
});
myButton =new JButton("Test the dialog!");
myButton.addActionListener(this);
mainFrame.setLocationRelativeTo(null);
mainFrame.getContentPane().add(myButton);
mainFrame.pack();
mainFrame.setVisible(true);
}
publicvoid actionPerformed(ActionEvent e){
if(myButton == e.getSource()){
System.err.println("Opening dialog.");
CustomDialog myDialog =new CustomDialog(mainFrame, true,"Do u wanna leave?");
System.err.println("After opening dialog.");
if(myDialog.getAnswer()){
System.err.println("The answer is true.)");
}else{
System.err.println("The answer is false");
}
}
}
publicstaticvoid main(String argv[]){
TestTheDialog tester =new TestTheDialog();
}
}
This one:
import javax.swing.JDialog;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
publicclass CustomDialogextends JDialogimplements ActionListener{
private JPanel myPanel =null;
private JButton yesButton =null;
private JButton noButton =null;
privateboolean answer =false;
publicboolean getAnswer(){return answer;}
public CustomDialog(JFrame frame,boolean modal, String myMessage){
super(frame, modal);
myPanel =new JPanel();
getContentPane().add(myPanel);
myPanel.add(new JLabel(myMessage));
yesButton =new JButton("Yes");
yesButton.addActionListener(this);
myPanel.add(yesButton);
noButton =new JButton("No");
noButton.addActionListener(this);
myPanel.add(noButton);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
publicvoid actionPerformed(ActionEvent e){
if(yesButton == e.getSource()){
System.err.println("User chose yes.");
answer =true;
setVisible(false);
System.exit(0);
}
elseif(noButton == e.getSource()){
System.err.println("User chose no.");
answer =false;
setVisible(false);
}
}
}
The real problem is in this part:
mainFrame.addWindowListener(new WindowAdapter(){
publicvoid windowClosing(WindowEvent e){
CustomDialog cust =new CustomDialog(mainFrame, true,"Do u wanna leave?");
mainFrame.setVisible(cust.getAnswer());}
});
Why is it not working correctly?!I mean, if I click on "x" button, and I click on the "no " button, it's automatically close my frame too!

