2014-01-12 18 views
1

我創建與MaskFormatter之外掩蓋JFormattedTextField的框架:蒙面的JFormattedTextField防止刪除斜槓字符

public static void main(String[] args) { 
    DateFormat df = new SimpleDateFormat("dd-mm-yyyy"); 
    JFrame frame = new JFrame(""); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    JPanel panel = new JPanel(); 
    frame.setLayout(new BorderLayout()); 
    JFormattedTextField tf = new JFormattedTextField(df); 
    tf.setColumns(20); 
    panel.add(tf); 
    try { 
     MaskFormatter dateMask = new MaskFormatter("##-##-####"); 
     dateMask.install(tf); 
    } catch (ParseException ex) { 
     Logger.getLogger(MaskFormatterTest.class.getName()).log(Level.SEVERE, null, ex); 
    } 

    frame.add(new JButton(), BorderLayout.LINE_START); 

    frame.add(panel, BorderLayout.LINE_END); 
    frame.pack(); 
    frame.setVisible(true); 
} 

確定。這是正常的,但是當我刪除(用鍵盤鍵)我在字段中寫入的文本也刪除斜槓。有沒有什麼模式可以阻止它?我想刪除文字,但沒有斜槓,如:

寫作日期:

"12-12-1212" 

後刪除:

" - - " 

回答

4

你如何刪除文本?你在用setText("")嗎?你不應該那樣做。改爲使用setValue(null)。 如果這不是你的問題,請詳細說明你在做什麼以及發生了什麼。

編輯:嘗試此代碼,看看問題是否存在。

public class Tester { 
    public static void main(String[] args) { 
    DateFormat df = new SimpleDateFormat("dd/mm/yyyy"); 
    JFrame frame = new JFrame(""); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    JPanel panel = new JPanel(); 
    frame.setLayout(new BorderLayout()); 
    JFormattedTextField tf = new JFormattedTextField(df); 
    tf.setFocusLostBehavior(JFormattedTextField.COMMIT); 
    tf.setColumns(20); 
    panel.add(tf); 
    try { 
     MaskFormatter dateMask = new MaskFormatter("##-##-####"); 
     dateMask.install(tf); 
    } catch (ParseException ex) { 
    } 

    frame.add(new JButton(), BorderLayout.LINE_START); 

    frame.add(panel, BorderLayout.LINE_END); 
    frame.pack(); 
    frame.setVisible(true); 
    } 
}´ 

EDIT2: 嘗試添加 tf.setFocusLostBehavior(JFormattedTextField.COMMIT); 請參閱JavDoc進一步閱讀。

+0

用鍵盤刪除 – DrkDeveloper

+0

如果我試用它,這可以在你的例子中起作用。 '-'字符保持原位。通常情況下,JFormattedTextField的行爲就是這樣,如果你給它一個無效的文本,它就會以這種方式打破。你可以發佈你的所有代碼嗎? –

+0

這是我所有的代碼 – DrkDeveloper