簡體   English   中英

檢查JTextField是否僅包含特定的允許字符

[英]Checking if JTextField contains only specific allowed characters

我有一個JFormattedTextField ,我只想插入字母數字字符。 我正在嘗試使用此代碼在用戶鍵入不允許的字符時啟動JDialog ,以防萬一可以從JFormattedTextField獲取字符串。 運行此代碼時,鍵入符號時不會出現JOptionPane 我知道我的代碼有問題,但是由於我的經驗不足,我無法識別它。 我將不勝感激。

先感謝您

static JFormattedTextField indivname = new JFormattedTextField();

final String individ = indivname.getText();

indivname.getDocument().addDocumentListener(new DocumentListener() {
    public void changedUpdate(DocumentEvent e) {
        warn(individ);
    }
    public void removeUpdate(DocumentEvent e) {
        warn(individ);
    }
    public void insertUpdate(DocumentEvent e) {
        warn(individ);
    }       
    public void warn(String textcheck) {
        textcheck = indivname.getText();
        boolean match = textcheck.matches("[a-zA-Z0-9]+"); 

        if (match=false) {                            
            JOptionPane.showMessageDialog(null, "You have inserted restricted characters (Only alphanumeric characters are allowed)", "Warning", JOptionPane.WARNING_MESSAGE);                   
        }

        if (match=true) {                            
            textcheck = individ ;                     
        }                   
    }
});

您在if語句的行中使用賦值運算符=而不是比較==

 if (match = false) {

 ...

 if (match=true) {

表達式match = false導致match獲得一個false值,並且整個表達式始終返回false

您應該將它們替換為:

 if (!match) {
     JOptionPane.showMessageDialog(null, "You have inserted restricted characters (Only alphanumeric characters are allowed)", "Warning", JOptionPane.WARNING_MESSAGE);
 } else { // instead of if(match)
     textcheck = individ;
 }

它直接使用match的值來確定要執行的分支。

使用if (match=false)您要分配false值來match ,然后if檢查其值,並且由於它為false因此將跳過此塊。

if(match=true)

采用

  • if(match==false)或更好地避免==錯誤使用if (!match)
  • if(match==true)或更好的if(match)

使用JFormattedTextField的目的是在輸入文本時對其進行編輯,以便不能添加無效字符。

閱讀Swing教程中有關如何使用格式文本字段的部分,以獲取更多信息和示例。 您可能需要有關Mask Formatters的部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM