validation in gui and error handling

H

harryos

hi,
I have a gui application which asks the user to input two numerical
values in text fields.
One must be an integer and the other should be a decimal . Also the
user is supposed to select an image file using a filechooser.I would
like to display proper error messages on a text area of the gui if the
selection is wrong or if the textfield inputs are improper.
I figured out that these scenarios can occur.
1.user doesn't select any file
2.user selects a file which is not an image file.
3.user doesnot enter any value in textfields or leaves one blank.
4.user enters invalid string in textfield which cannot be converted to
proper data type(ie int or double).

So,I thought I would do the validation in the model and let controller
ask the view to display appropriate messages.
I made a class ResultData to pass the message and values from model to
the controller.

<code>
class ResultData{
private boolean success;
private String someName;
private String resultMessage;
private double someValue;
public ResultData(boolean s,String n,double sv,String m){
success = s;
someName = n;
someValue = sv;
resultMessage = m;
}
//getters and setters...
}

</code>

In the model I have a processSelections() which accepts user input and
processes them

<code>
public ResultData processSelections(String intFieldInput,String
decimalFieldInput,String selectedFileName ){
ResultData rdata;
int someInteger;
double someDecimal;
try{
validateSelectedFile(selectedFileName);
someInteger = new Integer(intFieldInput).intValue();
someDecimal = new Double(decimalFieldInput).doubleValue();
rdata =
doSomeWorkwithUserInput(selectedFileName,someInteger,someDecimal);

}catch(Exception e){
rdata = new ResultData(false,null,0,e.getMessage());
return rdata;
}

}

private void validateSelectedFile(String fileName)throws Exception{
if (fileName.length() == 0){
throw new RuntimeException("select a file");
}
if (!isAnImageFile(faceimagename)){
throw new RuntimeException("select an imagefile");
}
}
....
</code>

The controller gets a ResultData object containing true value for
success,correct result values and a message if everything went ok.
If there were any exceptions during the validation or in
doSomeWorkwithUserInput() ,the ResultData object will have
success=false, someName=null ,0 for numerical value and the correct
error description in message .controller can ask view to display these
results.

This is the first time I am doing a gui app in java.I am not sure this
is the correct way of dealing with the validations and error
displays.If someone can point me to the right way ,it will help me a
lot.
thanks in advance,
harry
 
J

John B. Matthews

harryos said:
I have a gui application which asks the user to input two numerical
values in text fields.
One must be an integer and the other should be a decimal . Also the
user is supposed to select an image file using a filechooser.I would
like to display proper error messages on a text area of the gui if
the selection is wrong or if the textfield inputs are improper. I
figured out that these scenarios can occur.
1.user doesn't select any file
2.user selects a file which is not an image file.
3.user doesnot enter any value in textfields or leaves one blank.
4.user enters invalid string in textfield which cannot be converted to
proper data type(ie int or double).

So, I thought I would do the validation in the model and let
controller ask the view to display appropriate messages.

I'd also look at InputVerifier as a means of validating input before
it leaves the view. It may simplify your model's validation process:

<http://download.oracle.com/javase/6/docs/api/javax/swing/InputVerifier.html>

This example handles a non-image file by returning false from the
setImage() method of MyImagePanel:

<http://stackoverflow.com/questions/4054307>

[...]
 
H

harryos

I'd also look at InputVerifier as a means of validating input before
it leaves the view. It may simplify your model's validation process:


Thanks for the reply and pointer..InputVerifier simplifies it.but
suppose I make the app non gui(just command line)it may not help.I
will still have to handle all the exceptions.

This example handles a non-image file by returning false from the
setImage() method of MyImagePanel:

<http://stackoverflow.com/questions/4054307>


Thanks again..Will go through this.
regards
harry
 
M

markspace

So,I thought I would do the validation in the model and let controller
ask the view to display appropriate messages.


The thing here is should the model really be aware of the user's input
data?

First, to echo John's sentiments, there's also JFormattedTextField which
might make the input of values easier on users (and less likely to be
wrong when you validate it).

(Note: none of the code in this post was checked with a compiler.)

JFormattedTextField num = new JFormattedTextField( new Integer(32) );
JFormattedTextField fract = new JFormattedTextField(
new DecimalFormat( "###,###.##" ) );

But for validating in the model, for me it kinda depends on what your
model is. If the model is an actual object with an integer field, a
decimal field and an image, then perhaps adding a factory to parse an
object from string parameters is sensible.

public class MyModel {

private int num;
private BigDecimal fract;
private Image img;

public static MyModel makeInstance( String num, String fract,
String img )
throws IllegalArgumentException
{
// verify here...
}

Factories are a slightly more standard idiom Java, and easily
recognizable to most programmers.

OTOH, if the int, decimal and image are unrelated to each other, if you
don't actually have a "model" for those, then building a ResultData
object seems rather baroque to me. Java already has standard models for
those, with their own string factories or constructors (as appropriate),
and there's no reason not to use them.

String num = ...
String fract = ...
String img = ...
try {
int number = Integer.parse( num );
BigDecimal fraction = new BigDecimal( fract );
Image image = ImageIO.read( img );
} catch( ... variousException ex ) {
view.setErrorMessage( ex.toString() );
}

This seems a lot simpler to me than your way of doing it. It's simple
enough where making it part of the model doesn't seem to add a lot of
value. It could be easily done by the controller, there's no need for a
complicated return object or special validation code.

If the code gets much more complicated, you can always add a static
"utility" method to do parsing and return an exception, but I think
that's as far as I would go unless things get truly horrendous.
 
M

Martin Gregorie

Thanks for the reply and pointer..InputVerifier simplifies it.but
suppose I make the app non gui(just command line)it may not help.I will
still have to handle all the exceptions.
I see that InputVerifier doesn't appear to provide a method for giving
feedback to the user. Personally I'd find it very annoying to be locked
into a field without any feedback to say what was wrong with my input.

JFormattedTextField is much better since it looks as if its invalidEdit
method can be overridden to, e.g. display an error message in another
JTextField.

However, there are still cases, such as where only specific combinations
of the content of several fields are valid, when IMO its worth while
passing all the fields back to the Model for validation and using the
Observer mechanism to update the error message field.

And, only sort of slightly off topic, if you're inputting a Date or
Timestamp through a JTextField plus SimpleDateFormat.parse() and you
don't call SimpleDateFormat.setLenient(false) you'll probably not get the
validation behaviour you're expecting.

If you let parsing leniency default and input a date involving 30th Feb,
on displaying the resulting date value you'll find that the input will be
considered valid and the date will be set to the 1st or 2nd of March
depending on whether the date is a leap year.
 
S

Stefan Ram

harryos said:
I have a gui application which asks the user to input two numerical
values in text fields.

Most probably »numerals« not »values« - by my terminology.
One must be an integer and the other should be a decimal .

Usually the decimal system also is used for integral numerals.
So this is not a specification precise enough for a coder
to start to work from it.
So,I thought I would do the validation in the model and let controller
ask the view to display appropriate messages.

Code can be structured by a recursive application of the
MVC architecture:

You want a control to get two numerals from the user.

From the external point of view, this control is just a part
of the view and always will deliver a valid input (i.e.,
either two numerals, or, possibly, a »CANCELED« value.)

From the internal view of this control, it is made of a model,
a view, and a controller, itself.
This is the first time I am doing a gui app in java.I am not
sure this is the correct way of dealing with the validations
and error displays.If someone can point me to the right way
,it will help me a lot.

Read GUI code written by successful programmers before
writing your own. For example, study the sourcecode of some
Swing controls, for example, the JFileChooser.
 
J

John B. Matthews

Martin Gregorie said:
I see that InputVerifier doesn't appear to provide a method for giving
feedback to the user. Personally I'd find it very annoying to be locked
into a field without any feedback to say what was wrong with my input.

JFormattedTextField is much better since it looks as if its invalidEdit
method can be overridden to, e.g. display an error message in another
JTextField.

However, there are still cases, such as where only specific combinations
of the content of several fields are valid, when IMO its worth while
passing all the fields back to the Model for validation and using the
Observer mechanism to update the error message field.

And, only sort of slightly off topic, if you're inputting a Date or
Timestamp through a JTextField plus SimpleDateFormat.parse() and you
don't call SimpleDateFormat.setLenient(false) you'll probably not get the
validation behaviour you're expecting.

If you let parsing leniency default and input a date involving 30th Feb,
on displaying the resulting date value you'll find that the input will be
considered valid and the date will be set to the 1st or 2nd of March
depending on whether the date is a leap year.

All excellent points. This related example combines InputVerifier and
JFormattedTextField. It also demonstrates the effect of leniency, so
that 131-Oct-2010 silently becomes 08-Feb-2011.

<http://stackoverflow.com/questions/2241997>

I haven't found a generally useful way to address the feedback problem.
A tooltip or a status label may be overlooked, and beeping is just
annoying. In one scenario, I arranged to turn the problem character(s) a
different color.
 
J

John

All excellent points. This related example combines InputVerifier and
JFormattedTextField. It also demonstrates the effect of leniency, so
that 131-Oct-2010 silently becomes 08-Feb-2011.

<http://stackoverflow.com/questions/2241997>

I haven't found a generally useful way to address the feedback problem.
A tooltip or a status label may be overlooked, and beeping is just
annoying. In one scenario, I arranged to turn the problem character(s) a
different color.

I agree that there is no generally useful way. I have seen the use of
a different color work well.
I usually try to pop a message in either a JFrame or a JOptionPane
that tells the user which tab or frame the bad input
was in, what the name of the input was, what the bad value was, and if
I can tell, what about the value was invalid. Such
as using a comma in the input of a number, or having an embedded
space, etc. I try not to use theJOptionPane, because
the default is a blocking dialog. The JFrame implements FocusListener,
and disposes of itself when it loses the focus, so
the user can click anywhere to dismiss the message. If you're
interested you can go to
http://www.lanl.gov/orgs/da/d3/programming.shtml
and look at the description for status popups. This one is based on an
AWT frame, and we have a Swing version based on
a JFrame.

John
 
M

Martin Gregorie

I haven't found a generally useful way to address the feedback problem.
A tooltip or a status label may be overlooked, and beeping is just
annoying. In one scenario, I arranged to turn the problem character(s) a
different color.
I tend to put error messages, often formatted as red on white, in a
specially reserved JTextField at the bottom of the JPanel, but this is
partly doing what I'm used to: my favourite 4GL puts errors and comments
on the bottom line of the screen. Its common practise on a number of
mainframe online systems and is the house style for OS/400 interactive
screens.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top