Classes in this File | Line Coverage | Branch Coverage | Complexity | ||||
DocumentLengthFilterAvert |
|
| 2.0;2 |
1 | package org.jtheque.utils.ui; | |
2 | ||
3 | /* | |
4 | * This file is part of JTheque. | |
5 | * | |
6 | * JTheque is free software: you can redistribute it and/or modify | |
7 | * it under the terms of the GNU General Public License as published by | |
8 | * the Free Software Foundation, either version 3 of the License. | |
9 | * | |
10 | * JTheque is distributed in the hope that it will be useful, | |
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of | |
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
13 | * GNU General Public License for more details. | |
14 | * | |
15 | * You should have received a copy of the GNU General Public License | |
16 | * along with JTheque. If not, see <http://www.gnu.org/licenses/>. | |
17 | */ | |
18 | ||
19 | import javax.swing.JTextField; | |
20 | import javax.swing.text.AttributeSet; | |
21 | import javax.swing.text.BadLocationException; | |
22 | import javax.swing.text.DocumentFilter; | |
23 | import java.awt.Toolkit; | |
24 | ||
25 | /** | |
26 | * A document filter used to limit the length of a field. This filter avert the user with a popup when he go to | |
27 | * the limit. | |
28 | * | |
29 | * @author Baptiste Wicht | |
30 | */ | |
31 | public final class DocumentLengthFilterAvert extends DocumentLengthFilter { | |
32 | private DisplayPopupThread thread; | |
33 | private final JTextField field; | |
34 | ||
35 | /** | |
36 | * Construct a new <code>DocumentLengthFilterAvert</code> associated with a specific field and with a | |
37 | * maximum number of characters. | |
38 | * | |
39 | * @param max The maximum numbers of characters. | |
40 | * @param field The field we want to associate to fhe filter. | |
41 | */ | |
42 | public DocumentLengthFilterAvert(int max, JTextField field) { | |
43 | 0 | super(max); |
44 | ||
45 | 0 | this.field = field; |
46 | 0 | } |
47 | ||
48 | @Override | |
49 | public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { | |
50 | 0 | replace(fb, offset, length, "", null); |
51 | 0 | } |
52 | ||
53 | @Override | |
54 | public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String str, | |
55 | AttributeSet attrs) throws BadLocationException { | |
56 | 0 | if (str != null) { |
57 | 0 | int newLength = fb.getDocument().getLength() - length + str.length(); |
58 | ||
59 | 0 | if (thread != null) { |
60 | 0 | thread.close(); |
61 | } | |
62 | ||
63 | 0 | if (newLength <= getMax()) { |
64 | 0 | fb.replace(offset, length, str, attrs); |
65 | } else { | |
66 | 0 | Toolkit.getDefaultToolkit().beep(); |
67 | ||
68 | 0 | thread = new DisplayPopupThread(field); |
69 | 0 | thread.start(); |
70 | } | |
71 | } | |
72 | 0 | } |
73 | } |