How can I stop a JFrame from closing when clicking the close button.

I need to display a dialog when a user attempts to close my app, giving them the option to close, minimize or cancel. How can I stop the form from closing after the user makes his selection? I have the folllowing code, but my form still closes after selecting an option:
private void formWindowClosing(java.awt.event.WindowEvent evt) {                                  
        //An array of Strings to be used a buttons in a JOptionDialog
        String[] options = {"Close", "Minimize", "Cancel"};
        //Determines what the user wants to do
        int result = JOptionPane.showOptionDialog(null, "What to you want to do?  Close the application, minimize or cancel?", "Please select an option...", 0, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
       //Determines what to do, depending on the user's choice
        if (result == 0) {
            //Close the application
            System.exit(0);
        } else if (result == 1) {
            //Minimize the application
            this.setState(Frame.ICONIFIED);
    }Any help would be much appreciated!

import java.awt.event.*;
import javax.swing.*;
public class test extends JFrame {
     public static void main( String[] args ) {
          new test();
     public test() {
          setSize( 200, 200 );
          //the next line makes the JFrame not close
          setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE );
          //now add a listener that does the trick
          addWindowListener( new WindowAdapter() {
                    public void windowClosing( WindowEvent e ) {
                         //ask the user and do whatever you wish
          setVisible( true );
}

Similar Messages

  • How can i stop my picture from flipping when I take it on the front camera?

    How can i stop my picture from flipping when I take it on the front camera? Need help as it's frustrating me:(

    Hmm...Double click on the Home button and try to delete the camera app then launch it again that should fix it. You can also turn off your phone and turn it back on again.

  • Every time I restart my mac air some applications like calendar and Microsoft word automatically starts, how can I stop such applications from starting when ever I restart my mac

    Every time I restart my mac air some applications like calendar and Microsoft word automatically starts, how can I stop such applications from starting when ever I restart my mac?

    One thing to check:  when shutting down or restarting, there is a checkbox in the shutdown/restart dialog which asks whether you want currently open applications to open at startup.
    charlie

  • How can I stop a JFrame from painting it's background on setVisible?

    When a JFrame is set visible it will paint its background before it paints whatever is in the contentPane. This gives an ugly gray flash before the content pane is painted. I can't use the solution of setting the JFrame's background color because the content pane is displaying an image, not a simple color. I need the image to be the first thing displayed when the frame is set visible. Seems related to doublebuffering some how, but I'm not sure what to do. The same problem presents itself with a JWindow IF it has a parent JFrame. Below is code that will demonstrate this problem.
    import java.awt.Color;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class Test extends JFrame{
    JPanel panel = new JPanel();
    public static void main(String[] args) {
    new Test().setVisible(true);
    private Test(){      
    getContentPane().add(panel);
    // setBackground(Color.white); // <-- uncomment this to remove flash.
    panel.setBackground(Color.white);
    setSize(640, 480);
    super.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    I can't use the solution of setting the JFrame's background color because the content pane is displaying an image, not a simple colorMy question to you is what difference does it make?. Like it or not, JFrame is either going to set the background with the LAF control color or the color you specified. Take a look at the source code and you will see that JFrame calls a protected frameinit method where it gets and sets the backgroud color. The only feasible solution is shown below:
    import java.awt.Color;
    import javax.swing.*;
    public class Test extends JFrame {
       JPanel panel = new JPanel();
       public static void main(String[] args) {
          UIManager.put("control",Color.white);  // added by V.V.
          new Test().setVisible(true);
       private Test() {
          getContentPane().add(panel);
          panel.setBackground(Color.white);
          setSize(640, 480);
          super.setDefaultCloseOperation(EXIT_ON_CLOSE);
    };o)
    V.V.

  • HT1338 how can I stop my icons from moving around on the Lions desktop?

    My icons change position after a start-up or re-boot.
    It all started after installing Lion.
    Has anyone a suggestion how tostop this?
    I am running a MBP quadcore i7 500gb ssl, 8gb mem, OSX 7.4

    Hi Lance ..
    Open the Finder.
    From the Finder menu bar top of your screen click View > Show View Options
    Click the pop up menu next to:  Sort by
    Select:  Snap to grid

  • How can I write a code that triggers when clicking on Save button

    I want to hide certain fields inside my tracking list, if the login user is not part of the “Managers” group.
    To do so I want to add the following Page-load code inside a web part :-
    using (SPSite site = new SPSite(SPContext.Current.Site.Url))
    using (SPWeb web = site.OpenWeb())
    {SPGroup group = site.Groups["Managers"];
    bool isUser = site.IsCurrentUserMemberOfGroup(group.ID);
    if (isUser)
    {textbox.Visible=false;}}
    And the following custom code that triggers when saving the form :-
    using (SPSite site = new SPSite(SPContext.Current.Site.Url))
    using (SPWeb web = site.OpenWeb())
    SPList list = web.Lists["ListName"];web.AllowUnsafeUpdates = true;
    SPListItem item = list.Items[SPContext.Current.ListItem.UniqueId];
    txtTitle.Text = item["Title"] as string;item.Update();web.AllowUnsafeUpdates = false;
    But I am not sure where exactly I should add the custom code for the save button ? I tried writing it inside the Oninit method , but I got many errors as shown below:-
    So can anyone advice how i should write the web part to include the Page load & the custom save button code?
    second question in general is my above approach considered valid , i mean to hide/show list columns using web parts ?

    Hi,
    According to your post, my understanding is that you want to hide/show list columns based on specify the permission for Users, SharePoint Groups or Active Directory Groups.
    Here is a solution from CodePlex for your reference:
    SharePoint 2013 Column & View Permission
    https://sp2013columnpermission.codeplex.com/
    Best Regards
    Dennis Guo
    TechNet Community Support

  • How can I stop a JFrame from taking the focus?

    Hi,
    Please see my original post in the Java Event Handling forum:
    http://forum.java.sun.com/thread.jsp?forum=424&thread=565034&tstart=0&trange=15
    Sorry, for cross-posting but its been nearly a week and I have had no replies. This forum looks a bit more active.
    - David

    try this...
    JFrame frame = new JFrame();
    frame.setFocusableWindowState(false);setFocusableWindowState
    public void setFocusableWindowState(boolean focusableWindowState)Sets whether this Window can become the focused Window if it meets the other requirements outlined in isFocusableWindow. If this Window's focusable Window state is set to false, then isFocusableWindow will return false. If this Window's focusable Window state is set to true, then isFocusableWindow may return true or false depending upon the other requirements which must be met in order for a Window to be focusable.
    Setting a Window's focusability state to false is the standard mechanism for an application to identify to the AWT a Window which will be used as a floating palette or toolbar, and thus should be a non-focusable Window.
    Parameters:
    focusableWindowState - whether this Window can be the focused Window

  • How can I stop Firefox 34 from crashing when I click a button on the NOrton 360 toolbar??

    I have the latest Norton 360 and fully updated. Also have FF 34.05. After anywhere between an hour and 3 hours, clicking any of the Norton Toolbars buttons that open options and provide multiple log in options FF crashes and when I reopen it it brings up my old tabs and at the end it brings up the FF welcome screen. In the options, it changes my opening page to the Norton Welcome page and the option to open previous tabs which was there with open default site which now it the welcome screen. Need help as have tried several fixes from the net and none so far work. Have allowed FF to reinstall the pref file, have removed hardware acceleration as well as put flash into a non protected mode and none help.
    Don't know if it is a FF or Norton issue but, it is a real issue. Please help.

    Thanks for your quick turn around. I'd be surprised if corrupt files as I only got the machine last Thursday but, it was a refurb so perhaps issues from the previous owner.
    Do have some questions as follows:
    It is a Windows 8.1 64 machine so will the fix recommended work??
    looking at the page, appears option 2 is my best bet but, won't start until I get the go for Win 8.2. Assuming this is a good fix and since I would be doing it with the system and not a program, no malware??
    As far as drivers, do have a app from HP that updates drivers and I updated everything after I got it going so should have the latest drivers and I did try alone unclicking the machine acceleration and no change there but, with the scan, might help. I have run all of the Windows updates which were quite a few with a new computer and do have Windows set to perform automatic updates so don't think I need to worry about graphic drivers??
    Your thoughts on my questions before running the scan at the elevated admin level. By the way, I am the admin so do I simply run as admin or is there a higher thing I need to do to run at High Administrator???
    Also, if after I run the scan and repair, if OK on Win 8.1 should I send your results to Norton for them to look at since almost all of the problems are with Norton and perhaps they have a fix with those issues and having running the driver fix should help them?? Also will the scan and repair indicate what was fixed and what wasn't.
    Sorry so many questions but, don't want to mess up my new machine.
    Thanks so much,
    Dave

  • How can i stop my mb from sleeping when i close the lid?

    Probably very obvious, sorry about that, but any help you be appreciated

    The MacBook is designed to be operated in "Clamshell" (Display closed) mode.
    To activate this function you must connect an external Keyboard,Mouse and Display.
    All "Sleepless" does is allow this functionality without connecting the peripherals.
    If operating in "Clamshell" mode overheats your MacBook,then you have a defective MacBook and you need to contact Apple for repair/replacement.
    Jim
    PowerBook G3 500 Mhz "Pismo"/ 2.0Ghz BlackBook 2GB OWC RAM   Mac OS X (10.4.7)  

  • How can I stop Finder windows from moving when I drag files into them?

    I have searched but can't seem to find an answer.
    Thank you.

    HI Dave,
    Go to ~/Library/Preferences and move the com.apple.finder.plist file to the Trash.
    ~ (Tilde) character represents your Home Folder.
    Restart your Mac.
    Hopefully that will help.
    Carolyn

  • How to get current row value from table when press the submit button

    Hi,
    I want to get the current row value of SuccessionPlanId which is one of the column in a advanced table.
    I created one button (created using personalization, action fired thru CO)in the table as column, so each row having one button, if i press the first row's button means then i want to fetch the first row's SuccessionPlanId and if it is 3rd means then i want to get the value of third row's value.
    How to do it in controller extension?
    Please reply soon, its urgent.
    Thanks in advance,
    SAN

    Pratap,
    Yes, I tried with 'delete' button which is seeded one.
    For this, our code using row reference is working too fine. it throws exact SuccessionPlanId value of corresponding row.
    I created MessageStyledText, but here i need to give text value right, then only it 'll appear in the page.
    Instead i created one image and fired explicitly from the controller processRequest method.
    But the same problem remains..
    here my code:
    public void processRequest(OAPageContext pageContext, OAWebBean webBean){
    super.processRequest(pageContext, webBean);
    OAButtonBean oabb = (OAButtonBean)webBean.findChildRecursive("XXSubmit");
    FireAction action = new FireAction("XXSubmit");
    oabb.setAttributeValue(UIConstants.PRIMARY_CLIENT_ACTION_ATTR, action);
    OAImageBean oaib=(OAImageBean)webBean.findChildRecursive("XXSubmitImage");
    oaib.setFireActionForSubmit("XXSubmitImage", null, null, true);
    public void processFormRequest(OAPageContext pageContext, OAWebBean webBean){
    if("XXSubmitImage".equals(pageContext.getParameter("event"))){
    String succIdI="";
    String rowRefI = pageContext.getParameter(OAWebBeanConstants.EVENT_SOURCE_ROW_REFERENCE);
    if(rowRefI != null && !("".equalsIgnoreCase(rowRefI ))){
    PerSuccPlanSearchVORowImpl rowI = (PerSuccPlanSearchVORowImpl)oaam.findRowByRef(rowRefI);
    if(rowI != null)
    succIdI=rowI.getAttribute("SuccessionPlanId").toString();
    }else{
    throw new OAException("Row is null");
    throw new OAException(succIdI, OAException.INFORMATION);
    }else{
    super.processFormRequest(pageContext, webBean);
    If i run the page using this controller, it throws exception without any value, because for 'succIdI' i initialized without any string.
    Can you please suggest me how to solve?

  • In Acrobat Reader DC for Android, how do I prevent Verizon Cloud from launching when clicking the floating action button to retrieve files?

    I have a Verizon-branded Samsung Galaxy S5, which means a lot of Verizon apps were added from the factory install.
    Recently I upgraded Adobe Acrobat Reader to its most recent version.
    When I clicked on the floating action button to open a PDF, it launched Verizon Cloud instead of showing my file directory.
    Unless I disabled Verizon Cloud altogether, every time I did this, I would get the Verizon Cloud app instead of a file listing.
    Reader DC is the only app that does such a thing. Is this a defect?

    Thanks for the information.
    To remove the Verizon cloud storage from Adobe Acrobat DC application, you can 'Turn off' the Verizon cloud application from 'Settings'-->'Application Manager'-->'All applications'. After doing this, every time you tap on the Floating Action button, you will be presented the list of all your pdf files on your device.
    If you would like to view both the Verizon cloud based files as well as files from your internal memory/SD card, I would request you to download some file manager application from the Google Play Store such as And Explorer, ES File Explorer etc. After doing this, whenever you will tap on the floating action button, you will be provided an option to open the files either from the Verizon cloud or the files on your device.
    Hope this helps. Please let us know if you observe any more issues.
    Thanks.

  • All my contact are being copied to my friend's iphone and i also am getting his contacts on my phone,when i delete a contact it also deletes it from his phone,we are sharing the same apple ID. How can i stop our contacts from being shared between us

    All my contact are being copied to my friend's iphone and i also am getting his contacts on my phone,when i delete a contact it also deletes it from his phone,we are sharing the same apple ID. How can i stop our contacts from being shared between us

    Everything that you have checked in your icloud settings will be shared between devices using the same Apple ID.  If you don't want icloud to share that information, then simply turn off that process under settings > icloud

  • How can I stop my iPhone from synching my contacts and groups lists twice?

    How can I stop my iPhone from synching my contacts and groups lists twice....I am using iCloud but am not sure how correct this duplication.

    Go into Settings>Mail, Contacts, Calendars. Is this happening at the bottom in the signature section, or in the header of the mail where your email address is? If it is the signature, then go to the Signature area of the Mail settings. If this is in the header, then go to the account in question and edit your account information to include your name instead of Johnny.

  • How can i stop my phone from vibrating in my ear when i am on the call?

    How can i stop my phone from vibrating in my ear when i am on the call? I usually keeps my phone on vibration mode so i get notified when there is a new mail or message? However, when i am on the call, then also, it vibrates in my ear everytime a mail comes. Very irritating. I use my business phone and mails keep coming every 2-5 mins.
    Please help.

    very impractical . specially when you call A LOT and receive notifications constantly!

Maybe you are looking for

  • How to extract the values from WPBP table

    Hi experts, We are in preparation of a custom report. In the report we want to have a  value from WPBP table. We want to extract the value of Capacity utilization level from WPBP table. Could you please let me know the way to extract the value. Pleas

  • I need to reinstall creative suite 5.5 standard and I cannot find the file in the Adobe site.

    I cannot find the file for Adobe creative suite standard on the Adobe site. Does anyone know how to download?

  • NIK SOFTWARE CRASHING PHOTOSHOP CC

    In the past couple of days, Photoshop CC just won't load if the NIk Software files are present in the plug in folder. I get a crash report and have sent that off, but is there a temp or perm fix for this that I've missed?

  • No costing for intermediate materials

    We are running costing for a configured material.  When we cost the material in the sales order, the finished product is getting costed with values but the semi- and raw-materials for this finished good is not picking any values in the costing result

  • Is OIM 9.1.0.1 certified for 10.1.0.7 database?

    Per documentation OIM 9.1.0.1 is certified for Oracle 11g Enterprise edition 11.1.0.6 and later patch sets. Does this include 10.1.0.7 or only 11.1.0.6 patch set x are certified. I would appreciate your feedback