From: Michael B. <mic...@gm...> - 2008-12-10 08:46:12
|
2008/12/2 Michael Bedward <mic...@gm...>: > 2008/12/2 Paulo Santos <prs...@gm...>: >> As format a JFormattedTextField with 99º99' 99.99' '? I am using NetBeans >> 6.1. My Text must be 99º99' 99.99' ' e my Value 99999999. > > Hi Paulo > > You need a class derived from JFormattedTextField.AbstractFormatter to > do this for you... and I just happen to have one here :) > ...and here it is again without stupid the stupid bugs that affect negative coordinates Michael /** * Formatter to handle DMS data with JFormattedTextField * * @author Michael Bedward <mic...@gm...> */ class DMSFormatter extends JFormattedTextField.AbstractFormatter { public static final String DEGREES = "\u00B0"; public static final String MINUTES = "\'"; public static final String SECONDS = "\""; public static final String DECIMAL = "."; private static final String[] delims = {DEGREES, MINUTES, DECIMAL, SECONDS}; /** * Parse a string of degrees, minutes, seconds, decimal seconds * to an Long representation * @param text input string * @return a new Long value * @throws java.text.ParseException */ @Override public Object stringToValue(String str) throws ParseException { long value = 0; String tStr = str.trim(); boolean negative = false; if (tStr.startsWith("-")) { negative = true; tStr = tStr.substring(1); } int pos = 0; long x = 1000000; for (String delim : delims) { int index = tStr.indexOf(delim, pos); if (index > pos) { int part = Integer.parseInt(tStr.substring(pos, index)); value += x * part; pos = index + 1; } x /= 100; } return new Long(value); } /** * Format 99999999 as 99d99m99.99s * @param value an Integer value * @return formatted string * @throws java.text.ParseException */ @Override public String valueToString(Object value) throws ParseException { long lval = (Integer)value; StringBuilder sb = new StringBuilder(); if (lval < 0) { lval = -lval; sb.append("-"); } long[] parts = new long[4]; for (int i = 0; i < parts.length; i++) { if (lval > 0) { parts[i] = lval % 100; lval /= 100; } else { parts[i] = 0; } } for (int i = 0; i < parts.length; i++) { sb.append(parts[parts.length - i - 1]); sb.append(delims[i]); } return sb.toString(); } } |