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;
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
}
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?
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.
db
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. :smash:
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
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!