[英]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.