[英]How to disable a JButton or show an alert dialog box if the JFormattedTextField does not have appropriate text
如果电话号码的长度小于 11,我想显示一个警告对话框或禁用提交按钮。
这是用户输入数字的格式化文本字段的代码:
numText = new JFormattedTextField(createFormatter("#### #######"));
numText.setColumns(15);
numLabel = new JLabel("Enter Phone Number: ");
enterButtonTemp = new JButton("Enter");
检查条件的代码是:
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
}
该代码基本上检查 phoneStr 的长度是否小于 11。如果是,它应该弹出一个对话框,但是即使文本字段为空,.length() 方法也会将 12 作为 output 给出。 以下语句输出 12。是否有任何其他方法可以检查此条件。
System.out.println(phoneStr.length());
找到了解决方案。 效率不高,但速度更快。 默认情况下,格式化文本字段实际上创建了字段 12 的长度,因此如果未输入任何输入,则默认插入 12 个空格。 因此,下面的代码可以很好地工作,而不是使用 phoneStr.equals("")。 它将 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.