How to get the focus to a specific field in GUI in Java

When working with Graphical User Interfaces(GUI) the main thing you should keep in your mind is user friendliness. Think about an example that you try to get some details from the user for different text fields. When the user hits the save button we first have to validate the fields as to check the correctness of data. Then, we found that one data in a text field is incorrect. So we have to send a message to the user indicating that there is an error in that particular field. What if we can focus that text field to the user. Is it very friendly, right? It’s just a simple thing. Try this out

//code for the action performed event of the save button
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
.....
if(validateTextFields()){
// save the details
}
}

private booleanvalidateTextFields(){
JOptionPane.showMessageDialog(null, "The data you entered is incorrect", "Warning", 1);
jTextField2.requestFocus(true);
return false;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s