2014-01-07 123 views
2

我正在使用應用了MaskFormatter的JFormattedTextField,以便輸入電話號碼。有沒有辦法阻止JFormattedTextField自動擦除無效輸入?

但是,當我輸入一個無效的電話號碼,如「123」,然後按下按鈕,JFormattedTextField立即刪除所有文本。

有沒有辦法讓那些無效的文本在那裏?

這裏是一個代碼示例:

import java.awt.FlowLayout; 
import java.text.ParseException; 

import javax.swing.JButton; 
import javax.swing.JFormattedTextField; 
import javax.swing.JFrame; 
import javax.swing.text.MaskFormatter; 

public class Example extends JFrame 
{ 
    private JFormattedTextField formattedTextField; 

    public Example() 
    { 
     this.getContentPane().setLayout(new FlowLayout()); 

     try 
     { 
      MaskFormatter maskFormatter = new MaskFormatter("(###) ###-####"); 
      maskFormatter.setPlaceholderCharacter('_'); 
      formattedTextField = new JFormattedTextField(maskFormatter); 
     } 
     catch (ParseException pe) 
     { 
      System.out.println("Parse Exception"); 
     } 

     JButton button = new JButton("OK"); 

     add(formattedTextField); 
     add(button); 
    } 

    private static void createAndShowGUI() 
    { 
     JFrame frame = new Example(); 

     frame.pack(); 

     frame.setLocationRelativeTo(null); 

     frame.setVisible(true); 

     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 

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

      public void run() { 

       createAndShowGUI(); 

      } 

     }); 
    } 
} 

如果你只輸入幾個數字,如123,然後按下按鈕,你會看到它是如何自動刪除所有的文字。

這好像是因爲我指定

maskFormatter.setPlaceholderCharacter('_'); 

它與下劃線替換所有無效字符,但我想知道是否有辦法留住既無效123的輸入,並還有其餘的下劃線。

+0

是輸入掩碼有4個選項, – mKorbel

回答

4

直從the javadoc第三行:

的JFormattedTextField允許配置什麼丟失焦點時應該採取行動。可能的配置是[...]

+0

此選項可設置,重點是邊.... – mKorbel

+0

formattedTextField.setFocusLostBehavior(JFormattedTextField.COMMIT)似乎工作。 – JDJ

相關問題