How can I implement a comfirmation window when closing the javafx applications?

Hi, guys
I would add a confirmation window when the user closes my javafx application, if the user clicks Yes, I close the application, so no, I wouldn't close it, how can I implement this feature?
 
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>(){

               @Override
               public void handle(WindowEvent arg0) {
                    try
                    {
                         //todo
                    }
                    catch(Exception ex)
                    {
                         System.out.print(ex.getMessage()+"\r\n");
                    }

               }
        });

Hello. Here is an example:

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.paint.Color;
import javafx.scene.layout.*;
import javafx.scene.control.*;

public class ModalDialog {

    public ModalDialog(final Stage stg) {
     final Stage stage = new Stage();
        //Initialize the Stage with type of modal
        stage.initModality(Modality.APPLICATION_MODAL);
        //Set the owner of the Stage
        stage.initOwner(stg);
        Group group =  new Group();
        HBox hb = new HBox();
         hb.setSpacing(20);
        hb.setAlignment(Pos.CENTER);
        Label label = new Label("You are about to close \n your application: ");
        Button no  = new Button("No");

        no.setOnAction(new EventHandler() {

            public void handle(ActionEvent event) {
                   stage.hide();
            }
        });
        Button yes  = new Button("Yes");
        yes.setOnAction(new EventHandler() {

            public void handle(ActionEvent event) {
                   stg.close();
            }
        });

         hb.getChildren().addAll(yes, no);
         VBox vb =  new VBox();
         vb.setSpacing(20);
         vb.setAlignment(Pos.CENTER);
         vb.getChildren().addAll(label,hb);
        stage.setTitle("Closing ...");
        stage.setScene(new Scene( vb, 260, 110, Color.LIGHTCYAN));
        stage.show();

    }

}

Test:

   import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.*;

/**
 *
 * @author Shakir
 */
public class ModalTest extends Application {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Application.launch(ModalTest.class, args);
    }

    @Override
    public void start(final Stage primaryStage) {
        primaryStage.setTitle("Hello World");
        Group root = new Group();
        Scene scene = new Scene(root, 300, 250, Color.LIGHTGREEN);

       primaryStage.setOnCloseRequest(new EventHandler(){

               @Override
               public void handle(WindowEvent arg0) {
                                arg0.consume();
                    try
                    {
                     ModalDialog md = new ModalDialog(primaryStage);
                                }
                    catch(Exception ex)
                    {
                         System.out.print(ex.getMessage()+"\r\n");
                    }

               }
        });

        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

Tags: Java

Similar Questions

  • How to close a pop-up window without closing the entire application?

    Greetings!

    I just want to ask for help with this case. Here, I have a screenshot of what I'm trying to accomplish:

    screenshot.jpg

    I used this code, but it turns out that it closes the whole application:

    import flash.system.fscommand;
    btn_exit.addEventListener (MouseEvent.CLICK, goExit);
    function goExit(evt:MouseEvent) {}
    fscommand ("QUIT");
    }

    should what code I use to accomplish my goal? Thanks in advance!

    Sincerely,

    Milo

    1. don't you implement event handing in CongratsMC?

    2. Yes, there is a conflict because congratulations to instance inside function is a quite different case: it is not seen outside the dropObject() method - therefore it can not be removed in the listener. So, you must do the following (read the comments in the case of top):

    function dropObject(e:MouseEvent):void {
         stage.removeEventListener(MouseEvent.MOUSE_UP, dropObject);
         stopDrag();
         var droppedOn:MovieClip;
         correctCounter.text = String(correct);
         if (currentlyDragged.dropTarget) {
              // loop through targets belonging to the currently dragged clip
              for each(var mc:MovieClip in currentlyDragged.dropTargets) {
                   if (currentlyDragged.hitTestObject(mc)) {
                        // get the target
                        droppedOn = mc;
                        currentlyDragged.removeEventListener(MouseEvent.MOUSE_DOWN, pickObject);
                        currentlyDragged.buttonMode = false;
                        currentlyDragged.x = droppedOn.x;
                        currentlyDragged.y = droppedOn.y;
                        correct++;
                        correctCounter.text = String(correct);
                        // stop loop - it is not necessary to continue
                        break;
                   }
              }
         }
         attempt++;
         attemptCounter.text = String(attempt);
         // return to the initial position if there is no hit
         if (!droppedOn) {
            currentlyDragged.x = startX;
            currentlyDragged.y = startY;
         }
         // DO NOT DECLARE THIS VARIABLE AGAIN - YOU ALREADY HAVE THE INSTANCE
         //var congrats:CongratsMC;
         if (correct == objects.length) {
              // DO NOT INSTANTIATE IT
              //congrats = new CongratsMC();
              // place i in the middle of the screen
              congrats.x = (stage.stageWidth - congrats.width) * .5;
              congrats.y = (stage.stageHeight - congrats.height) * .5;
              addChild(congrats);
         }
    }
    
  • Z560-I want to install windows xp. How can I go back to windows 7 in the future?

    Hello

    My friend just bought lenovo Z560 laptop of the United States and to use it in India.

    The laptop has pre installed windows 7.

    Now I want to format my laptop and install a new copy of windows XP. I have a few general questions on the same.

    (1) in the future, if I want to change my OS to Windows 7, how can I do / I have not received any installation or the windows installation CD 7 with my computer laptop lenovo.

    (2) is there a cancelled if guarantee I fomat my lapto and change OS?

    Any official help will be appreciated.

    Thank you

    -You can burn recovery discs on your own, reading instructions for a key recovery or take a look at this thread.

    -It is not void your warranty

    You must change the ide/sata settings in the bios to install xp, either said passing.

    You can download the drivers for xp from here

  • Why Firefox will allow me to have several tabs, but not allow me to switch between tabs and can only watch a new tab when closing the previous?

    Everytime I open a new tab, it appears on the tab bar where it should, but if I click on it nothing happens, the tab does not open, and I can't switch between multiple tabs. The only way to get a new tab is to close one on that I am currently, and even then it will only open the next tab in the order of precedence, so I can't even choose which tab is next to see. This problem makes it impossible to use firefox as a research tool that requires quick change back and forth between pages in multiple tabs at the same time.

    Try Firefox Safe mode to see if the problem goes away. Firefox Safe mode is a troubleshooting mode that disables certain parameters, disables most Add-ons (extensions and themes).

    If Firefox is open, you can restart Firefox Safe mode in the Help menu:

    • In Firefox 29,0 and above, click on the menu button

      click Help

      then select restart with disabled modules.

    • In previous versions of Firefox, click on the Firefox button in the upper left of the Firefox window and click help (or click on help in the Menu bar, if you do not have a Firefox button) and click on restart with disabled modules.

    If Firefox is not running, you can start Firefox in Mode safe mode as follows:

    • On Windows: Hold down the SHIFT key when you open the desktop Firefox or shortcut in the start menu.
    • On Mac: Hold the option key during the startup of Firefox.
    • On Linux: Exit Firefox, go to your Terminal and run firefox-safe-mode
      (you may need to specify the installation path of Firefox for example/usr/lib/firefox)

    When the Firefox Safe Mode window appears, select "start mode safe."

    If the issue is not present in Firefox Safe Mode, your problem is probably caused by an extension, and you need to understand that one. Please follow the section Troubleshooting extensions, themes and problems of hardware acceleration to resolve common Firefox problems to find the cause.

    To exit safe mode of Firefox, simply close Firefox and wait a few seconds before you open Firefox for normal use again.

    When find you what is causing your problems, please let us know. This might help others with the same problem.

  • How can I delete my emails in bulk in the Mail application?

    Original title: deleting email

    I have yahoo mail and I'm on windows 8 How can I delete my emails in bulk

    Hi Lynn,
     

    Thanks for posting the query on Microsoft Community and we give the opportunity to help you on this question.
     

    According to the description of the problem, it seems you want to delete the emails in bulk from the e-mail account.
     

    I would like to ask a few questions on this topic to help you best:

     
    (1) do you use Windows 8 Mail app on the computer?
    (2) did synchronize you with Windows 8 Mail app Yahoo mail account?
     
    If you use Mail app to view emails on the computer and that you have configured the account Yahoo mail with the Mail application, then, you can delete messages by selecting the mail by using the Remove option.
     
    I rather suggest that you follow the instructions below to find it's much easier:

     
    (a) click on one of them, the messages you want to delete.
    (b) press and hold the Ctrl on the keyboard, and then click all messages you want to delete.
    (c) the list of messages must be all shady. Click the delete option in the upper right corner of the Mail application.
    (d) check if you have deleted messages required at the same time.
     
    It will be useful.
     

    Please feel free to post if you have any other question related to Windows.
  • How can I stop pop-up window when new messages to the?

    Pop-up when new messages to the must be turned off. What should I do to stop it.

    "Tools" > "Options" > "General".
    or
    'Icon menu' > 'Options' > 'Options' > 'General '.

    Uncheck "show an alert".
    Deselect or select any other option.
    Click OK

  • How can you convert disks on Windows 7 drives the external without losing data or the system perform?

    How do you write the command for the conversion of FAT32 disk to ntfs without losing data to an external drive in Windows 7 and how you can convert the local drive too?

    How do you write the command for the conversion of FAT32 disk to ntfs without losing data to an external drive in Windows 7 and how you can convert the local drive too?

    Convert a drive to NTFS does not fit.
    http://Windows.Microsoft.com/en-us/Windows-Vista/convert-a-hard-disk-or-partition-to-NTFS-format
    (Vista/Windows 7 - it doesn't matter in this case).
     
    However, pay attention to this:
    "Although the risk of corruption or loss of data during a conversion are minimal, you must back up all data on the partition before you begin."
     
    Because something can and probably will happen.

  • How can I take bcd a windows xp with the ports com correctly?

    I want bcd a windows xp sp2, after he and load bcdwindows its com ports it is unclear what should I do to config correctly?

    Hello

    Install Service Pack 3 and let us know if you still face the question.

     
    Windows XP Service Pack 3 network installation Package for IT professionals and developers

    http://www.Microsoft.com/en-US/Download/details.aspx?&ID=24

    Install the Windows XP Service Pack 3 - file to Image CD ISO-9660.

    http://www.Microsoft.com/en-US/Download/details.aspx?&ID=25129

  • How can I reinstall or repair Windows Vista without the original disc?

    How do reinstal or repair Vista after changing the new hard drive, where no original software CD has been given at the time of the purchase of the computer because the computer has been pre-loaded with Vista

    original title: reinstal or repair vista without CD

    There is no Vista free download legal available.

    Contact your computer manufacturer and ask them to send a recovery disk/s Vista set.

    Normally, they do this for a cost of $ small.

    See you soon.

    Mick Murphy - Microsoft partner

  • How can I get an email from hp for the eprint application

    Idk

    Hello

    Please, use this link and select the device that you want to print from. The page will then be English allow you through the steps for you to print from your mobile device.

  • How can I stop photos to reproduce when downloading in windows live gallery

    How can I stop photos to reproduce when downloading in windows live gallery

    Hi KathyAdubato,

    Try this link for Live Help:

    www.windowslivehelp.com

    Hope this helps,

    Eddie B.

  • How can I get a browser window in firefox

    I just downloaded firefox on my Galaxy note and have no idea how to use it. I expect to open the firefox application and see a browser window, if I can just put a search quickly. I have no research, just the start page or menu bar which is a shortcut to a search bar, but not a browser screen.
    I do not expect to be the same as it is to say, but when I open IE starts in a browser window ready to search.

    Sorted! It's the add on full screen.

  • How can I close only 1 session, without closing all sessions, when you run several at the same time?

    I run normally 2 sessions of Firefox. Currently I have 3 sessions running. How can I close only 1 session without closing all? When I choose "File" and then "Exit", all sessions nearby.

    Firefox does not work more 'sessions', you see several windows running in the same process. IE runs each window in its ' own process and Chrome runs each tab in its' own process, but Firefox running in a single process.

    Do not use file > outputis to completely close Firefox, do not close the window you are looking at when you use this command. There was formerly a command to close this window on the file menu, but who took a few versions ago. You will need to use the X in the upper right of the window to close this window and leave the other open windows. Or you can use {Ctrl + Maj + W} close the window that is to the point (where you look).

  • How can I stop Photos to start when I plug my iPod nano?

    How can I stop Photos to start when I plug my iPod nano?  I use mac os x El Capitan 10.11.3 & iTunes 12.3.2.35.

    It takes your iPod nano 5th generation.  If so, this happens because he has a camera.  After Photos opens when you connect iPod, near the top of the window, is there a checkbox to Open the Photos for this device (or words to that effect)?  If you see this checkbox, uncheck.  Photos should be open when the iPod is connected.

  • How can I start/re-start Windows professional XP in safe MODE

    How can I start/re-start Windows professional XP in safe MODE? Aid filw I get only instructed on XP Home Edition and the buttons and it tells you to follow the guests do not appear in the professional edition. I need the instructions for Pro.  Can someone help me with this?

    Original title: Safe Mode

    You can start either home or Pro in SafeMode by this technique...

    Keep F8 hitting twice a second immediately after you have switched on the PC. You should get a boot menu where safe mode is selectable using the up/down arrow keys.

    Or, use the msconfig utility. When you do it this way, Windows starts in SafeMode permanently until you reverse the changes in msconfig...

    • Click Start
    • Click on run
    • Type msconfig and press enter
    • Click on the CHEST. INI tab
    • Check the box for/SafeBoot
    • Click OK
    • Restart the PC when prompted

    Tricky

Maybe you are looking for

  • My question has been archived. Answers are not helpful. I want to send a screenshot to ask... How do I get it to you?

    I want to have thumbnails options when I open a new tab, but I want my homepage regularly when I opened. For some reason, my home page was unsuccessful; Instead, I get this annoying Smart Search Web, I will never use, because I always use the address

  • Qosmio F750 - need drivers for Windows 8

    I have a Qosmio F750 = PQF75A and I installed upgrading to win 8 supplied with the laptop. My laptop is working except for the 3D and Blu - Ray players. I contacted Toshiba Australia and told me that there are no drivers available for the players. If

  • How to perform the two steps in parallel?

    I have always used the sequential execution, but now a situation that two steps must be performed in parallel (one step sends data to a device and another step cut the power to the unit with a delay). How it can be implemented in TestStand?

  • TestStandPersistedOptions

    Hello What is TestStandPersistedOptions? Thank you Rafi

  • How to create the type of waveform data

    Hello I work with the oscilloscope TDS 30xx series and I want to create the data type of waveform in the waveform of Fetch VI. I have problems with that. Can someone help me? I don't know how to data table of waveform to the creation of a data type.