2011-05-12 42 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