Search code examples
javaswingjoptionpane

Making the cancel-operation go back to start of program?


I have this gui where the user is prompted to choose between a person or a firm, but I want the cancel-button to go back to the start of the program, or the main frame.

int chooseVehicleType = JOptionPane.showOptionDialog(this,
                "What kind of vehicle is it?", "Choose and option",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                vehicle, "");

if (chooseVehicleType == 1) {
        int result2 = JOptionPane.showConfirmDialog(null, truck,
                "Enter the truck details", JOptionPane.OK_CANCEL_OPTION);
        // Printing out the input of the user in the center panel
        if (result2 == JOptionPane.OK_OPTION) {
                             //Do stuff here, proceed to he next prompt window
            }
        if (result2 == JOptionPane.CANCEL_OPTION) {
            updateCenterPanel("Operation cancelled!");
                           /* Updating the center panel, 
                            * but also close the operation   
                            * and go back to the main screen 
                            */
        }

So, I came this far. But now the user is prompted to the next choosing screen instead of going back to the main frame.

Any ideas? I've run out of them... Thanks in advance!


Solution

  • Since have not posted an SSCCE there are many scenarios to take into consideration.

    According to the comments in your code you have a center panel that might have opened the JOptionPane and the main screen might be in the background. If pressing the cancel button you want to close the center panel and gain focus on the main screen frame. You can add the following code to the cancel option:

       if (result2 == JOptionPane.CANCEL_OPTION) {
            updateCenterPanel("Operation cancelled!");
                          centerPanel.dispose(); // closes the window and releases it's occupied resources
                          mainScreen.setVisible(true); //gain focus on the main window
        }
    

    If you just want to gain focus on the main screen frame without closing any other windows add only this to your cancel option of the JOptionPane:

        mainScreen.setVisible(true);
    

    I hope this helped. Cheers!