Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JOptionPane.createDialog and OK_CANCEL_OPTION

I have a custom dialog box that collects two strings from the user. I use OK_CANCEL_OPTION for the option type when creating the dialog. Evertyhings works except when a user clicks cancel or closes the dialog it has the same effect has clicking the OK button.

How can i handle the cancel and close events?

Heres the code I'm talking about:

JTextField topicTitle = new JTextField();
JTextField topicDesc = new JTextField();
Object[] message = {"Title: ", topicTitle, "Description: ", topicDesc};

JOptionPane pane = new JOptionPane(message,  JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
JDialog getTopicDialog =  pane.createDialog(null, "New Topic");
getTopicDialog.setVisible(true);

// Do something here when OK is pressed but just dispose when cancel is pressed.
like image 210
philb28 Avatar asked Dec 15 '11 14:12

philb28


People also ask

What are the 4 JOptionPane dialog boxes?

Java AWT Programming Project The JOptionPane displays the dialog boxes with one of the four standard icons (question, information, warning, and error) or the custom icons specified by the user.

What is JOptionPane showInputDialog?

With this method we can prompt the user for input while customizing our dialog window. The showConfirmDialog returns either String or Object and can be called using the following combinations of parameters: Object (returns String) – Shows a question-message dialog requesting input from the user.

What is the purpose of a JOptionPane?

The JOptionPane class is used to provide standard dialog boxes such as message dialog box, confirm dialog box and input dialog box. These dialog boxes are used to display information or get input from the user. The JOptionPane class inherits JComponent class.


1 Answers

I think a better option for you would be to use the following code

    JTextField topicTitle = new JTextField();
    JTextField topicDesc = new JTextField();
    Object[] message = {"Title: ", topicTitle, "Description: ", topicDesc};


    Object[] options = { "Yes", "No" };
    int n = JOptionPane.showOptionDialog(new JFrame(),
            message, "",
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
            options, options[1]);
    if(n == JOptionPane.OK_OPTION){ // Afirmative
        //.... 
    }
    if(n == JOptionPane.NO_OPTION){ // negative
        //....
    }
    if(n == JOptionPane.CLOSED_OPTION){ // closed the dialog
        //....
    }

by using the showOptionDialog method, you are getting an result based on what the user does, so you don't need to do anything else except for interpret that result

like image 114
PTBG Avatar answered Sep 28 '22 02:09

PTBG