开发者

Checking whether the text in a JTextField is a certain data type

I am trying to write some validation code in my class for my GUI. How would I go about getting the text from a JTextField into a while statement and prompting a JOptionPane for the user to enter the necessary number(double)? To be more specific, how do I check if what I got from the JTextField is a string/string+number/anything other than a number?

String text=JTextField.getText();

while(text.equals*a string or anything but a number*);
   JOP("Invalid input ............ etc...

If you have time, here is my GUI and my class. I am trying to do this for the rest of the methods. But the answer to the above will suffice.

http://www.mediafire.com/?f079i1xtihypg1b

http://www.mediafire.com/file/f079i1xtihypg1b/FinanceGUI.java

Update:

This is what I have so far:

  //get the text entered in the amountRentText
  //JTextField and parse it to a Doubl开发者_高级运维e
String amtRentIn=amountRentText.getText();

try{Double.parseDouble(amtRentIn);}
catch(NumberFormatException nfe){
   while()
       amtRentIn=JOptionPane.showInputDialog("Invalid input. Please "+
           "enter your rent: ");
 }

 double rent= Double.parseDouble(amtRentIn);
 fin.setRent(rent);

What do I put in the while?


String amtRentIn=amountRentText.getText();
boolean incorrect = true;
while(incorrect){
try{Double.parseDouble(amtRentIn);incorrect = false;}
catch(NumberFormatException nfe){
   amtRentIn=JOptionPane.showInputDialog("Invalid input. Please "+
           "enter your rent: ");
 }

}


javax.swing.InputVerifier is designed for this. Your implementation of verify() could invoke parseDuble(). Here's another example.


A "cheap" not too beautiful solution that occurs to me would be using the Double.parseDouble(..) on that string, and being ready to catch the parsing exception that would occur in the event the String had any non-numeric content.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜