Multiple Jtextfields to be filled before Jbutton enable

前端 未结 1 1923
醉话见心
醉话见心 2021-01-16 01:05

Hi I badly need some help I already search about Jtextfield to be filled before jbutton enables, DocumentListener most people use to determined if Jtextfield is being popula

相关标签:
1条回答
  • 2021-01-16 02:08

    if (Ftext.getText().equals("") && Mtext.getText().equals("") && Ltext.getText().equals("") && Addtext.getText().equals(""))

    Means that all the fields must be empty. Some times you need to read this logic aloud...

    "if field is empty AND field is empty AND field is empty..."

    If you used || (or) instead, it would mean that if any one of the fields was empty the statement would be true for example...

    if (Ftext.getText().equals("") || 
        Mtext.getText().equals("") ||
        Ltext.getText().equals("") ||
        Addtext.getText().equals("")) {...
    

    You should also consider using .getText().isEmpty() or .getText().trim().isEmpty() if the fields shouldn't contain just spaces.

    You might also consider writing a single DocumentListener implementation instead of creating a new anonymous class for each field

    public class FieldValidationHandler implements DocumentListener() {
    
        private List<JTextField> monitorFields;
    
        public FieldValidationHandler(JTextField... fields) {
            monitorFields = Arrays.asList(fields);
            for (JTextField field : monitorFields) {
                field.getDocument().addDocumentListener(this);
            }
        }
    
        @Override
        public void insertUpdate(DocumentEvent e) {
            change();
        }
    
        @Override
        public void removeUpdate(DocumentEvent e) {
            change();
        }
    
        @Override
        public void changedUpdate(DocumentEvent e) {
            change();
        }
    
        private void change(){
    
            boolean enabled = true;
            for (JTextField field : monitorFields) {
                if (field.getText().trim().isEmpty()) {
                    enabled = false;
                    break;
                }
            }
            SaveButton.setEnabled(enabled);
        }
    }
    

    Then you'd just create a single instance...

    FieldValidationHandler handler = new FieldValidationHandler(Ftext, Mtext, Ltext, Addtext);
    

    Now, this approach is a little sneaky, in that it adds the DocumentListener to the fields you specify via the constructor automatically.

    Another approach might be to have some kind "Validation" controller, that you would pass to this handler and it would call some kind of "validate" method when change was called.

    This would separate the listener from the fields, but this is all a matter of context at the time.

    I would personally have a "register" and "unregister" process which would allow you to add or remove fields as you need to

    0 讨论(0)
提交回复
热议问题