2012-09-06 39 views
1

我正在學習java swing。有一個可編輯的JComboBox選擇不同深度的水和JTextField接受手機號碼。我的問題是,如何限制用戶在這兩個字段中只輸入數字,以及如何限制手機號碼的最大字符輸入數不超過10個?方法是否可用於這些需求,或者我需要定義他們自己的方法? 在此先感謝您的幫助。如何限制輸入類型

+4

您可能會使用一個帶有數字模型的JSpinner。 –

回答

4

使用JFormattedTextField是這樣的:

public static void main(String[] args) { 
    SwingUtilities.invokeLater(new Runnable() { 

     @Override 
     public void run() { 
      JFrame frame = new JFrame("JFormattedTextField Example"); 
      MaskFormatter fmt = null; 

      // A phone number 10 digits 
      try { 
       fmt = new MaskFormatter("(###)-###-####");//brackets() are optional just there for my pref 
       fmt.setPlaceholderCharacter('*');//set place holder for the empty digits of the number 

      } catch (java.text.ParseException e) { 
      } 

      JFormattedTextField tft1 = new JFormattedTextField(fmt); 

      frame.add(tft1); 

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      frame.setLocationRelativeTo(null); 
      frame.pack(); 
      frame.setVisible(true); 
     } 
    }); 
} 

這會自動有你想要將只接受指定的格式 數字的性質有一個在該文檔也可瞭解詳情:JFormattedTextField

+1

感謝您的幫助。 –

0

如何限制用戶在電話文本字段中輸入數字以外的字符

TF1.addKeyListener(new KeyListener() { 

      @Override 
      public void keyTyped(KeyEvent arg0) { 
       // TODO Auto-generated method stub 
       char k=arg0.getKeyChar(); 
       if (!(k>='0' && k<='9')) 
        arg0.consume(); 
      } 

      @Override 
      public void keyReleased(KeyEvent arg0) { 
       // TODO Auto-generated method stub    
      } 

      @Override 
      public void keyPressed(KeyEvent arg0) { 
       // TODO Auto-generated method stub    
      } 
     }); 
+1

絕對不是一個好的方法,而是使用[JTextField]中的[DocumentListener](http://docs.oracle.com/javase/tutorial/uiswing/events/documentlistener.html)(即使那樣),這就是' JFormattedTextField是IMO的必備條件 –