001: /*
002: * Created on 04/12/2005
003: *
004: * ============================================================================
005: * GNU Lesser General Public License
006: * ============================================================================
007: *
008: * Swing Components - visit http://sf.net/projects/gfd
009: *
010: * Copyright (C) 2004 Igor Regis da Silva Simões
011: *
012: * This library is free software; you can redistribute it and/or
013: * modify it under the terms of the GNU Lesser General Public
014: * License as published by the Free Software Foundation; either
015: * version 2.1 of the License, or (at your option) any later version.
016: *
017: * This library is distributed in the hope that it will be useful,
018: * but WITHOUT ANY WARRANTY; without even the implied warranty of
019: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
020: * Lesser General Public License for more details.
021: *
022: * You should have received a copy of the GNU Lesser General Public
023: * License along with this library; if not, write to the Free Software
024: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
025: */
026: package br.com.gfpshare.beans;
027:
028: import java.awt.Color;
029: import java.awt.event.FocusEvent;
030: import java.lang.reflect.InvocationTargetException;
031: import java.lang.reflect.Method;
032:
033: import javax.swing.Icon;
034: import javax.swing.JComponent;
035: import javax.swing.JLabel;
036: import javax.swing.JToolTip;
037:
038: /**
039: * Este é um label que controla a indicação de que o campo para o qual ele ser refere
040: * é um campo requerido
041: * @author Igor Regis da Silva Simoes
042: */
043: public class ZLabel extends JLabel implements RequiredFieldLabel {
044: /**
045: * Indica a cor para alertar ao usuario de que se rtata de um campo requerido
046: * Default RED
047: */
048: private Color requiredColor = new Color(255, 120, 120);
049:
050: /**
051: * Campo reuerido para quem este Label aponta
052: */
053: private RequiredField requiredField;
054:
055: /**
056: * Método usado para validar o campo requerido
057: */
058: private Method method = null;
059:
060: /**
061: * Objeto usado para validar o campo requerido
062: */
063: private Object object;
064:
065: /**
066: * Indica que só será feita validação para verificar se este campo está preenchido
067: */
068: private boolean notNull;
069:
070: /**
071: * Thread que faz os componentes piscarem
072: */
073: private Blink thread = null;
074:
075: /**
076: * Cor original do campo
077: */
078: private Color fieldColor = null;
079:
080: /**
081: * Cor e backgroud do campo requerido
082: */
083: private Color fieldBgColor = null;
084:
085: /**
086: * Indica se esta sendo tratado algum erro de campo com dado inválido
087: */
088: private boolean processandoErro = false;
089:
090: /**
091: * View através da qual são exibidas mensagens ao usuário
092: */
093: private MessageView messageView = null;
094:
095: /**
096: * Cria um novo requiredLabel
097: */
098: public ZLabel() {
099: super ();
100: }
101:
102: /**
103: * Cria um novo requiredLabel usando um messageView para mensagens ao usuário
104: */
105: public ZLabel(MessageView messageView) {
106: super ();
107: setMessageView(messageView);
108: }
109:
110: @Override
111: public void setForeground(Color fg) {
112: super .setForeground(fg);
113: fieldColor = fg;
114: }
115:
116: private void changeColor(Color change) {
117: super .setForeground(change);
118: }
119:
120: /**
121: * Cria um novo requiredLabel
122: * @param image
123: * @param horizontalAlignment
124: */
125: public ZLabel(Icon image, int horizontalAlignment) {
126: super (image, horizontalAlignment);
127: }
128:
129: /**
130: * Cria um novo requiredLabel
131: * @param image
132: */
133: public ZLabel(Icon image) {
134: super (image);
135: }
136:
137: /**
138: * Cria um novo requiredLabel
139: * @param text
140: * @param icon
141: * @param horizontalAlignment
142: */
143: public ZLabel(String text, Icon icon, int horizontalAlignment) {
144: super (text, icon, horizontalAlignment);
145: }
146:
147: /**
148: * Cria um novo requiredLabel
149: * @param text
150: * @param horizontalAlignment
151: */
152: public ZLabel(String text, int horizontalAlignment) {
153: super (text, horizontalAlignment);
154: }
155:
156: /**
157: * Cria um novo requiredLabel
158: * @param text
159: */
160: public ZLabel(String text) {
161: super (text);
162: }
163:
164: /**
165: * Indica se o campo a que se refere este label é requerido
166: */
167: public boolean isRequired() {
168: return method != null || notNull;
169: }
170:
171: public void setRequiredColor(Color cor) {
172: requiredColor = cor;
173: }
174:
175: public Color getRequiredColor() {
176: return requiredColor;
177: }
178:
179: public void setRequiredField(RequiredField requiredField) {
180: if (!(requiredField instanceof JComponent)) {
181: throw new IllegalArgumentException(
182: "RequiredField must be a subclass of JComponent");
183: }
184: fieldBgColor = ((JComponent) requiredField).getBackground();
185: this .requiredField = requiredField;
186: setLabelFor((JComponent) this .requiredField);
187: ((JComponent) this .requiredField).addFocusListener(this );
188: }
189:
190: public void setValidationAction(Object object, String method) {
191: if (object == null) {
192: this .object = null;
193: this .method = null;
194: return;
195: }
196: this .object = object;
197: try {
198: this .method = object.getClass().getMethod(method,
199: new Class[] { Object.class });
200: } catch (SecurityException e) {
201: throw new IllegalArgumentException(
202: "Acesso ao metodo de validação proibido!");
203: } catch (NoSuchMethodException e) {
204: throw new IllegalArgumentException(
205: "O método de validação indicado não existe!");
206: }
207: }
208:
209: public void focusGained(FocusEvent e) {
210: //Não fazemos nada pois se houver erro
211: //vamos puxar o foco automaticamente para nos
212: }
213:
214: public void focusLost(FocusEvent e) {
215: if (requiredField.isSameComponent(e.getOppositeComponent()))
216: return;
217: if (processandoErro)
218: return;
219: processandoErro = true;
220: if (isRequired()) {
221: try {
222: if (notNull) {
223: if (requiredField.getRequiredValue() == null
224: || requiredField.getRequiredValue().equals(
225: ""))
226: throw new NullPointerException(BeansMessages
227: .getMessages().getString(
228: "requiredFieldIsEmpty"));
229: } else {
230: method.invoke(object, new Object[] { requiredField
231: .getRequiredValue() });
232: }
233: } catch (Exception e1) {
234: String msg = e1.getMessage();
235: if (e1 instanceof InvocationTargetException) {
236: msg = e1.getCause().getMessage();
237: }
238: thread = new Blink();
239: thread.start();
240: if (messageView == null) {
241: messageView = new PopupMessageView();
242: setToolTipText(msg);
243: }
244: MessageView temp = messageView.showMessage("", msg,
245: false);
246: temp.getMessagePanel().piscar(true);
247: temp.finishUse(20);
248: }
249: }
250:
251: }
252:
253: /**
254: * Thread responsável por piscar o campo requerido e pintar o label referente a este campo
255: */
256: private class Blink extends Thread {
257: /**
258: * Cria uma nova instancia de blink
259: */
260: public Blink() {
261: super ("BlinkRequiredField");
262: }
263:
264: @Override
265: public void run() {
266: try {
267: for (int i = 0; i < 4; i++) {
268: // ((JComponent)requiredField).setBackground(requiredColor);
269: changeColor(requiredColor);
270: try {
271: Thread.sleep(800);
272: } catch (InterruptedException e) {
273: return;
274: }
275:
276: // ((JComponent)requiredField).setBackground(fieldBgColor);
277: changeColor(fieldColor);
278: try {
279: Thread.sleep(800);
280: } catch (InterruptedException e) {
281: return;
282: }
283: }
284: } catch (Exception e) {
285: //Fazemos nada
286: } finally {
287: // ((JComponent)requiredField).setBackground(fieldBgColor);
288: changeColor(fieldColor);
289: processandoErro = false;
290: }
291: };
292: }
293:
294: public void setValidationNotNull(boolean notNull) {
295: this .notNull = notNull;
296: }
297:
298: public void highlight(boolean highlight) {
299: if (!isRequired())
300: return;
301: if (highlight)
302: changeColor(requiredColor);
303: else
304: changeColor(fieldColor);
305: }
306:
307: /**
308: * Determina a view através da qual serão exibidas as mensagens de alerta ao usuário
309: * @param messageView View usada para exibição de mensagens
310: */
311: public void setMessageView(MessageView messageView) {
312: this .messageView = messageView;
313: }
314:
315: @Override
316: public JToolTip createToolTip() {
317: if (messageView instanceof PopupMessageView) {
318: ((JToolTip) ((PopupMessageView) messageView)
319: .getMessagePanel()).setComponent(this );
320: return (JToolTip) ((PopupMessageView) messageView)
321: .getMessagePanel();
322: }
323: return super.createToolTip();
324: }
325: }
|