JOptionPane.createDialog and OK_CANCEL_OPTION

I have a custom dialog that collects two lines from the user. When creating a dialog box, I use OK_CANCEL_OPTION for the parameter type. Evertyhings works, unless the user clicks the Cancel button or closes the dialog box with the same effect by clicking the OK button.

How can I handle cancel and close events?

Here is 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. 
+6
source share
3 answers

I think the best 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 //.... } 

using the showOptionDialog method, you get a result based on what the user is doing, so you don’t have to do anything except interpret this result

+4
source

JOptionPane returns in your case

 JOptionPane.OK_OPTION JOptionPane.CLOSED_OPTION JOptionPane.CANCEL_OPTION 

simple example here

+2
source

See the JOptionPane Class . Start reading in the text at the point "Examples:"

Here is my complete example:

 import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.JTextField; public class Main { public static void main(String[] args) { JTextField topicTitle = new JTextField(); JTextField topicDesc = new JTextField(); Object[] message = {"Title: ", topicTitle, "Description: ", topicDesc}; JOptionPane pane = new JOptionPane(message, JOptionPane.PLAIN_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION); JDialog getTopicDialog = pane.createDialog(null, "New Topic"); getTopicDialog.setVisible(true); Object selectedValue = pane.getValue(); int n = -1; if(selectedValue == null) n = JOptionPane.CLOSED_OPTION; else n = Integer.parseInt(selectedValue.toString()); if (n == JOptionPane.YES_OPTION){ System.out.println("Yes"); } else if (n == JOptionPane.NO_OPTION){ System.out.println("No"); } else if (n == JOptionPane.CANCEL_OPTION){ System.out.println("Cancel"); } else if (n == JOptionPane.CLOSED_OPTION){ System.out.println("Close"); } } } 
0
source

Source: https://habr.com/ru/post/903848/


All Articles