Question

I'm creating frame which asks user to enter his information. I want to notify user using labels or something else when he does not give required input. Like here is the screenshot when all fields are empty: Empty fields

As when wrong input is entered and i move to the next text field text appears in red color below the text field. here is the screenshot:After entering wrong input. i want to do this. Does anyone tell me how to do this..????

Was it helpful?

Solution

There are few ways to achieve this...

The first thing you need to do is valid the field...

You Could...

Use an InputVerifier which allows to validate a field when it loses focus as demonstrated here.

This method also allows you to determine if focus should be continue to the next field or remain with the current field.

You Could...

Use a FocusListener and valid the field when focus is lost. This is pretty much the same thing as the above suggestion, just know you have to do the work yourself

You Could...

Use a DocumentListener on text fields to monitor changes to the fields contents and perform real time validation of the field.

Next, you need to determine the best way to display the state...

You can use:

  • A LineBorder to change the field's border state. Be careful though, some look and feels won't like you doing this (looking at you MacOS). Take a look at How to use borders for more details
  • The tool tip API
  • setVisible to toggle the visibility of JLabels to display error messages, but to be honest, I might be tempted to use a full alpha color to hide the text and a full opaque color to show as this won't effect the layout
  • Ballon Tip
  • GridBagLayout would probably be my choice of layout manager, but you could also use compound layouts to make things eaiser
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top