View Javadoc

1   /*
2    * Copyright 2006-2016 The JGUIraffe Team.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License")
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package net.sf.jguiraffe.gui.platform.swing.builder.components;
17  
18  import javax.swing.text.AttributeSet;
19  import javax.swing.text.BadLocationException;
20  import javax.swing.text.PlainDocument;
21  
22  /**
23   * <p>
24   * An internally used document class for text components with a limited text
25   * length.
26   * </p>
27   * <p>
28   * This document class is initialized with a length parameter. It ensures that
29   * only text with this maximum length can be typed in the corresponding text
30   * component.
31   * </p>
32   *
33   * @author Oliver Heger
34   * @version $Id: SwingLimitedTextModel.java 205 2012-01-29 18:29:57Z oheger $
35   */
36  class SwingLimitedTextModel extends PlainDocument
37  {
38      /**
39       * Serial version UID.
40       */
41      private static final long serialVersionUID = 1L;
42  
43      /** Stores the maximum text length. */
44      private int maximumLength;
45  
46      /**
47       * Creates a new instance of <code>SwingLimitedTextModel</code> and
48       * initializes it with the maximum allowed text length.
49       *
50       * @param maxlen the maximum text length
51       */
52      public SwingLimitedTextModel(int maxlen)
53      {
54          super();
55          maximumLength = maxlen;
56      }
57  
58      /**
59       * Returns the maximum text length.
60       *
61       * @return the maximum text length
62       */
63      public int getMaximumLength()
64      {
65          return maximumLength;
66      }
67  
68      /**
69       * Inserts text into this document. This implementation ensures that the
70       * maximum text length is taken into account.
71       *
72       * @param offset the insert position
73       * @param str the string to insert
74       * @param a attributes
75       * @throws BadLocationException if the position is invalid
76       */
77      public void insertString(int offset, String str, AttributeSet a)
78              throws BadLocationException
79      {
80          if (getLength() + str.length() <= getMaximumLength())
81          {
82              super.insertString(offset, str, a);
83          } /* if */
84      }
85  }