0

Ok, so I understand that if you want to test what the user clicks in a JOptionPane, you would do something like this:

final int option = JOptionPane.showConfirmDialog(null, "That file name does not exist.", "File Name", JOptionPane.OK_CANCEL_OPTION);

                if(option == JOptionPane.CANCEL_OPTION)
                {
                    g++;
                }

However, what if I wanted to set a String = to a JOptionPane like this?

String fileName = JOptionPane.showInputDialog("File Name") + ".txt";

How am I supposed to compare what the user clicked then?

CRABOLO
  • 8,605
  • 39
  • 41
  • 68
NathanWick
  • 87
  • 1
  • 10

2 Answers2

0

When you're using showInputDialog() you want to get user input from a textfield, not depend on what the user clicked.

You can use either a JOptionPane with an input field

String s = JOptionPane.showInputDialog(null, "Enter a message:); 

Or you can use a combobox style JOptionPane

Object[] possibilities = {"ham", "spam", "yam"};
String s = (String)JOptionPane.showInputDialog(
                null,
                "Complete the sentence:\n"
                + "\"Green eggs and...\"",
                "Customized Dialog",
                JOptionPane.PLAIN_MESSAGE,
                null,
                possibilities,
                "ham");

Edit:

String s = JOptionPane.showInputDialog(null, "Enter a message:); 
if (s != null){     // OK is pressed with a value in the field
    // do something with s
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
0

you can use as you mentioned

String fileName = JOptionPane.showInputDialog("File Name");

Default input dialog has OK button and cancel buttons. Therefore if you press cancel button your string value will be null Otherwise it is the value you entered on textfield

so you can have a if(fileName == null) to check whether user clicked cancel or OK button

String fileName = JOptionPane.showInputDialog("Enter file name");
if (fileName == null) {
      System.out.println("User pressed cancel");
      //your logic
}else{
      System.out.println(fileName);
      //your logic
}