| 1 | // Copyright 2004-2007 Jean-Francois Poilpret |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package net.sourceforge.hivegui.component; |
| 16 | |
| 17 | import java.text.AttributedCharacterIterator; |
| 18 | import java.text.FieldPosition; |
| 19 | import java.text.Format; |
| 20 | import java.text.ParseException; |
| 21 | import java.text.ParsePosition; |
| 22 | |
| 23 | /** |
| 24 | * Format, used with JFormattedTextField, that allows empty strings as valid |
| 25 | * input (empty input will give a null value, and conversely). |
| 26 | * |
| 27 | * @author Jean-Francois Poilpret |
| 28 | */ |
| 29 | public class EmptyFormat extends Format |
| 30 | { |
| 31 | public EmptyFormat(Format format) |
| 32 | { |
| 33 | _format = format; |
| 34 | } |
| 35 | |
| 36 | @Override public StringBuffer format( Object obj, |
| 37 | StringBuffer toAppendTo, |
| 38 | FieldPosition pos) |
| 39 | { |
| 40 | if (obj == null) |
| 41 | { |
| 42 | return toAppendTo; |
| 43 | } |
| 44 | else |
| 45 | { |
| 46 | return _format.format(obj, toAppendTo, pos); |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | @Override public Object parseObject(String source, ParsePosition pos) |
| 51 | { |
| 52 | if (source == null || source.length() == 0) |
| 53 | { |
| 54 | return null; |
| 55 | } |
| 56 | else |
| 57 | { |
| 58 | return _format.parseObject(source, pos); |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | @Override public AttributedCharacterIterator formatToCharacterIterator(Object obj) |
| 63 | { |
| 64 | return _format.formatToCharacterIterator(obj); |
| 65 | } |
| 66 | |
| 67 | @Override public Object parseObject(String source) throws ParseException |
| 68 | { |
| 69 | if (source == null || source.length() == 0) |
| 70 | { |
| 71 | return null; |
| 72 | } |
| 73 | else |
| 74 | { |
| 75 | return _format.parseObject(source); |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | private final Format _format; |
| 80 | } |