I want to take input as string from user through a Input dialog box, and also handle the situation if user presses cancel button.
Any suggestions?
You may use the showInputDialog method of class JOptionPane .
If the user hits Cancel, the returned value is null.
Also note, as #mKorbel said in the comments, that you will also get null if the windows has been closed directly.
String result = JOptionPane.showInputDialog("Please enter something");
if(result == null){
System.out.println("User pressed CANCEL, or window has been closed");
}
else{
// do something with the String
}
Try this:
if(result == null){
System.out.println("User pressed CANCEL, or window has been closed");
System.exit(0);
}
Related
I'm unsure of best practices with JOptionPanes, though this could equally just be a logic problem. I want an input box that asks for a name, checks it is a letter only string, and user can cancel.
I understand that cancelling a JOptionPane results in returning a null, which I've implemented at the start. The issue is that if a user enters incorrectly in the first pane, they cannot cancel from the second.
EDIT: worth pointing out that if user cancels I don't want to do anything with the name. This is the issue that forces me into the loop. Logic should be to check user input; if ==2 do nothing. If something else, validate is a word and use it. Loop around if not valid. The problem is the user can cancel later and the action of using the name is actioned anyway since it's in the second loop, with the value of 2.
I currently have:
JOptionPane optionPane1 = new JOptionPane(text, OK_OPTION, CANCEL_OPTION);
optionPane1.setWantsInput(true);
JDialog d1 = optionPane1.createDialog(null);
d1.setVisible(true);
name = optionPane1.getInputValue().toString();
if(name == null){
gamePaused = true;
}
else{
while(!name.matches("^[a-zA-Z]+$") || name.length() == 0){
JOptionPane optionPane2 = new JOptionPane("Please enter a word.\nTry again.", OK_OPTION, CANCEL_OPTION);
optionPane2.setWantsInput(true);
JDialog d2 = optionPane2.createDialog(null);
d2.setVisible(true);
name = optionPane2.getInputValue().toString();
}
///use name
}
Is there a better way of doing this, so that I can allow a user to cancel and escape the loop?
You can replace all your code with this one
do {
name = JOptionPane.showInputDialog(null, "Enter name here : ", "title", JOptionPane.OK_CANCEL_OPTION);
} while(name != null && !name.matches("^[a-zA-Z]+$"));
if (name == null) {
gamePaused = true;
} else {
//Do whatever want with the name
}
The problem is that inside your while loop, there is no further check whether the user pressed cancel (which means name == null). Once the user enters something invalid in his first attempt, he stays inside of the while loop and is asked for his name over and over again until there is a valid input, and the program does not care anymore about whether he clicked cancel. Therefore, you need to add before name = optionPane2.getInputValue().toString();:
if (optionPane2.getInputValue() == null) {
gamePaused = true;
break;
}
Inside your while loop, check if cancel is selected by user:
Add this inside the while loop:
if(optionPane2.getValue().toString().equals ("2")){ // 2 for close option in your case
break;
}
Am working on a project where i need to ask the user to enter a path to save the program using jOptionPane but my problem is if the user dont put anything in the text and click cancel or ok am getting an error...i tried to control it buy checking the string if is Empty() or equals to null
Try to make a function for this JOptionPane, case you need back again, and don't forget to catch the errors with methods like NullPointerException.
public void optionPane(){
String m = JOptionPane.showInputDialog("your text...");
try{
if((m == null) || (m.equals(""))){
optionPane();
}
}catch(NullPointerException e){
optionPane();
}
}
I am building a GUI for some Java project. I need to validate what user input on JTextField. But I have a small problem.
The JTextField is for entering Integer. So, I did try and catch for NumberFormatException. The question is: if the user fires an action (press Enter) without writing anything in the JTextField even space, How could I handle this?
int id = 0;
try {
id = Integer.parseInt(tfID.getText());
} catch (NumberFormatException e1 ) {
if (tfID.getText()==null) //This does not work
idError.setText("Enter an Integer");
else
idError.setText("Intgers only accepted");
}
I want to show a message on another JTextfield (which is idError in this case) to tell the user to enter an Integer.
Thanks in advance.
Instead of using:
if (tfID.getText()==null)
use:
if( tfID.getText().equals("") )
which will return true if and only if the two strings are equal, which is here tfID.getText() and ("").
Thanks for you all.
I am developing a custom keyboard.In this, I use an Enter button which works well as an enter key when I typed in a text or messaging But I want to use this button as a search key when any one type in a browser. In my keyboard, this works as newline instead of search.How can I handle this with the same button?
I am following this Link to make this Keyboard
https://code.tutsplus.com/tutorials/create-a-custom-keyboard-on-android--cms-22615
here is code
if(primaryCode == Keyboard.KEYCODE_DONE ) {
ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER));
}
Maybe you could use:
if(primaryCode == Keyboard.KEYCODE_DONE ) {
if(Patterns.WEB_URL.matcher(editText.getText().toString()).matches()){
search();
} else {
ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_ENTER));
}
}
I am trying to cover possible options when using the JOptionPane.showInputDialog box.The user must enter a "Y" to continue running the code, "N" will cancel the procedure and clicking the cancel button should do the same as typing "N". But, when the user clicks cancel, I want to show the a message like "You have chosen to cancel the order" before the System.exit(0) runs. I have not been able to get that message to display. Below is the code I have so far:
inputStr = JOptionPane.showInputDialog("Enter an order (Y/N)");
if(inputStr.equalsIgnoreCase("N")){
JOptionPane.showMessageDialog(null, "Since you are not entering an order....\n" +
"The program will close.");
System.exit(0);
}
else if(inputStr.equals(null)){
JOptionPane.showMessageDialog(null, "You have chosen to cancel this order");
System.exit(0);
}
else if(!inputStr.equalsIgnoreCase("Y")){
JOptionPane.showMessageDialog(null, "You have entered an invalid character.\n" +
"Enter a 'Y' or 'N' only.");
continue;
}
I would use the YES_NO_CANCEL_OPTION:
Object[] options = {"Yes","No","Cancel"};
int n = JOptionPane.showOptionDialog(frame,
"Continue?",
"Would you like to continue?",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);
if (n == JOptionPane.YES_OPTION) {
System.out.println("Clicked Yes");
} else if (n == JOptionPane.NO_OPTION) {
System.out.println("Clicked No");
} else if (n == JOptionPane.CANCEL_OPTION) {
System.out.println("Clicked Cancel");
} else {
System.out.println("something else (like clicked the 'x' button)");
}
Try changing inputStr.equals(null) to inputStr == null
Works fine as long as you change the if statments around to what they are below.
String inputStr;
inputStr = JOptionPane.showInputDialog("Enter an order (Y/N)");
if(inputStr == null){
JOptionPane.showMessageDialog(null, "You have chosen to cancel this order");
System.out.println("hello");
System.exit(0);
}
else if(inputStr.equalsIgnoreCase("N")){
JOptionPane.showMessageDialog(null, "Since you are not entering an order....\n" +
"The program will close.");
System.exit(0);
}
else if(!inputStr.equalsIgnoreCase("Y")){
JOptionPane.showMessageDialog(null, "You have entered an invalid character.\n" +
"Enter a 'Y' or 'N' only.");
}
Think about
if(inputStr.equals(null)){
Does it make sense to call the 'equals()' method on a 'null' object? Because if inputStr is null, then you would not be able to call a method on it.
The correct syntax would be:
if(inputStr == null){
and do this as the first 'if', to protect you from a NPE.
This what i will do
String inputStr = JOptionPane.showInputDialog("Enter an order (Y/N)");
if (inputStr == null || inputStr.isEmpty()) {
JOptionPane.showMessageDialog(null, "You Cancelled");
} else {
if (inputStr.equalsIgnoreCase("N")) {
JOptionPane.showMessageDialog(null,
"Since you are not entering an order....\n"
+ "The program will close.");
System.exit(0);
} else if (!inputStr.equalsIgnoreCase("Y")) {
JOptionPane.showMessageDialog(null,
"You have entered an invalid character.\n"
+ "Enter a 'Y' or 'N' only.");
}
}
Goodluck
Make a delay in between exit(0) and message with javax.swing.Timer
And Change
if(inputStr.equals(null)){
with
if(inputStr == null){
== will always compare for identity - i.e. whether the two values are references to the same object. This is also called reference equality. Java doesn't have any user-defined operator overloading.
.equals() will call the virtual equals method declared by Object, unless a more specific overload has been introduced by the compile-time type of inputStr.
Of course, if inputStr is null then you'll get a NullPointerException when you try to call inputStr.equals(null).