Solved

exit popup

Posted on 2004-08-10
21
462 Views
Last Modified: 2012-05-05
Hi experts..
I need some sample code on how to have a small popup or dialog box (I'm not sure if it makes any difference) when the main program frame is closed or exit(menu item) are selected..

Something like:
---------------------- l
Exit without save?   l
ok        cancel        l
---------------------- l
thanks
0
Comment
Question by:Samooramad
  • 9
  • 6
  • 5
  • +1
21 Comments
 
LVL 15

Accepted Solution

by:
Javatm earned 250 total points
ID: 11767882
What do you need a JOptionPane ?


import javax.swing.*;

public class Show {
public static void main(String args[]) {

Object[] options = { "OK", "CANCEL" };
JOptionPane.showOptionDialog(null, "Click OK to continue", "Warning",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
}
}
0
 
LVL 15

Expert Comment

by:Javatm
ID: 11767908
If I transfer that on your question it will be like :


import javax.swing.*;

public class Show {
public static void main(String args[]) {

 Object[] options = { "OK", "CANCEL" };

            JOptionPane.showOptionDialog(null, "Exit without save? ", "Exit . . .",
            JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
      }
}

Hope that helps . . .
Javatm
0
 
LVL 15

Expert Comment

by:Javatm
ID: 11767922
Or you can do it like :

import javax.swing.*;

public class Show {
public static void main(String args[]) {

      JOptionPane.showConfirmDialog(null,"Are you sure you want to exit ?", "Exit . . .",
      JOptionPane.OK_CANCEL_OPTION);

      }
}
0
 

Author Comment

by:Samooramad
ID: 11772174
how do I make it work when closing the frame?
0
 

Author Comment

by:Samooramad
ID: 11772211
if you don't mind could you explain what that does.. I havent used JoptionPane before
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11772367
You can capture the button which was clicked by the value returned by JOptionPane.showOptionDialog () or showConfirmDialog (), and then decide what to do.
0
 

Author Comment

by:Samooramad
ID: 11776013
how do I do that..(sorry for all the questions but I haven't done this before)
0
 
LVL 37

Assisted Solution

by:zzynx
zzynx earned 250 total points
ID: 11778079
Hi Samooramad, I think this little app does what you want:

/*
 * ExitDemo.java
 *
 */

import javax.swing.*;
/**
 *
 * @author  zzynx
 */
public class ExitDemo extends javax.swing.JFrame {
   
    public ExitDemo() {
        initComponents();
        setSize(500,500);
        setLocationRelativeTo(null);  // to center on the screen
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);       // Important!!!!
    }
   
    private void initComponents() {
        theButton = new javax.swing.JButton();

        getContentPane().setLayout(new java.awt.FlowLayout());

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });

        theButton.setText("Exit");
        theButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                theButtonActionPerformed(evt);
            }
        });

        getContentPane().add(theButton);

        pack();
    }

    private void theButtonActionPerformed(java.awt.event.ActionEvent evt) {
        if (sureToExit())
            System.exit(0);        
    }
   
    private boolean sureToExit() {
        Object[] options = { "OK", "CANCEL" };
       
        int choice = JOptionPane.showOptionDialog(null, "Exit without save? ", "Exit . . .",
                                                  JOptionPane.DEFAULT_OPTION,
                                                  JOptionPane.QUESTION_MESSAGE,
                                                  null, options, options[0]);
        return choice==0;
    }
   
    private void exitForm(java.awt.event.WindowEvent evt) {
        if (sureToExit())
            System.exit(0);
    }
   
    public static void main(String args[]) {
        new ExitDemo().show();
    }
   
    private javax.swing.JButton theButton;
}

Some explanation/

1) It's important to have this:

        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

    otherwise no matter what the answer is on the question the frame would disappear.

2) We want the same behaviour if the exit button is pressed or if the window is closed (via the x on the right top)

    For the first we need an actiolistener on the button:

        theButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                theButtonActionPerformed(evt);
            }
        });

    For the second we need a windowlistener on the window

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });

3) since in both cases we want the same, the code for both the functions theButtonActionPerformed() and exitForm() is:

        if (sureToExit())
            System.exit(0);

4) sureToExit is the function responsible for asking the user. It returns true if the user confirmed, false otherwise.

5) Explanation of JOptionPane: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JOptionPane.html
0
 
LVL 37

Assisted Solution

by:zzynx
zzynx earned 250 total points
ID: 11778115
Remark: I used <OK> and <Cancel> like you asked for.
But since you ask a question ("Exit without save?") it would be better/more clear to use <Yes> & <No> buttons.

In that case just replace

          Object[] options = { "OK", "CANCEL" };
by
          Object[] options = { "Yes", "No" };
0
 
LVL 37

Assisted Solution

by:zzynx
zzynx earned 250 total points
ID: 11778150
Remark:
the integer returned by JOptionPane.showOptionDialog() indicates which option is chosen.
It's the index in the options array. (So 0 if OK/Yes is chosen, 1 if Cancel/No is chosen)
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 

Author Comment

by:Samooramad
ID: 11778414
Thats great! ok let me work on it about a day (takes me forever to do anything)
and will get back
thanks
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11778439
>> ok let me work on it about a day and will get back
OK
0
 
LVL 15

Expert Comment

by:Javatm
ID: 11779320
I'm back and we are in a different timezone so I'm sorry I'm late but I think your
2nd question was already answered by zzynx.

> if you don't mind could you explain what that does.. I havent used JoptionPane before
It displays what you want. You just have to put it in your main method and handle the exit part.
0
 

Author Comment

by:Samooramad
ID: 11788113
ok..Ill work on it and get back to you...
thanks Javatm
0
 

Author Comment

by:Samooramad
ID: 11788317
ok it worked great but I have a question (for either of you). could someone please explain the parameters in the following line:

JOptionPane.showOptionDialog(null, "Click OK to continue", "Warning",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
0
 
LVL 15

Expert Comment

by:Javatm
ID: 11789957
> JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE
An option that you use for JOptionPane.

> options, options[0]
Is the object's that you are calling to be added in JOptionPane.

So you made a custome JOptionPane through using :

JOptionPane.showOptionDialog(null, "Click OK to continue", "Warning",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);

Hope that helps . . .
Javatm
0
 

Author Comment

by:Samooramad
ID: 11799087
yes it did.
Sorry you were right about the time zone messing things up
thank you both!
0
 

Author Comment

by:Samooramad
ID: 11799099
zzynx, your answers were VERY VERY helpful but I accepted Javatm answer since it came first :)
thanks guys!
0
 
LVL 15

Expert Comment

by:Javatm
ID: 11802880
=-) Always glad to help . . .

http://freewebs.com/cube-j
Friend : Javatm
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11917583
>> zzynx, your answers were VERY VERY helpful
Glad to hear that :°)
>> but I accepted Javatm answer since it came first :)
No problem.

PS. sorry for not answering your extra question about the parameters. I was offline for 14 days.
But I'm back ;°)
0
 

Author Comment

by:Samooramad
ID: 11982229
glad to have you back!
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now