简体   繁体   English

如果 JFormattedTextField 没有适当的文本,如何禁用 JButton 或显示警告对话框

[英]How to disable a JButton or show an alert dialog box if the JFormattedTextField does not have appropriate text

I want to either show an alert dialog box or disable the submit button if the length of the phone number is less than 11.如果电话号码的长度小于 11,我想显示一个警告对话框或禁用提交按钮。

Here is the code for the formatted text field where the user enters the number:这是用户输入数字的格式化文本字段的代码:

        numText = new JFormattedTextField(createFormatter("#### #######"));
        numText.setColumns(15);

        numLabel = new JLabel("Enter Phone Number: ");

        enterButtonTemp = new JButton("Enter");

The code to check the condition is:检查条件的代码是:

        phoneStr = numText.getText();

        System.out.println(phoneStr.length());
        if(phoneStr.length() <= 11){
             //show the JoptionPane for dialog box
        }
        else{
            //Send the name to be stored in db
        }

The code basically checks if the length of the phoneStr is less than 11. If it is it should pop up a dialog box but the.length() method gives 12 as an output even if the text field is left empty.该代码基本上检查 phoneStr 的长度是否小于 11。如果是,它应该弹出一个对话框,但是即使文本字段为空,.length() 方法也会将 12 作为 output 给出。 The following statement outputs 12. Is there any other way to check this condition.以下语句输出 12。是否有任何其他方法可以检查此条件。

System.out.println(phoneStr.length());

Found a solution.找到了解决方案。 Not that efficient but a bit quicker.效率不高,但速度更快。 The formatted text field actually creates the length of the field 12 by default and thus if no input is entered, 12 spaces are inserted by default.默认情况下,格式化文本字段实际上创建了字段 12 的长度,因此如果未输入任何输入,则默认插入 12 个空格。 So instead of using phoneStr.equals(""), the following code works well.因此,下面的代码可以很好地工作,而不是使用 phoneStr.equals("")。 It compares phoneStr with 12 spaces instead of an empty string.它将 phoneStr 与 12 个空格而不是空字符串进行比较。

if(phoneStr.equals("            ")){
     System.out.println("in loop");
     JOptionPane.showMessageDialog(dialogFrame,"Fill all the fields.","Alert",JOptionPane.WARNING_MESSAGE);
}
else{
     //Send the num to db
}

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

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