2013-01-14 38 views
2

可能重複:
Restricting JTextField input to Integers
Detecting JTextField 「deselect」 event如何驗證一個JTextField只接受整數

我需要通過允許用戶僅輸入整數值來驗證JTextField如果用戶輸入除數字以外的其他字符,JOptionPane.show消息框應該出現,顯示輸入的值不正確,只允許整數。我已經編寫它一個數字值,但我還需要丟棄字母

public void keyPressed(KeyEvent EVT) { 
    String value = text.getText(); 
    int l = value.length(); 
    if (EVT.getKeyChar() >= '0' && EVT.getKeyChar() <= '9') { 
     text.setEditable(true); 
     label.setText(""); 
    } else { 
     text.setEditable(false); 
     label.setText("* Enter only numeric digits(0-9)"); 
    } 
} 
+0

http://theunixshell.blogspot.com/search/label/java – Vijay

回答

6

您可以使用僅允許整數的文檔編寫自定義JTextField,而不使用JFormattedTextField。我只喜歡格式化的字段用於更復雜的蒙版... 看一看。

import javax.swing.JTextField; 
import javax.swing.text.AttributeSet; 
import javax.swing.text.BadLocationException; 
import javax.swing.text.Document; 
import javax.swing.text.PlainDocument; 

/** 
* A JTextField that accepts only integers. 
* 
* @author David Buzatto 
*/ 
public class IntegerField extends JTextField { 

    public IntegerField() { 
     super(); 
    } 

    public IntegerField(int cols) { 
     super(cols); 
    } 

    @Override 
    protected Document createDefaultModel() { 
     return new UpperCaseDocument(); 
    } 

    static class UpperCaseDocument extends PlainDocument { 

     @Override 
     public void insertString(int offs, String str, AttributeSet a) 
       throws BadLocationException { 

      if (str == null) { 
       return; 
      } 

      char[] chars = str.toCharArray(); 
      boolean ok = true; 

      for (int i = 0; i < chars.length; i++) { 

       try { 
        Integer.parseInt(String.valueOf(chars[i])); 
       } catch (NumberFormatException exc) { 
        ok = false; 
        break; 
       } 


      } 

      if (ok) 
       super.insertString(offs, new String(chars), a); 

     } 
    } 

} 

如果您正在使用NetBeans構建你的圖形用戶界面,你只需要把定期JTextFields將在您的GUI,並在創建代碼,您將指定IntegerField的構造。

1

使用JFormattedTextField能力。看看example

相關問題