I have a code sample with JTextFields. When a user does not enter the details in some JTextField, and then clicks the \"Register\" button, I want the u
Here is a simple example. instead of iterating over the length of the inputs, iterate over the fields themselves. If one is empty paint it red and append its corresponding message to the list of messages. Then display that list on a label.
public class Main {
public static void main(String[] args) {
JTextField fName = new JTextField();
fName.setName("First Name");
JTextField lName = new JTextField();
lName.setName("last Name");
JTextField address = new JTextField();
address.setName("Address");
JTextField[] fields = new JTextField[] {fName, lName, address};
StringBuilder sb = new StringBuilder("");
for (JTextField field : fields) {
if (field.getText().isEmpty()){
field.setBackground(Color.RED);
sb.append("").append("You haven't entered " + field.getName());
}
}
JLabel label = new JLabel(sb.toString());
}
}