001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.gui.widgets; 003 004import javax.swing.text.JTextComponent; 005 006import org.openstreetmap.josm.Main; 007import org.openstreetmap.josm.tools.Utils; 008 009/** 010 * An abstract class for ID text fields. 011 * 012 * @param <T> The ID validator class 013 * @since 5765 014 */ 015public abstract class AbstractIdTextField<T extends AbstractTextComponentValidator> extends JosmTextField { 016 017 protected final T validator; 018 019 /** 020 * Constructs a new {@link AbstractIdTextField} 021 * @param klass The validator class 022 */ 023 public AbstractIdTextField(Class<T> klass) { 024 this(klass, 0); 025 } 026 027 /** 028 * Constructs a new {@link AbstractIdTextField} 029 * @param klass The validator class 030 * @param columns The number of columns to use to calculate the preferred width 031 * @see JosmTextField#JosmTextField(int) 032 */ 033 public AbstractIdTextField(Class<T> klass, int columns) { 034 super(columns); 035 T validator = null; 036 try { 037 if (klass != null) { 038 validator = klass.getConstructor(JTextComponent.class).newInstance(this); 039 } 040 } catch (Exception e) { 041 Main.error(e); 042 } finally { 043 this.validator = validator; 044 } 045 } 046 047 /** 048 * Performs the field validation 049 */ 050 public final void performValidation() { 051 validator.validate(); 052 } 053 054 /** 055 * Clears field if content is invalid 056 */ 057 public final void clearTextIfInvalid() { 058 if (!validator.isValid()) 059 setText(""); 060 validator.validate(); 061 } 062 063 /** 064 * Reads the id(s). 065 * @return true if at least a valid id has been successfully read, false otherwise 066 */ 067 public abstract boolean readIds(); 068 069 /** 070 * Tries to set text from clipboard (no effect with invalid or empty clipboard) 071 */ 072 public void tryToPasteFromClipboard() { 073 tryToPasteFrom(Utils.getClipboardContent()); 074 } 075 076 /** 077 * Tries to set text from given contents (no effect with invalid or empty contents) 078 * @param contents The text to interprete as ID(s) 079 * @return true if text has been pasted and valid ids have been read 080 */ 081 public boolean tryToPasteFrom(String contents) { 082 if (contents != null && !contents.trim().isEmpty()) { 083 setText(contents.trim()); 084 clearTextIfInvalid(); 085 return readIds(); 086 } 087 return false; 088 } 089}