01: /*
02: * @(#)PointFormatter.java 4/26/2007
03: *
04: * Copyright 2002 - 2007 JIDE Software Inc. All rights reserved.
05: */
06:
07: package com.jidesoft.spinner;
08:
09: import javax.swing.*;
10: import javax.swing.text.DefaultFormatter;
11: import java.awt.*;
12: import java.text.ParseException;
13:
14: /**
15: * @author Nako Ruru
16: */
17: public class PointFormatter extends DefaultFormatter {
18:
19: private static JFormattedTextField.AbstractFormatter formatter;
20:
21: public synchronized static JFormattedTextField.AbstractFormatter getInstance() {
22: if (formatter == null) {
23: formatter = new PointFormatter();
24: }
25: return formatter;
26: }
27:
28: private PointFormatter() {
29: super ();
30: }
31:
32: @Override
33: public Object stringToValue(String text) throws ParseException {
34: text = text.trim();
35: if (text.startsWith("(") && text.endsWith(")")) {
36: text = text.substring(1, text.length() - 1);
37: }
38: try {
39: String[] splition = text.split(",");
40: return new Point(Integer.parseInt(splition[0].trim()),
41: Integer.parseInt(splition[1].trim()));
42: } catch (Exception e) {
43: e.printStackTrace();
44: return super .stringToValue(text);
45: }
46: }
47:
48: @Override
49: public String valueToString(Object value) throws ParseException {
50: if (value instanceof Point) {
51: Point point = (Point) value;
52: return "(" + point.x + ", " + point.y + ")";
53: } else {
54: return super .valueToString(value);
55: }
56: }
57:
58: public static void main(String[] args) {
59: Point point = new Point(5, -5);
60: JFormattedTextField.AbstractFormatter formatter = PointFormatter
61: .getInstance();
62: String value;
63: try {
64: value = formatter.valueToString(point);
65: } catch (ParseException e) {
66: value = null;
67: }
68: System.out.println(value);
69: value = "(3, -3)";
70: try {
71: point = (Point) formatter.stringToValue(value);
72: } catch (ParseException e) {
73: point = null;
74: }
75: System.out.println(point);
76: }
77:
78: }
|