1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.StringTokenizer;
/**
* @author Muel
*
* An IPAddressFormat formats a number like an IP address. IPAddressFormat should be used in
* conjunction with a JFormattedTextField like so:
* <blockquote>
* JFormattedTextField ipAddress = new JFormattedTextField(new IPAddressFormat());
* </blockquote>
*/
public class IPAddressFormat extends NumberFormat {
private static final long LOCALHOST = 2130706433l;
private static final int LOCALHOST_PARSE_POSITION = 9;
/**
* This method isn't used and returns null.
* @param d
* @param buffer
* @param fp
* @return
* @see java.text.NumberFormat#format(double, java.lang.StringBuffer, java.text.FieldPosition)
*/
public StringBuffer format(double d, StringBuffer buffer, FieldPosition fp) {
return null;
} //end format
/**
* Formats the long in the appropriate style for an IP address.
* @param l
* @param buffer
* @param fp
* @return
* @see java.text.NumberFormat#format(long, java.lang.StringBuffer, java.text.FieldPosition)
*/
public StringBuffer format(long l, StringBuffer buffer, FieldPosition fp) {
StringBuffer buf = new StringBuffer();
buf.append(new Long((l >> 24) & 0x000000ff).toString());
buf.append(".");
buf.append(new Long((l >> 16) & 0x000000ff).toString());
buf.append(".");
buf.append(new Long((l >> 8) & 0x000000ff).toString());
buf.append(".");
buf.append(new Long(l & 0x000000ff).toString());
return buf;
} //end format
/**
* Parses the text into a Long that represents the IP address.
* @param text The text contained within the formatted text field.
* @param pp The current ParsePosition.
* @return A Long that represents an IP address. If the parsing fails the localhost IP is returned.
* @see java.text.NumberFormat#parse(java.lang.String, java.text.ParsePosition)
*/
public Number parse(String text, ParsePosition pp) {
pp.setIndex(text.length());
int c = 24;
long l = 0;
StringTokenizer tokens = new StringTokenizer(text, ".");
try {
while (tokens.hasMoreTokens() && c >= 0) {
int value = Integer.parseInt(tokens.nextToken());
if (value > 255) value = 255;
else if (value < 0) value = 0;
l |= (value << c);
c -= 8;
}
} catch (Exception e) {
pp.setIndex(LOCALHOST_PARSE_POSITION);
return new Long(LOCALHOST);
}
return new Long(l);
} //end parse
} //end class |
Partager