2011-05-12 48 views

回答

2

用一個簡單的谷歌搜索,我發現JFormattedTextField的幫助下,這裏有一個關於如何使用它的一個example


IP地址例如:

public static void main(String args[]) throws ParseException 
{ 
    JFrame frame = new JFrame("Test"); 

    JTextField f = new JFormattedTextField(new MaskFormatter("###.###.###.###")); 
    f.setFont(new Font("Monospaced", Font.PLAIN, 10)); 
    frame.add(f); 

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(100, 50); 
    frame.setVisible(true); 
} 
+0

非常感謝以達維爲例。 – yurib 2011-05-12 09:09:13

2

正如先前對堆棧溢出討論(見How do I set the value of a JFormattedTextField with a placeholder character?),你不能輕易使用JFormattedTextField上輸入IP地址。然而,也有來自Sun的RegexFormatter(見http://java.sun.com/products/jfc/tsc/articles/reftf/;在http://java.sun.com/products/jfc/tsc/articles/reftf/RegexFormatter.java下載源代碼),你可以使用這樣的:

JFormattedTextField ipAddress; 
    try{ 
    RegexFormatter ipmask = new RegexFormatter("\\d{0,3}\\.\\d{0,3}\\.\\d{0,3}\\.\\d{0,3}"); 
     ipmask.setOverwriteMode(false); 
    ipAddress = new JFormattedTextField(ipmask); 
}catch(Exception e1){ 
} 
ipAddress.setValue("255.255.255.255"); 

這會讓你輸入/編輯值,並在輸出保存點。

+0

不錯。我已經使用了'RegexFormatter ipmask = new RegexFormatter(「\\ d {1,3} \\。\\ d {1,3} \\。\\ d {1,3} \\。\\ d {1, 3}「);'和'ipAddress.setValue(」...「);'但是,MaskFormatter具有更好的行爲 - 它阻止用戶設置不正確的字符; – xmedeko 2011-12-07 14:55:18