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:
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:. i want to do this. Does anyone tell me how to do this..????
There are few ways to achieve this...
The first thing you need to do is valid the field...
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.
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
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:
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 detailssetVisible
to toggle the visibility of JLabel
s 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 layoutGridBagLayout
would probably be my choice of layout manager, but you could also use compound layouts to make things eaiser