62,628
社区成员
发帖
与我相关
我的任务
分享 JFormattedTextField ipField = new JFormattedTextField(ipFormatter);
ipField.setValue(new byte[] { (byte)(192), (byte)168, 4, 1 });
addRow("IP地址格式", ipField); class IPAddressFormatter extends DefaultFormatter {
public String valueToString(Object value) throws ParseException {
if (!(value instanceof byte[])) {
throw new ParseException("该IP地址的值只能是字节数组", 0);
}
byte[] a = (byte[]) value;
if (a.length != 4) {
throw new ParseException("IP地址必须是四个整数", 0);
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 4; i++) {
int b = a[i];
if (b < 0)
b += 256;
builder.append(String.valueOf(b));
if (i < 3)
builder.append('.');
}
return builder.toString();
}
public Object stringToValue(String text) throws ParseException {
// 将格式化文本框内的字符串以点号(.)分成四节。
String[] nums = text.split("\\.");
if (nums.length != 4) {
throw new ParseException("IP地址必须是四个整数", 0);
}
byte[] a = new byte[4];
for (int i = 0; i < 4; i++) {
int b = 0;
try {
b = Integer.parseInt(nums[i]);
} catch (NumberFormatException e) {
throw new ParseException("IP地址必须是整数", 0);
}
if (b < 0 || b >= 256) {
throw new ParseException("IP地址值只能在0~255之间", 0);
}
a[i] = (byte) b;
}
return a;
}
}