IP IP控件 IP输入控件 JFormattedTextField
原理,用最笨的方法,模拟一个输入框,将一个输入框分成几部分[].[].[].[] 几部分, []是一个JFormattedTextField, . 是一个Label,然后重写getText和setText方法就行了,

以下是代码,有说明。
public class IpField extends JTextField {
private Format format = null; // [] 中的内容格式
private Dimension fieldSize = new Dimension(20, 14);
private Dimension dotSize = new Dimension(3, 14);
private int paddingTop = 3;
private JTextField jt1 = null; //一共有4个 []
private JTextField jt2 = null;
private JTextField jt3 = null;
private JTextField jt4 = null;
public IpField() {
super("");
this.setSize(100, 19);
this.setPreferredSize(this.getSize());
this.setLayout(null);
//this.setEditable(false);
this.setBackground(Color.white);
jt1 = new IpFormattedField(127, 1);
jt2 = new IpFormattedField(127, 26);
jt3 = new IpFormattedField(127, 51);
jt4 = new IpFormattedField(127, 76);
this.add(jt1, null);
this.add(new IPDotField(22), null);
this.add(jt2, null);
this.add(new IPDotField(47), null);
this.add(jt3, null);
this.add(new IPDotField(72), null);
this.add(jt4, null);
}
// 这是格式,只能输入##0的数字,没有就为0
private Format getFormat() {
if(format == null) {
try {
format = new DecimalFormat("##0");
} catch(Exception ex) {
}
}
return format;
}
public String getText() { // 重写getText
super.setText("");
return jt1.getText()
.concat(jt2.getText())
.concat(jt3.getText())
.concat(jt4.getText());
}
public void setText(String ip) { // 重写setText
String[] fields = ip.split("\\.");
try { jt1.setText(fields[0]); } catch(Exception ex) {}
try { jt2.setText(fields[1]); } catch(Exception ex) {}
try { jt3.setText(fields[2]); } catch(Exception ex) {}
try { jt4.setText(fields[3]); } catch(Exception ex) {}
}
class IpFormattedField extends JFormattedTextField {
IpFormattedField(int defaultValue, int x) {
super(getFormat());
this.setValue(defaultValue);
this.setBorder(null);
this.setSize(fieldSize);
this.setPreferredSize(fieldSize);
this.setLocation(x, paddingTop);
this.setHorizontalAlignment(JTextField.CENTER);
// 在中间对齐,为了美观,可以更好看
this.setColumns(3);
this.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(KeyEvent e) {
String txt = getText();
if(txt.length() > 3)
{//如果超过3的长度,只取前3位
setText(txt.substring(0, 3));
}
else
{//如果大于255,改为255,如果非数字,交给formated处理
try {
int i = Integer.parseInt(txt);
if(i > 255)
setText("255");
} catch(Exception ex) {
}
}
}
});
}
}
class IPDotField extends Label {
IPDotField(int x) {
super(".");
this.setAlignment(Label.CENTER);
this.setSize(dotSize);
this.setPreferredSize(dotSize);
this.setLocation(x, paddingTop);
}
}
}
Labels:
Trackback: http://cwq.iou1314.com/_a133
Trackback: http://cwq.iou1314.com/_a133




















