简体   繁体   English

在填写必填字段之前禁用JButton所需的建议 - Java

[英]Advice needed with disabling a JButton until required fields have been filled in - Java

I am making a courier program in which the user can create a new account. 我正在制作一个快递程序,用户可以在其中创建一个新帐户。 I want to have a next button that the user cannot press until the text fields have been filled in. 我希望有一个下一个按钮,用户在填写文本字段之前无法按下该按钮。

So a blank Name Field and Surname field would mean the next button cannot be pressed but if the fields have been filled in, the next button can be pressed 因此,空白的名称字段和姓氏字段将意味着无法按下下一个按钮,但如果已填写字段,则可以按下下一个按钮

Add a KeyListener like this to your fields: 像这样添加KeyListener到您的字段:

nameField.addKeyListener(new KeyAdapter() {
        public void keyReleased(KeyEvent e) {
            super.keyReleased(e);
            if(nameField.getText().length() > 0 && surNameField.getText().length() > 0)
                nextButton.setEnabled(true);
            else
                nextButton.setEnabled(false);
        }
    });

This will check if the two fields are not empty, every time a key has been pressed in the field. 每次在字段中按下某个键时,这将检查两个字段是否为空。 If the condition is true, the next button will be enabled. 如果条件为真,则启用下一个按钮。

In your actionPerformed method, for every actionEvent checking, check whether the required fields are filled up, if so, set your button setEnabled(true). 在actionPerformed方法中,对于每个actionEvent检查,检查是否填充了必填字段,如果是,请设置按钮setEnabled(true)。 Perhaps a better answer can be provided if you can show us your code. 如果您可以向我们展示您的代码,也许可以提供更好的答案。

In simple term, try something like. 简单来说,尝试类似的东西。

String text = textField.getText();
if (text.length()>0)
   button.setEnabled(true);
 ...

If you want to have the button enable on the fly then its a bit more complicated 如果你想在运行中启用按钮,那么它会更复杂一些

EDIT : 编辑:

complicated case: 复杂案例:

Document textFieldDoc = myTextField.getDocument();
textFieldDoc.addDocumentListener(new DocumentListener() {
 void changedUpdate(DocumentEvent e) {
   updated(e);
}
void insertUpdate(DocumentEvent e) {
   updated(e);
}
void removeUpdate(DocumentEvent e) {
   updated(e);
}
private void updated(DocumentEvent e) {
   boolean enable = e.getDocument().getLength() > 0;
   myButton.setEnabled(enable);
}
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM