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();
}
}
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;
}
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 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);
}
I am trying to check if a user entered a number and if not, then it uses a default number like 10. How do i check if the user just presses enter and doesn't enter anything in Java
input = scanner.nextInt();
pseudo code:
if(input == user just presses enter without entering anything){
input = 10;
}
else just proceed with input = what user entered
//scanner is a Scanner
int i; // declare it before the block
try {
i = scanner.nextInt();
}
catch (InputMismatchException ime) {
i = 10;
}
// i is some integer from the user, or 10
First things first, geeeeeez guys, when the OP says something like
"I don't want an exception, i want i = 10 if nothing is entered, so what do i do"
That should clue you in that he probably doesn't know too much about exceptions (maybe even java) and might need a simple answer. And if that's not possible, explain to him the difficult ones.
Alright, here's the plain and simple way to do it
String check;
int input = 10;
check = scanner.nextLine/*Int*/();
if(check.equals(""))
{
//do nothing since input already equals 10
}
else
{
input = Integer.parseInt(check);
}
Let me explain what this code is doing. You were originally using nextInt() to get your number for input, correct? The problem is, nextInt() only responds if the user actually inputs something, not if they press enter. In order to check for enter, we used a method that actually responds when the user presses enter and used that to ensure that our code does what we wanted to. One thing I recommend using is an API, Java has one.
Here's the link for the API HERE
And here's the link for the actual method I used HERE. You can find descriptions and instructions on many methods you'll run into on this API.
Now, back to my answer, that's the easy way to do it. Problem is, this code isn't necessarily safe. It'll throw exceptions if something goes wrong, or if someone is trying to hack into your system. For example, if you were to enter a letter instead of pressing enter or entering a number, it would throw an exception. What you've been seeing in the other answers is what we call exception handling, that's how we make sure exceptions don't happen. If you want an answer that'll catch most of these exceptions, you need to make sure your code catches them, or avoids them all together (I'm simplifying things immensely). The above answer is working code, but isn't safe code, you wouldn't ever use something like this all by itself in real life.
Here is something that might be considered safe code. And no exceptions to keep it simple! ;)
import java.util.Scanner;
public class SOQ15
{
public Scanner scanner;
public SOQ15()
{
scanner = new Scanner(System.in);
int input = 10;
boolean isAnInt = true;
String check;
check = scanner.nextLine/*Int*/();
if(check.equals(""))
{
//do nothing since input already equals 10
}
for(int i = 0; i < check.length(); i++)
{
if(check.charAt(i) >= '0' && check.charAt(i) <= '9' && check.length() < 9)
{
//This is if a number was entered and the user didn't just press enter
}
else
{
isAnInt = false;
}
}
if(isAnInt)
{
input = Integer.parseInt(check);
System.out.println("Here's the number - " + input);
}
}
public static void main(String[] args)
{
SOQ15 soq = new SOQ15();
}
}
I don't have time to go into all the details right now, but ask and I'll gladly respond when I get the time! :)
Well if you are using scanner, given the details provided, you can try:
Scanner in = new Scanner(System.in);
if in.hasNextInt(){ //Without this, the next line would throw an input mismatch exception if given a non-integer
int i = in.nextInt(); //Takes in the next integer
}
You said you wanted a default of 10 otherwise so:
else {
int i = 10;
}
I know this shouldn't be too difficult but my searching hasn't led to anything useful yet. All I want to do is make sure the user inputs a positive integer into a textField. I've tried:
public class myInputVerifier extends InputVerifier {
#Override
public boolean verify(JComponent jc) {
String text = ((jTextFieldMTU) jc).getText();
//Validate input here, like check int by try to parse it using Integer.parseInt(text), and return true or false
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
So in my main code I want to use this to display "OK" if successful and "Enter a positive number" if not successful.
Can someone point me in the right direction please? Thanks!
You could use a try-catch block to check if the input is an integer:
try {
int i = Integer.parseInt(input);
// input is a valid integer
}
catch (NumberFormatException e) {
// input is not a valid integer
}
String has a matches method you can use with regular expressions to see if the contents match a particular pattern. The regular expression for positive integers is ^[1-9]\d*$ so you can use it like this...
boolean matches = text.matches("^[1-9]\d*$");
if(matches){
//Do something if it is valid
}else{
//Do something if it is not
}
I suggest you use try catch.
Catch the NumberFormatException.
In this way you check if the text can be parsed to an integer. If not you can display an error message to the user.
After that you can us an if else statement to check if the number is positive if not positive you can give the user an error message. I suggest you research try catch if you don't know it.