Results 1 to 5 of 5
- 02-19-2012, 10:20 PM #1
JTextField and Try-Catch Question
I have a general question about using JTextFields and Try-Catches properly.. If I had, say 3 JTextFields that are only supposed to accept integers, how can I initiate a try-catch to check WHICH JTextField has incorrect information?
I know how to use a normal try-catch, for example;
Something along the lines of that. Would I have to do a try-catch inside a try-catch? If so, how could I format that properly?Java Code:try { int price1 = Integer.parseInt(txtField1.getText()); int price2 = Integer.parseInt(txtField2.getText()); int price3 = Integer.parseInt(txtField3.getText()); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Please fill in the required fields", "Invalid data!", JOptionPane.ERROR_MESSAGE); //Now here's the problem, program needs to determine WHICH JTextFields //have crashed and do something with it afterwards.. like setting the background //of said textfield red, for example }Last edited by CuppaCoffee; 02-19-2012 at 10:24 PM.
- 02-19-2012, 10:28 PM #2
Re: JTextField and Try-Catch Question
Programming by Exception is generally regarded as bad form. You could use a DocumentFilter that permits only digits and does a bounds check to prevent a text that would represent a value greater than Integer.MAX_VALUE.
Moving to AWT/Swing.
dbWhy do they call it rush hour when nothing moves? - Robin Williams
- 02-19-2012, 10:37 PM #3
Re: JTextField and Try-Catch Question
I would do that, but this is an in-class assignment and we're specifically learning about try-catch statements, so I'll have to abide by the assignment rules.
- 02-19-2012, 11:12 PM #4
Re: JTextField and Try-Catch Question
Use an array for the text fields and the index will tell you which one had the bad data
or put each of the parseInt() calls in its own try/catch
- 02-20-2012, 01:16 AM #5
Re: JTextField and Try-Catch Question
Yeah, I did what Norm suggested and gave each parseInt() it's own try/catch. It has a lot of confusing nonsense involved.. but my teacher said it's correct, in the terms for which he asked for, so there's no real need to post the code.
Thanks for the suggestions, guys. Much appreciated!Last edited by CuppaCoffee; 02-20-2012 at 01:18 AM.
Similar Threads
-
JTextfield question
By xyknight in forum New To JavaReplies: 3Last Post: 04-08-2011, 04:25 PM -
JTextField Question
By Rocketz in forum New To JavaReplies: 1Last Post: 03-09-2011, 12:38 AM -
JTextField Question
By Kyle227 in forum New To JavaReplies: 5Last Post: 05-09-2010, 07:44 AM -
JTextField question
By Chasingxsuns in forum New To JavaReplies: 5Last Post: 07-14-2009, 02:39 AM -
Question reg try/catch block
By nn12 in forum New To JavaReplies: 1Last Post: 09-16-2008, 05:56 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks