I have just wrote an actionPerformed for my save button, that will save data into arraylists, but before that I must be sure that all fields are not empty so if a textfield is empty I want to show a dialogbox and put all empty textfield in red background color
here is my code
//Field outside constructor
private List<Component> comp;
//inside constructor
comp = getAllComponents(this);
//method
public static List<Component> getAllComponents(final Container c) {
Component[] comps = c.getComponents();
List<Component> compList = new ArrayList<Component>();
for (Component comp : comps) {
compList.add(comp);
if (comp instanceof Container)
compList.addAll(getAllComponents((Container) comp));
}
return compList;
}
``
//actionperformed
if(e.getSource() == savebtn){
for(Component item:comp){
if(item.isVisible()){
if(item instanceof JTextField){
JTextField txtField = (JTextField)item;
//here is my problem: with no if statement my program works fine and puts all textfields in red but I want to highlight just empty textfields;
if(txtField.getText() == null)
txtField.setBackground(Color.RED);
}
}
}
}
so how can I solve this problem? thank you very much
Yes Maroun Maroun is right you're checking if the String is null (The Object doesn't exsit). But you want to check if the String is empty. I think the other answer solves you're Problem, but the cleaner solution is to use the isempty method.
if(txtField.getText().isEmpty())
txtField.setBackground(Color.RED);
I would have added a comment to the other answer, but my reputation is not high enough...