source: josm/trunk/src/org/openstreetmap/josm/gui/widgets/AbstractIdTextField.java@ 5886

Last change on this file since 5886 was 5886, checked in by Don-vip, 11 years ago

see #4429 - Right click menu "undo, cut, copy, paste, delete, select all" for each text component (originally based on patch by NooN)

File size: 2.6 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.widgets;
3
4import javax.swing.text.JTextComponent;
5
6import org.openstreetmap.josm.gui.widgets.JosmTextField;
7import org.openstreetmap.josm.tools.Utils;
8
9/**
10 * An abstract class for ID text fields.
11 *
12 * @param <T> The ID validator class
13 * @since 5765
14 */
15public abstract class AbstractIdTextField<T extends AbstractTextComponentValidator> extends JosmTextField {
16
17 protected final T validator;
18
19 /**
20 * Constructs a new {@link AbstractIdTextField}
21 * @param klass The validator class
22 */
23 public AbstractIdTextField(Class<T> klass) {
24 this(klass, 0);
25 }
26
27 /**
28 * Constructs a new {@link AbstractIdTextField}
29 * @param klass The validator class
30 * @param columns The number of columns to use to calculate the preferred width
31 * @see JTextField#JTextField(int)
32 */
33 public AbstractIdTextField(Class<T> klass, int columns) {
34 super(columns);
35 T validator = null;
36 try {
37 if (klass != null) {
38 validator = klass.getConstructor(JTextComponent.class).newInstance(this);
39 }
40 } catch (Exception e) {
41 System.err.println(e.getClass().getName()+": "+e.getMessage());
42 } finally {
43 this.validator = validator;
44 }
45 }
46
47 /**
48 * Performs the field validation
49 */
50 public final void performValidation() {
51 validator.validate();
52 }
53
54 /**
55 * Clears field if content is invalid
56 */
57 public final void clearTextIfInvalid() {
58 if (!validator.isValid())
59 setText("");
60 validator.validate();
61 }
62
63 /**
64 * Reads the id(s).
65 * @return true if at least a valid id has been successfully read, false otherwise
66 */
67 public abstract boolean readIds();
68
69 /**
70 * Tries to set text from clipboard (no effect with invalid or empty clipboard)
71 */
72 public void tryToPasteFromClipboard() {
73 tryToPasteFrom(Utils.getClipboardContent());
74 }
75
76 /**
77 * Tries to set text from given contents (no effect with invalid or empty contents)
78 * @param contents The text to interprete as ID(s)
79 * @return true if text has been pasted and valid ids have been read
80 */
81 public boolean tryToPasteFrom(String contents) {
82 if (contents != null && !contents.trim().isEmpty()) {
83 setText(contents.trim());
84 clearTextIfInvalid();
85 return readIds();
86 }
87 return false;
88 }
89}
Note: See TracBrowser for help on using the repository browser.