libsimple-validation-java-.orig/ 0000755 0001750 0001750 00000000000 12234612336 015667 5 ustar tony tony libsimple-validation-java-.orig/org/ 0000755 0001750 0001750 00000000000 11654612134 016457 5 ustar tony tony libsimple-validation-java-.orig/org/netbeans/ 0000755 0001750 0001750 00000000000 11654612134 020256 5 ustar tony tony libsimple-validation-java-.orig/org/netbeans/validation/ 0000755 0001750 0001750 00000000000 11654612134 022410 5 ustar tony tony libsimple-validation-java-.orig/org/netbeans/validation/spi/ 0000755 0001750 0001750 00000000000 11654612134 023203 5 ustar tony tony libsimple-validation-java-.orig/org/netbeans/validation/spi/accessibility/ 0000755 0001750 0001750 00000000000 11654612134 026032 5 ustar tony tony ././@LongLink 0000000 0000000 0000000 00000000150 00000000000 011561 L ustar root root libsimple-validation-java-.orig/org/netbeans/validation/spi/accessibility/GlobalValidationCallback.java libsimple-validation-java-.orig/org/netbeans/validation/spi/accessibility/GlobalValidationCallback.j0000644 0001750 0001750 00000004143 11654612134 033037 0 ustar tony tony /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.netbeans.validation.spi.accessibility;
import java.util.Collection;
import org.netbeans.validation.api.Problem;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
/**
*
* @author Tim Boudreau
*/
public abstract class GlobalValidationCallback {
private static final Object LOCK = new Object();
private static GlobalValidationCallback INSTANCE;
static GlobalValidationCallback getDefault() {
synchronized (LOCK) {
if (INSTANCE == null) {
INSTANCE = new ProxyGlobalCallback();
}
}
return INSTANCE;
}
public void onValidationTrigger (Object source, Object triggeringEvent) {
}
public void onValidationFinished (Object source, Object triggeringEvent) {
}
public abstract void onProblem (Object component, Problem problem);
public abstract void onProblemCleared (Object component, Problem problem);
private static final class ProxyGlobalCallback extends GlobalValidationCallback {
private ProxyGlobalCallback() {
}
Collection extends GlobalValidationCallback> registered() {
return Lookup.getDefault().lookupAll(GlobalValidationCallback.class);
}
@Override
public void onProblem(Object component, Problem problem) {
for (GlobalValidationCallback cb : registered()) {
try {
cb.onProblem(component, problem);
} catch (Exception e) {
Exceptions.printStackTrace(e);
}
}
}
@Override
public void onProblemCleared(Object component, Problem problem) {
for (GlobalValidationCallback cb : registered()) {
try {
cb.onProblemCleared(component, problem);
} catch (Exception e) {
Exceptions.printStackTrace(e);
}
}
}
}
}
libsimple-validation-java-.orig/org/netbeans/validation/api/ 0000755 0001750 0001750 00000000000 11654612134 023161 5 ustar tony tony libsimple-validation-java-.orig/org/netbeans/validation/api/Bundle.properties 0000644 0001750 0001750 00000004505 11654612134 026514 0 ustar tony tony # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
#
# Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
#
# The contents of this file are subject to the terms of either the GNU
# General Public License Version 2 only ("GPL") or the Common
# Development and Distribution License("CDDL") (collectively, the
# "License"). You may not use this file except in compliance with the
# License. You can obtain a copy of the License at
# http://www.netbeans.org/cddl-gplv2.html
# or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
# specific language governing permissions and limitations under the
# License. When distributing the software, include this License Header
# Notice in each file and include the License file at
# nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
# particular file as subject to the "Classpath" exception as provided
# by Sun in the GPL Version 2 section of the License file that
# accompanied this code. If applicable, add the following below the
# License Header, with the fields enclosed by brackets [] replaced by
# your own identifying information:
# "Portions Copyrighted [year] [name of copyright owner]"
#
# Contributor(s):
#
# The Original Software is NetBeans. The Initial Developer of the Original
# Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
# Microsystems, Inc. All Rights Reserved.
#
# If you wish your version of this file to be governed by only the CDDL
# or only the GPL Version 2, indicate your decision by adding
# "[Contributor] elects to include this software in this distribution
# under the [CDDL or GPL Version 2] license." If you do not indicate a
# single choice of license, a recipient has the option to distribute
# your version of this file under either the CDDL, the GPL Version 2 or
# to extend the choice of license to its licensees as provided above.
# However, if you add GPL Version 2 code and therefore, elected the GPL
# Version 2 license, then the option applies only if the new code is
# made subject to such option by the copyright holder.
OpenIDE-Module-Name=Validation Ui Api
GENERIC_EMPTY_TEXTFIELD_ERROR={0} not set
INFO=Informational Message
WARNING=Warning Message
FATAL=Fatal Error
INFO.annotation=Informational Message: {0}
WARNING.annotation=Warning Message: {0}
FATAL.annotation=Fatal Error: {0}
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/ 0000755 0001750 0001750 00000000000 11661314136 023575 5 ustar tony tony libsimple-validation-java-.orig/org/netbeans/validation/api/ui/ValidationListener.java 0000644 0001750 0001750 00000013512 11654612134 030243 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui;
import org.netbeans.validation.api.Problem;
import org.netbeans.validation.api.Problems;
/**
* Abstract base class for UI component listeners that can trigger validation when an interesting
* event occurs, and when requested perform validation of the UI component using a {@link org.netbeans.validation.api.Validator}.
*
* Implement whatever UI component listener interface
* is necessary, add it as a listener to the UI component(s) it should listen to, and
* then pass the listener to {@code ValidationGroup.add()}.
*
* When an event that should
* trigger validation occurs, let the listener (the subclass of {@code ValidationListener}) call the
* {@link #performValidation() } method to notfify the simplevalidation infrastructure
* what's going on. The infrastrure will then usually call the {@link #performValidation(org.netbeans.validation.api.Problems) }
* method, in which the the listener (the subclass of {@code ValidationItem})
* should validate the UI-component using a suitable {@link org.netbeans.validation.api.Validator}.
*
* Note that one validation listener may not belong to more than one ValidationGroup.
*
*
* @author Tim Boudreau
* @author Hugo Heden
*/
public abstract class ValidationListener extends ValidationItem implements java.util.EventListener {
private TargetType target;
private final Class targetType;
protected ValidationListener(Class targetType, ValidationUI ui, TargetType component){
super(ui);
this.targetType = targetType;
this.target = component;
}
/**
* Called by subclasses to indicate to the simple-validation infrastructure
* that user has interacted with the UI-component in a way that makes revalidation
* needed.
*
* This will initiate the validation logic (unless the validation is suspended, see
* {@link ValidationItem#runWithValidationSuspended(java.lang.Runnable)}:
* A call to {@link ValidationListener#performValidation(org.netbeans.validation.api.Problems)}
* will occur.
*
* If this results in a {@link Problem}, the {@link ValidationUI}
* managed by this {@code ValidationListener} (such as an error icon
* decorating the UI-component) will be activated, indicating the {@code Problem}
* to the user.
*
* If this ValidationListener is added to a {@link ValidationGroup},
* the latter will update its {@code ValidationUI}:s as well (unless there happens
* to be a more severe {@code Problem} somewhere else within that {@code ValidationGroup})
*/
// protected final void performValidation() { // Intended to be called by subclasses
// super.performValidation();
// }
@Override
final void subtreeRevalidation(){ // Intended to be called by parent ValidationGroup
if (isSuspended()) {
return;
}
Problems ps = new Problems();
this.performValidation(ps);
Problem lead = ps.getLeadProblem();
super.setCurrentLeadProblem(lead);
}
/**
* Called by the simplevalidation infrastructure when it is time to
* perform the validation. The instance of the class subclassing ValidationListener
* should have access to the UI-component to validate, and to a validator, and simply call
* the validator's validate() method with the appropriate arguments.
*
* If the component to be validated is disabled (it is greyed out and can't
* be interacted with) it is usually considered to have no problems.
*/
protected abstract void performValidation(Problems problems);
protected final TargetType getTarget() {
return target;
}
Class targetType() {
return targetType;
}
}
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/ValidationListenerFactory.java 0000644 0001750 0001750 00000026067 11715053270 031602 0 ustar tony tony /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.netbeans.validation.api.ui;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import org.netbeans.validation.api.Validator;
import org.netbeans.validation.api.ValidatorUtils;
import org.openide.util.Lookup;
/**
* Factory for listeners on a particular type of component with a particular
* type of model. Creates listeners which can be attached to one
* component and run validators for the specified model type.
* For example, a validator for the Document of a JTextArea would most likely
* be a Validator<JTextComponent, Document>.
*
* Instances of ValidationListenerFactory for specific component types may
* be declaratively registered in META-INF/services in your JAR (i.e.
* findable via JDK 6's ServiceLoader or NetBeans default Lookup).
*
* The library contains built-in listeners for Swing components, including
* JList, JTextComponent, JComboBox and arrays of AbstractButton. These
* will be found in preference to any registered factories.
*
* @author Tim Boudreau
*/
public abstract class ValidationListenerFactory {
private final Class componentType;
private final Class modelType;
protected ValidationListenerFactory(Class componentType, Class modelType) {
this.componentType = componentType;
this.modelType = modelType;
}
final Class componentType() {
return componentType;
}
final Class modelType() {
return modelType;
}
/**
* Create a ValidationListener for a specific type of component, which accepts
* Validators of a given type. By default, the following combinations are
* supported:
*
* JList + Integer[]
* JList[] + ListSelectionModel
* JTextComponent + Document
* JTextComponent + String
* JComboBox + ComboBoxModel
* JComboBox + String
* AbstractButton[] + ButtonModel[]
* AbstractButton[] + Integer
*
* To register validation listeners for additional types, subclass
* SwingValidationListenerFactory and register it
* in JDK 6's ServiceLoader/NetBeans default Lookup by placing flat
* files in META-INF/services in a JAR on the classpath. Each such
* registered type must also have an annotation of type
* ListenerFor
, so that it can be located correctly.
* Example:
@SwingValidationListenerFactory.ListenerFor(componentType=JColorChooser.class, modelObjectType=Color.class)
public class ColorChooserValidationListenerFactory extends SwingValidationListenerFactory {
@Override
protected ValidationListener createListener(
JColorChooser component, ValidationStrategy strategy,
ValidationUI validationUI, Validator validator) {
//This cast is safe - this method will never be called unless
//the type has first been checked
return new ColorChooserListener(component, validationUI,
(Validator) validator);
}
static final class ColorChooserListener
extends AbstractValidationListener
implements PropertyChangeListener {
ColorChooserListener (JColorChooser comp, ValidationUI ui,
Validator validator) {
super (comp, ui, color);
comp.addPropertyChangeListener("color", this);
}
@Override
protected Color getModelObject(JColorChooser comp) {
return comp.getColor();
}
public void propertyChange(PropertyChangeEvent evt) {
performValidation();
}
}
}
*
* @param The component type.
* @param The type of object the Validator accepts
* @param component A component of CType or a subclass
* @param strategy The validation strategy to use
* @param validationUI A validation UI, typically the component decorator
* @param validator A validator that accepts ModelType arguments
* @return a listener
*/
public static ValidationListener createValidationListener(final CType component, final ValidationStrategy strategy, ValidationUI validationUI, final Validator validator) {
Class modelType = validator.modelType();
ValidationListener result = null;
//If we're really using some other toolkit, avoid loading more Swing
//classes than JComponent
if (component instanceof JComponent || (component.getClass().isArray() && JComponent.class.isAssignableFrom(component.getClass().getComponentType()))) {
result = findBuiltInValidationListener(component, strategy, validationUI, validator);
}
if (result == null) {
@SuppressWarnings("rawtypes")
Collection extends ValidationListenerFactory> registered = Lookup.getDefault().lookupAll(ValidationListenerFactory.class);
if (Object.class.equals(modelType)) {
Logger.getLogger(ValidationListenerFactory.class.getName()).log(
Level.WARNING,
"Bad form to create a Validator: {0}",
validator.getClass().getName());
}
@SuppressWarnings("unchecked") // XXX this code is probably wrong, but have not yet figured out why; probably should accept Class param
Class compType = (Class) component.getClass();
for (ValidationListenerFactory,?> f : registered) {
if (f.componentType().isAssignableFrom(compType)) {
ValidationListenerFactory cast = f.as(compType, modelType, component);
if (cast != null) {
return cast.createListener(component, strategy, validationUI, validator);
}
}
}
}
if (result == null) {
throw new IllegalArgumentException("No registered validator for " +
"components of type " + component.getClass().getName() +
" and validators for objects of type " + modelType);
}
return result;
}
// XXX unchecked warnings: need cast method for ValidationListener
@SuppressWarnings("unchecked")
static ValidationListener findBuiltInValidationListener(final CType component, final ValidationStrategy strategy, ValidationUI validationUI, final Validator validator) {
Class modelType = validator.modelType();
if (component instanceof JList && Integer[].class.equals(modelType)) {
return (ValidationListener) SwingValidationListenerFactories.createJListValidationListenerConverted((JList) component, strategy, validationUI, ValidatorUtils.cast(Integer[].class, validator));
} else if (component instanceof JList && ListSelectionModel.class.isAssignableFrom(modelType)) {
return SwingValidationListenerFactories.createJListValidationListener(JList.class.cast(component), strategy, validationUI, (Validator) validator);
} else if (component instanceof JTextComponent && String.class.equals(modelType)) {
return SwingValidationListenerFactories.createJTextComponentValidationListener(JTextComponent.class.cast(component), strategy, validationUI, (Validator) validator);
} else if (component instanceof JTextComponent && Document.class.isAssignableFrom(modelType)) {
return SwingValidationListenerFactories.createJTextComponentValidationListener(JTextComponent.class.cast(component), strategy, validationUI, (Validator) validator);
} else if (component instanceof JComboBox && String.class.equals(modelType)) {
return SwingValidationListenerFactories.createJComboBoxValidationListener(JComboBox.class.cast(component), strategy, validationUI, (Validator) validator);
} else if (component instanceof JComboBox && ComboBoxModel.class.isAssignableFrom(modelType)) {
return SwingValidationListenerFactories.createJComboBoxValidationListener(JComboBox.class.cast(component), strategy, validationUI, (Validator) validator);
} else if (ButtonModel[].class.equals(modelType) && component.getClass().isArray() && component.getClass().getComponentType().isAssignableFrom(AbstractButton.class)) {
return SwingValidationListenerFactories.createButtonsValidationListener(AbstractButton[].class.cast(component), validationUI, (Validator) validator);
} else if (Integer[].class.equals(modelType) && component.getClass().isArray() && component.getClass().getComponentType().isAssignableFrom(AbstractButton.class)) {
return SwingValidationListenerFactories.createButtonsValidationListener(AbstractButton[].class.cast(component), validationUI, (Validator) validator);
}
return null;
}
protected abstract ValidationListener createListener (final CompType component, final ValidationStrategy strategy, ValidationUI validationUI, final Validator validator);
ValidationListenerFactory as (Class actualCompType, Class actualModelType, T comp) {
return new Cast (actualCompType, actualModelType, comp, this);
}
private static final class Cast extends ValidationListenerFactory {
private final ValidationListenerFactory other;
Cast(Class compType, Class model, CompType comp, ValidationListenerFactory other) {
super (compType, model);
this.other = other;
}
@Override
@SuppressWarnings("unchecked")
protected ValidationListener createListener(CompType component, ValidationStrategy strategy, ValidationUI validationUI, Validator validator) {
T t = other.componentType.cast(component);
Validator v = ValidatorUtils.cast(other.modelType(), validator);
ValidationListener> real = other.createListener(t, strategy, validationUI, v);
return (ValidationListener) real;
}
}
}
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/ValidationStrategy.java 0000644 0001750 0001750 00000005545 11654612134 030267 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui;
/**
* Determines what event on the component will trigger running validation.
* For example, if validation of a text component's content involves expensive
* calculation which could slow down the UI, you may want to use ON_FOCUS_LOSS;
* however ON_CHANGE_OR_ACTION (reacting every time a key is typed) provides
* more satisfactory user experience.
*
* @author Tim Boudreau
*/
public enum ValidationStrategy {
/** Use whatever is generally most appropriate for this component */
DEFAULT,
/** Validate when focus is lost */
ON_FOCUS_LOSS,
/** Validate on a document change or action performed or change event */
ON_CHANGE_OR_ACTION,
/** Validate using JComponent.setInputVerifier */
INPUT_VERIFIER,
}
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/ButtonsValidationListenerImpl.java 0000644 0001750 0001750 00000010352 11654612134 032443 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui;
import java.awt.Color;
import org.netbeans.validation.api.Validator;
import org.netbeans.validation.api.ui.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.JColorChooser;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.netbeans.validation.api.Problems;
/**
* THIS CLASS AND EVERYTHING ELSE IN THIS PACKAGE IS NOT API. DO NOT CALL
* OR INSTANTIATE DIRECTLY.
*
* @author Hugo Heden
*/
class ButtonsValidationListenerImpl extends ValidationListener implements ItemListener, ChangeListener{
private final Validator validator;
private final AbstractButton[] buttons;
public ButtonsValidationListenerImpl(AbstractButton[] buttons, ValidationUI validationUI, Validator validator) {
super(AbstractButton[].class, validationUI, buttons);
this.validator = validator;
this.buttons = buttons;
for (int i = 0; i < buttons.length; i++) {
buttons[i].getModel().addChangeListener(this);
buttons[i].getModel().addItemListener(this);
}
performValidation(); // Make sure any initial errors are discovered immediately.
}
@Override
public void itemStateChanged(ItemEvent e) {
performValidation();
}
@Override
public void stateChanged(ChangeEvent pce) {
performValidation();
}
@Override
protected void performValidation(Problems ps) {
boolean theyreAllDisabled = true;
List selectedButtons = new ArrayList();
for (AbstractButton button : buttons) {
if (button.getModel().isEnabled()) {
theyreAllDisabled = false;
if (button.getModel().isSelected()) {
selectedButtons.add(button.getModel());
}
}
}
if (!theyreAllDisabled) {
validator.validate(ps, null, selectedButtons.toArray(new ButtonModel[selectedButtons.size()]));
}
}
}
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/SwingValidationListenerFactories.java0000644 0001750 0001750 00000037517 11654612134 033126 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui;
import java.awt.EventQueue;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import org.netbeans.validation.api.Validator;
import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import org.netbeans.validation.api.ValidatorUtils;
import org.netbeans.validation.api.conversion.Converter;
import org.netbeans.validation.api.ui.swing.SwingValidationGroup;
/**
* A number of factory methods for creating ValidationListeners handling validation of Swing components.
*
* Note that there are also some convenience methods for creating a ValidationListener
* and directly adding it to a ValidationGroup, see the {@code add} methods in class {@link SwingValidationGroup},
* so the using the methods in this class should often not be necessary.
*
* Note that the factory methods here could be moved to ValidationGroup, however,
* this would cause ValidationGroup to trigger heavier classloading (at least
* if -Xverify:none is not set for the VM).
*
* @author Tim Boudreau
* @author Hugo Heden
*/
final class SwingValidationListenerFactories {
private SwingValidationListenerFactories(){}
/**
* Create a ValidationListener for a JList. The JList will be validated
* with the passed ValidationStrategy
* using the passed Validator
* showing any problems in the passed ValidationUI
*
* Note that there is also a convenience method for creating a ValidationListener
* and directly adding it to a ValidationGroup, see
* {@link SwingValidationGroup#add(javax.swing.JList, org.netbeans.validation.api.Validator[]) }
*
*
*/
static ValidationListener createJListValidationListener(final JList component, final ValidationStrategy strategy, ValidationUI validationUI, final Validator validator) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
return new JListValidationListenerImpl(component, strategy, validationUI, validator);
}
/**
* Create a ValidationListener for a JList. The JList will be validated
* with the passed ValidationStrategy
* using the passed chain of Validator
* showing any problems in the passed ValidationUI
*
* Note that there is also a convenience method for creating a ValidationListener
* and directly adding it to a ValidationGroup, see
* {@link SwingValidationGroup#add(javax.swing.JList, org.netbeans.validation.api.Validator[]) }
*
*/
static ValidationListener createJListValidationListenerConverted(final JList component, final ValidationStrategy strategy, ValidationUI validationUI, final Validator orig) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
final Validator validator = Converter.find(Integer[].class, ListSelectionModel.class).convert(orig);
return new JListValidationListenerImpl(component, strategy, validationUI, validator);
}
/**
* Create a ValidationListener for a JTextComponent (such as JTextField or JTextArea). The JTextComponent will be validated
* with the passed ValidationStrategy
* using the passed Validator
* showing any problems in the passed ValidationUI
*
* Swing {@code Document}s (the model used by JTextComponent)
* are thread-safe, and can be modified from other threads. In
* the case that a text component validator receives an event on
* another thread, validation will be scheduled for later,
* on the event thread.
*
* Note that there is also a convenience method for creating a ValidationListener
* and directly adding it to a ValidationGroup, see
* {@link SwingValidationGroup#add(javax.swing.text.JTextComponent, org.netbeans.validation.api.Validator[]) }
*
*/
static ValidationListener createJTextComponentValidationListener(final JTextComponent comp, final ValidationStrategy strategy, final ValidationUI validationUI, final Validator validator) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
return new JTextComponentValidationListenerImpl(comp, strategy, validationUI, validator);
}
/**
* Create a ValidationListener for a JTextComponent (such as JTextField or JTextArea). The JTextComponent will be validated
* (with ValidationStrategy.DEFAULT)
* using the passed Validator
* showing any problems in the passed ValidationUI
*
* Swing {@code Document}s (the model used by JTextComponent)
* are thread-safe, and can be modified from other threads. In
* the case that a text component validator receives an event on
* another thread, validation will be scheduled for later,
* on the event thread.
*
* Note that there is also a convenience method for creating a ValidationListener
* and directly adding it to a ValidationGroup, see
* {@link SwingValidationGroup#add(javax.swing.text.JTextComponent, org.netbeans.validation.api.Validator[]) }
*
*/
static ValidationListener createJTextComponentValidationListener(final JTextComponent comp, final ValidationUI validationUI, final Validator validator) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
return new JTextComponentValidationListenerImpl(comp, ValidationStrategy.DEFAULT, validationUI, validator);
}
/**
* Create a ValidationListener for a JTextComponent (such as JTextField or JTextArea). The JTextComponent will be validated
* with the passed ValidationStrategy
* using the passed chain of Validator
* showing any problems in the passed ValidationUI
*
* Swing {@code Document}s (the model used by JTextComponent)
* are thread-safe, and can be modified from other threads. In
* the case that a text component validator receives an event on
* another thread, validation will be scheduled for later,
* on the event thread.
*
* Note that there is also a convenience method for creating a ValidationListener
* and directly adding it to a ValidationGroup, see
* {@link SwingValidationGroup#add(javax.swing.text.JTextComponent, org.netbeans.validation.api.Validator[]) }
*
*/
static ValidationListener createJTextComponentValidationListener(final JTextComponent comp, final ValidationStrategy strategy, final ValidationUI validationUI, final Validator... validators) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
final Validator merged = ValidatorUtils.merge(validators);
final Validator validator = Converter.find(String.class, Document.class).convert(merged);
return new JTextComponentValidationListenerImpl(comp, strategy, validationUI, validator);
}
/**
* Create a ValidationListener for a JTextComponent (such as JTextField or JTextArea). The JTextComponent will be validated
* (with ValidationStrategy.DEFAULT)
* using the passed chain of Validator
* showing any problems in the passed ValidationUI
*
* Swing {@code Document}s (the model used by JTextComponent)
* are thread-safe, and can be modified from other threads. In
* the case that a text component validator receives an event on
* another thread, validation will be scheduled for later,
* on the event thread.
*
* Note that there is also a convenience method for creating a ValidationListener
* and directly adding it to a ValidationGroup, see
* {@link SwingValidationGroup#add(javax.swing.text.JTextComponent, org.netbeans.validation.api.Validator[]) }
*
*/
static ValidationListener createJTextComponentValidationListener(final JTextComponent comp, final ValidationUI validationUI, final Validator... validators) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
return createJTextComponentValidationListener(comp, ValidationStrategy.DEFAULT, validationUI, validators);
}
/**
* Create a ValidationListener for a JComboBox. The JComboBox will be validated
* with the passed ValidationStrategy
* using the passed Validator
* showing any problems in the passed ValidationUI
*
* Note that there is also a convenience method for creating a ValidationListener
* and directly adding it to a ValidationGroup, see
* {@link SwingValidationGroup#add(javax.swing.JComboBox, org.netbeans.validation.api.Validator[]) }
*/
static ValidationListener createJComboBoxValidationListener(final JComboBox component, final ValidationStrategy strategy, ValidationUI validationUI, final Validator validator) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
return new JComboBoxValidationListenerImpl(component, strategy, validationUI, validator);
}
/**
* Create a ValidationListener for a JComboBox. The JComboBox will be validated
* (with ValidationStrategy.DEFAULT)
* using the passed Validator
* showing any problems in the passed ValidationUI
*
* Note that there is also a convenience method for creating a ValidationListener
* and directly adding it to a ValidationGroup, see
* {@link SwingValidationGroup#add(javax.swing.JComboBox, org.netbeans.validation.api.Validator[]) }
*/
static ValidationListener createJComboBoxValidationListener(final JComboBox component, ValidationUI validationUI, final Validator validator) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
return new JComboBoxValidationListenerImpl(component, ValidationStrategy.DEFAULT, validationUI, validator);
}
/**
* Create a ValidationListener for a JComboBox. The JComboBox will be validated
* with the passed ValidationStrategy
* using the passed chain of Validator
* showing any problems in the passed ValidationUI
*
* Note that there is also a convenience method for creating a ValidationListener
* and directly adding it to a ValidationGroup, see
* {@link SwingValidationGroup#add(javax.swing.JComboBox, org.netbeans.validation.api.Validator[]) }
*/
static ValidationListener createJComboBoxValidationListener(final JComboBox component, final ValidationStrategy strategy, ValidationUI validationUI, final Validator... validators) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
final Validator merged = ValidatorUtils.merge(validators);
final Validator validator = Converter.find(String.class, ComboBoxModel.class).convert(merged);
return new JComboBoxValidationListenerImpl(component, strategy, validationUI, validator);
}
/**
* Create a ValidationListener for a JComboBox. The JComboBox will be validated
* (with ValidationStrategy.DEFAULT)
* using the passed chain of Validator
* showing any problems in the passed ValidationUI
*
* Note that there is also a convenience method for creating a ValidationListener
* and directly adding it to a ValidationGroup, see
* {@link SwingValidationGroup#add(javax.swing.JComboBox, org.netbeans.validation.api.Validator[]) }
*/
static ValidationListener createJComboBoxValidationListener(final JComboBox component, ValidationUI validationUI, final Validator... validator) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
return createJComboBoxValidationListener(component, ValidationStrategy.DEFAULT, validationUI, validator);
}
/**
* Create a ValidationListener for a AbstractButton[] (such as a number of JCheckBoxes and JRadioButtons). The AbstractButton[] will be validated
* using the passed Validator
* showing any problems in the passed ValidationUI
*
*
* Note that there is also a convenience method for creating a ValidationListener
* and directly adding it to a ValidationGroup, see
* {@link SwingValidationGroup#add(javax.swing.AbstractButton[], org.netbeans.validation.api.Validator[]) }
*/
static ValidationListener createButtonsValidationListener(final AbstractButton[] buttons, ValidationUI validationUI, final Validator validator) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
return new ButtonsValidationListenerImpl(buttons, validationUI, validator);
}
/**
* Create a ValidationListener for a AbstractButton[] (such as a number of JCheckBoxes and JRadioButtons). The AbstractButton[] will be validated
* using the passed chain of Validator
* showing any problems in the passed ValidationUI
*
* Note that there is also a convenience method for creating a ValidationListener
* and directly adding it to a ValidationGroup, see
* {@link SwingValidationGroup#add(javax.swing.AbstractButton[], org.netbeans.validation.api.Validator[]) }
*
*/
static ValidationListener createButtonsValidationListener(final AbstractButton[] buttons, ValidationUI validationUI, final Validator... validators) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
final Validator merged = ValidatorUtils.merge(validators);
final Validator validator = Converter.find(Integer[].class, ButtonModel[].class).convert(merged);
return new ButtonsValidationListenerImpl(buttons, validationUI, validator);
}
}
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/ValidationUI.java 0000644 0001750 0001750 00000007762 11654612134 027005 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui;
import org.netbeans.validation.api.Problem;
/**
* User interface controller which can show the user one problem. This
* could involve showing an icon and some textual info in a status
* bar, and/or disabling some OK-button (if the problem is of {@code
* Severity.FATAL}) etc.
*
* For one {@link ValidationGroup} (a group of UI-components
* validated together), typically one or a few {@code ValidationUI}
* instances might be used, but one instance of {@code ValidationUI}
* should only be used with at most one {@code ValidationGroup} -
* otherwise a new {@code Problem} in one {@code ValidationGroup} will
* hide any {@code Problem}s in others.
*
*
Also, typically a {@code ValidationUI} instance is also used
* for decorating each separate GUI-component that has a Problem. The
* {@link org.netbeans.validation.api.ui.swing.SwingComponentDecorationFactory} is
* a factory class creating such {@code ValidationUI} instances for decorating
* Swing components when there is a validation problem in them.
*
* @author Tim Boudreau
*/
public interface ValidationUI {
/**
* Sets the {@link Problem} to be displayed to the user. Depending on the
* severity of the problem, the user interface may want to block the
* user from continuing until it is fixed (for example, disabling the
* Next button in a wizard or the OK button in a dialog).
* @param problem A problem that the user should be shown, which may
* affect the state of the UI as a whole. Should never be null.
*/
public void showProblem(final Problem problem);
/**
* Clear the problem shown in this UI.
*/
public void clearProblem();
/**
* Access a ValidationUI instance that does nothing.
*/
public static final ValidationUI NO_OP = new ValidationUI(){
@Override
public void showProblem(Problem problem) {}
public void clearProblem() {}
};
}
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/swing/ 0000755 0001750 0001750 00000000000 11661314136 024724 5 ustar tony tony libsimple-validation-java-.orig/org/netbeans/validation/api/ui/swing/ValidationPanel.java 0000644 0001750 0001750 00000027156 11654612134 030655 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui.swing;
import org.netbeans.validation.api.ui.ValidationGroupProvider;
import org.netbeans.validation.api.ui.*;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.KeyboardFocusManager;
import java.awt.LayoutManager;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.netbeans.validation.api.Problem;
import org.openide.util.NbBundle;
/**
* A simple panel which can display a problem, fire changes when the problem
* changes. To use, create your own panel and call setInnerComponent() with it.
* Call getValidationGroup() to add other components to the validation group.
*
* @author Tim Boudreau
*/
public final class ValidationPanel extends JPanel implements ValidationGroupProvider {
private final JComponent problemLabel;
private boolean initialized;
private Problem problem = null;
private final List listeners = Collections.synchronizedList(
new LinkedList());
protected final SwingValidationGroup group;
private final VUI vui = new VUI();
public ValidationPanel (SwingValidationGroup group) {
super(new BorderLayout());
if (group == null) {
group = SwingValidationGroup.create(vui);
} else {
group.addUI(vui);
}
this.group = group;
problemLabel = group.createProblemLabel();
problemLabel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
add(problemLabel, BorderLayout.SOUTH);
initialized = true;
int b = System.getProperty("mrj.version") != null ? 12 : 5;
setBorder(BorderFactory.createEmptyBorder(b,b,b,b));
}
public ValidationPanel() {
this(null);
}
public void setDelegateValidationUI(ValidationUI ui) {
group.addUI(ui);
}
public void removeDelegateValidationUI (ValidationUI ui) {
group.removeUI(ui);
}
private JDialog createDialog() {
Window w = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
if (w == null) {
Frame[] f = Frame.getFrames();
w = f == null || f.length == 0 ? null : f[0];
}
JDialog result;
if (w instanceof Frame) {
result = new JDialog ((Frame) w);
} else if (w instanceof Dialog) {
result = new JDialog ((Dialog) w);
} else {
result = new JDialog();
}
if (w != null) {
result.setLocationRelativeTo(w);
}
return result;
}
public boolean showOkCancelDialog(String title) {
final JDialog dlg = createDialog();
dlg.setModal(true);
dlg.setTitle (title);
JPanel content = new JPanel(new BorderLayout());
content.add(this, BorderLayout.CENTER);
dlg.setContentPane(content);
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.TRAILING));
final JButton ok = new JButton(NbBundle.getMessage(ValidationPanel.class, "OK")); //NOI18N
final JButton cancel = new JButton(NbBundle.getMessage(ValidationPanel.class, "Cancel"));
boolean mac = System.getProperty("mrj.version") != null;
buttons.add(mac ? cancel : ok);
buttons.add(mac ? ok : cancel);
final ValidationUI okButtonEnabler = new ValidationUI(){
public void showProblem(Problem problem) {
if(problem == null || !problem.isFatal()){
ok.setEnabled(true);
} else {
ok.setEnabled(false);
}
}
public void clearProblem() {
showProblem(null);
}
};
group.addUI(okButtonEnabler);
content.add(buttons, BorderLayout.SOUTH);
dlg.getRootPane().getActionMap().put("esc", new AbstractAction(){ //NOI18N
@Override
public void actionPerformed(ActionEvent e) {
cancel.doClick();
}
});
dlg.getRootPane().getInputMap(
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).
put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "esc"); //NOI18N
final boolean[] result = new boolean[1];
ok.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
group.removeUI(okButtonEnabler);
result[0] = true;
dlg.setVisible(false);
dlg.dispose();
}
});
cancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
group.removeUI(okButtonEnabler);
result[0] = false;
dlg.setVisible(false);
dlg.dispose();
}
});
dlg.getRootPane().setDefaultButton(ok);
dlg.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
centerScreen (e.getWindow());
}
public void centerScreen(Window w) {
if (w.getOwner() == null) {
Dimension dim = getToolkit().getScreenSize();
Rectangle abounds = w.getBounds();
w.setLocation((dim.width - abounds.width) / 2,
(dim.height - abounds.height) / 2);
}
}
@Override
public void windowClosing(WindowEvent e) {
cancel.doClick();
}
});
dlg.pack();
dlg.setVisible(true);
return result[0];
}
/**
* Get this panel's built-in validation group, which drives its display
* of error messages. Add an inner panel by calling setInnerComponent(),
* then add your components to that, and add them to the validation group
* using whatever validators you want
* @return The validation group
*/
@Override
public final ValidationGroup getValidationGroup() {
return group;
}
/**
* Overridden to disallow setting the layout manager. Use
* setInnerComponent()
.
* @param mgr
*/
@Override
public final void setLayout(LayoutManager mgr) {
if (initialized) {
throw new IllegalStateException("Use setInnerComponent, do not set" + //NOI18N
" the layout"); //NOI18N
}
super.setLayout(mgr);
}
/**
* Set the inner component which will be displayed above the
* problem label
* @param c The component
*/
public final void setInnerComponent(Component c) {
removeAll();
add(problemLabel, BorderLayout.SOUTH);
add(c, BorderLayout.CENTER);
if (isDisplayable()) {
invalidate();
revalidate();
repaint();
}
}
@Override
protected void addImpl(Component comp, Object constraints, int index) {
super.addImpl(comp, constraints, index);
if (comp instanceof ValidationGroupProvider) {
ValidationGroup g = ((ValidationGroupProvider) comp).getValidationGroup();
group.addItem(g, false);
}
if (comp instanceof ValidationUI) {
ValidationUI theUI = (ValidationUI) comp;
group.addUI(theUI);
}
}
private class VUI implements ValidationUI {
@Override
public final void showProblem(Problem problem){
Problem old = ValidationPanel.this.problem;
ValidationPanel.this.problem = problem;
if ( (old != null && !old.equals(problem)) || (old == null && problem != null) ) {
fireChange();
}
}
public void clearProblem() {
showProblem(null);
}
}
/**
* Get the last reported problem
* @return the problem, or null if there is none
*/
public final Problem getProblem() {
return problem;
}
/**
* Determine if there currently is a fatal problem
* @return true if there is a problem
*/
public final boolean isFatalProblem() {
return problem != null && problem.isFatal();
}
/**
* Add a change listener which will be notified when the problem
* returned by getProblem changes
* @param cl a change listener
*/
public final void addChangeListener(ChangeListener cl) {
listeners.add(cl);
}
/**
* Add a change listener which will be notified when the problem
* returned by getProblem changes
* @param cl a change listener
*/
public final void removeChangeListener(ChangeListener cl) {
listeners.remove(cl);
}
private void fireChange() {
ChangeListener[] cl = listeners.toArray(new ChangeListener[0]);
if (cl.length > 0) {
ChangeEvent e = new ChangeEvent(this);
for (ChangeListener l : cl) {
l.stateChanged(e);
}
}
// doLayout();
}
}
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/swing/Bundle.properties 0000644 0001750 0001750 00000004073 11654612134 030260 0 ustar tony tony # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
#
# Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
#
# The contents of this file are subject to the terms of either the GNU
# General Public License Version 2 only ("GPL") or the Common
# Development and Distribution License("CDDL") (collectively, the
# "License"). You may not use this file except in compliance with the
# License. You can obtain a copy of the License at
# http://www.netbeans.org/cddl-gplv2.html
# or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
# specific language governing permissions and limitations under the
# License. When distributing the software, include this License Header
# Notice in each file and include the License file at
# nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
# particular file as subject to the "Classpath" exception as provided
# by Sun in the GPL Version 2 section of the License file that
# accompanied this code. If applicable, add the following below the
# License Header, with the fields enclosed by brackets [] replaced by
# your own identifying information:
# "Portions Copyrighted [year] [name of copyright owner]"
#
# Contributor(s):
#
# The Original Software is NetBeans. The Initial Developer of the Original
# Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
# Microsystems, Inc. All Rights Reserved.
#
# If you wish your version of this file to be governed by only the CDDL
# or only the GPL Version 2, indicate your decision by adding
# "[Contributor] elects to include this software in this distribution
# under the [CDDL or GPL Version 2] license." If you do not indicate a
# single choice of license, a recipient has the option to distribute
# your version of this file under either the CDDL, the GPL Version 2 or
# to extend the choice of license to its licensees as provided above.
# However, if you add GPL Version 2 code and therefore, elected the GPL
# Version 2 license, then the option applies only if the new code is
# made subject to such option by the copyright holder.
WARNING_LABEL=Warning Label
OK=Ok
Cancel=Cancel
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/swing/SwingValidationGroup.java 0000644 0001750 0001750 00000044006 11654612134 031713 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui.swing;
import java.awt.Component;
import org.netbeans.validation.api.ui.*;
import java.awt.EventQueue;
import java.awt.Point;
import javax.swing.AbstractButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.Popup;
import javax.swing.text.JTextComponent;
import org.netbeans.validation.api.Problem;
import org.netbeans.validation.api.Validator;
import org.netbeans.validation.api.ValidatorUtils;
/**
* {@link ValidationGroup} subclass specialized for handling Swing
* components. This subclass has {@code add}-methods for adding
* GUI-components for common Swing cases. There are also a method for
* getting the {@link SwingComponentDecorationFactory} used by this
* SwingValidationGroup to create decorations for the separate
* GUI-components added to the group. A custom {@code SwingComponentDecorationFactory}
* can be specified when creating the {@code SwingValidationGroup}.
*
* For components this library supports out-of-the-box such as
* JTextField
s or JComboBox
es, simply call
* one of the add()
methods with your component and
* validators. For validating your own components or ones this class
* doesn't have methods for, you implement {@link ValidationListener}s, and add them
* to the {@code ValidationGroup} using the the method
* {@link ValidationGroup#addItem(org.netbeans.validation.api.ui.ValidationItem, boolean) }
*/
public final class SwingValidationGroup extends ValidationGroup {
private final SwingComponentDecorationFactory decorator;
private SwingValidationGroup(GroupValidator additionalGroupValidation, SwingComponentDecorationFactory decorator, ValidationUI... ui) {
super(additionalGroupValidation, ui);
if (ui == null) {
throw new NullPointerException();
}
this.decorator = ( decorator!=null ? decorator : SwingComponentDecorationFactory.getDefault() );
}
public static SwingValidationGroup create(ValidationUI... ui) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
return new SwingValidationGroup(null, null, ui);
}
/**
* Creates a {@code SwingValidationGroup}.
*
* Will use a {@code SwingComponentDecorationFactory} returned by {@link SwingComponentDecorationFactory#getDefault() } to modify the appearance of
* subsequently added components (to show that there is a problem with a
* component's content). To instead use a custom {@code SwingComponentDecorationFactory}, call
* {@link #create(org.netbeans.validation.api.ui.GroupValidator, org.netbeans.validation.api.ui.swing.SwingComponentDecorationFactory, org.netbeans.validation.api.ui.ValidationUI[]) }
*
* @param ui Zero or more {@code ValidationUI}:s. Will be used by the {@code SwingValidationGroup} to show the leading problem (if any)
*/
public static SwingValidationGroup create(GroupValidator additionalGroupValidation, ValidationUI... ui) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
return new SwingValidationGroup(additionalGroupValidation, null, ui);
}
/**
* Creates a {@code SwingValidationGroup}.
* @param additionalGroupValidation may be null
* @param ui Zero or more {@code ValidationUI}:s. Will all be used by the
* {@code SwingValidationGroup} to show the leading problem (if any)
* @param decorator A decorator to be used to modify the appearance of
* subsequently added components (to show that there is a problem with a
* component's content).
*/
public static SwingValidationGroup create(GroupValidator additionalGroupValidation, SwingComponentDecorationFactory decorator, ValidationUI... ui) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
return new SwingValidationGroup(additionalGroupValidation, decorator, ui);
}
/**
* Gets the currently set component decorator used to modify
* components appearance (to show that there is a problem with a
* component's content).
* @return decorator A decorator. May not be null.
*/
final SwingComponentDecorationFactory getComponentDecorationFactory() {
return decorator;
}
@Override
protected final ValidationUI decorationFor (T comp) {
ValidationUI dec = comp instanceof JComponent ?
this.getComponentDecorationFactory().decorationFor((JComponent) comp) :
ValidationUI.NO_OP;
return dec;
}
/**
* Add a text component to be validated using the passed validators.
*
* When a problem occurs, the created ValidationListener will
* use a {@link ValidationUI} created by this {@code ValidationGroup} to decorate
* the component.
*
*
Note: All methods in this class must be called from
* the AWT Event Dispatch thread, or assertion errors will be
* thrown. Manipulating components on other threads is not safe.
*
*
Swing {@code Document}s (the model used by JTextComponent)
* are thread-safe, and can be modified from other threads. In
* the case that a text component validator receives an event on
* another thread, validation will be scheduled for later,
* on the event thread.
*
* @param comp A text component such as a JTextField
* @param validators One or more Validators
*/
public final void add(JTextComponent comp, Validator... validators) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
assert validators.length > 0 : "Empty validator array";
Validator merged = ValidatorUtils.merge(validators);
ValidationListener vl = ValidationListenerFactory.createValidationListener(comp,
ValidationStrategy.DEFAULT,
this.getComponentDecorationFactory().decorationFor(comp),
merged);
this.addItem (vl, false);
}
/**
* Add a text component to be validated using the passed validator.
*
* When a problem occurs, the created ValidationListener will
* use a {@link ValidationUI} created by this {@code ValidationGroup} to decorate
* the component.
*
*
Note: All methods in this class must be called from
* the AWT Event Dispatch thread, or assertion errors will be
* thrown. Manipulating components on other threads is not safe.
*
*
Swing {@code Document}s (the model used by JTextComponent)
* are thread-safe, and can be modified from other threads. In
* the case that a text component validator receives an event on
* another thread, validation will be scheduled for later,
* on the event thread.
*
Unlike {@link #add(JTextComponent,Validator...)}, calling this method does not trigger warnings under {@code -Xlint:unchecked}.
* If you wish to add more than one validator, simply add the result of {@link ValidatorUtils#merge(Validator,Validator)}.
* @param comp A text component such as a JTextField
* @param validator a validator
*/
public final void add(JTextComponent comp, Validator validator) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
ValidationListener vl = ValidationListenerFactory.createValidationListener(comp,
ValidationStrategy.DEFAULT,
this.getComponentDecorationFactory().decorationFor(comp),
validator);
this.addItem (vl, false);
}
/**
* Add a combo box to be validated using the passed validators
*
* When a problem occurs, the created {@link ValidationListener} will
* use a {@link ValidationUI} created by this {@code ValidationGroup} to decorate
* the component.
*
*
Note: All methods in this class must be called from
* the AWT Event Dispatch thread, or assertion errors will be
* thrown. Manipulating components on other threads is not safe.
*
* @param box A combo box component
* @param validators One or more Validators
*/
public final void add(JComboBox box, Validator... validators) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
this.addItem(ValidationListenerFactory.createValidationListener(box, ValidationStrategy.DEFAULT, ValidationUI.NO_OP, ValidatorUtils.merge(validators)), false);
}
/**
* Add a combo box to be validated using the passed validator.
*
* When a problem occurs, the created {@link ValidationListener} will
* use a {@link ValidationUI} created by this {@code ValidationGroup} to decorate
* the component.
*
*
Note: All methods in this class must be called from
* the AWT Event Dispatch thread, or assertion errors will be
* thrown. Manipulating components on other threads is not safe.
*
Unlike {@link #add(JComboBox,Validator...)}, calling this method does not trigger warnings under {@code -Xlint:unchecked}.
* If you wish to add more than one validator, simply add the result of {@link ValidatorUtils#merge(Validator,Validator)}.
* @param box A combo box component
* @param validator a validator
*/
public final void add(JComboBox box, Validator validator) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
this.addItem(ValidationListenerFactory.createValidationListener(box, ValidationStrategy.DEFAULT, ValidationUI.NO_OP, validator), false);
}
/**
* Add a JList to be validated using the passed validators
*
* When a problem occurs, the created {@link ValidationListener} will
* use a {@link ValidationUI} created by this {@code ValidationGroup} to decorate
* the component.
*
*
Note: All methods in this class must be called from
* the AWT Event Dispatch thread, or assertion errors will be
* thrown. Manipulating components on other threads is not safe.
*
* @param list A JList component
* @param validators One or more Validators
*/
public final void add(JList list, Validator... validators) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
this.addItem(ValidationListenerFactory.createValidationListener(list, ValidationStrategy.DEFAULT, this.getComponentDecorationFactory().decorationFor(list), ValidatorUtils.merge(validators)), false);
}
/**
* Add a JList to be validated using the passed validator.
*
* When a problem occurs, the created {@link ValidationListener} will
* use a {@link ValidationUI} created by this {@code ValidationGroup} to decorate
* the component.
*
*
Note: All methods in this class must be called from
* the AWT Event Dispatch thread, or assertion errors will be
* thrown. Manipulating components on other threads is not safe.
*
Unlike {@link #add(JList,Validator...)}, calling this method does not trigger warnings under {@code -Xlint:unchecked}.
* If you wish to add more than one validator, simply add the result of {@link ValidatorUtils#merge(Validator,Validator)}.
* @param list A JList component
* @param validator a validator
*/
public final void add(JList list, Validator validator) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
this.addItem(ValidationListenerFactory.createValidationListener(list, ValidationStrategy.DEFAULT, this.getComponentDecorationFactory().decorationFor(list), validator), false);
}
/**
* Add a validator of button models - typically to see if any are selected.
*
* Note: All methods in this class must be called from
* the AWT Event Dispatch thread, or assertion errors will be
* thrown. Manipulating components on other threads is not safe.
*
* @param buttons The buttons
* @param validators A number of Validators
*/
public final void add(final AbstractButton[] buttons, Validator... validators) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
this.addItem(ValidationListenerFactory.createValidationListener(buttons, ValidationStrategy.DEFAULT, ValidationUI.NO_OP, ValidatorUtils.merge(validators)), false);
}
/**
* Add a validator of button models - typically to see if any are selected.
*
* Note: All methods in this class must be called from
* the AWT Event Dispatch thread, or assertion errors will be
* thrown. Manipulating components on other threads is not safe.
*
Unlike {@link #add(AbstractButton[],Validator...)}, calling this method does not trigger warnings under {@code -Xlint:unchecked}.
* If you wish to add more than one validator, simply add the result of {@link ValidatorUtils#merge(Validator,Validator)}.
* @param buttons The buttons
* @param validator a validator
*/
public final void add(final AbstractButton[] buttons, Validator validator) {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
this.addItem(ValidationListenerFactory.createValidationListener(buttons, ValidationStrategy.DEFAULT, ValidationUI.NO_OP, validator), false);
}
/**
* Create a label which will show the current problem if any, which
* can be added to a panel that uses validation
*
* @return A JLabel
*/
public final JComponent createProblemLabel() {
assert EventQueue.isDispatchThread() : "Must be called on event thread";
final MultilineLabel result = new MultilineLabel();
addUI(result.createUI());
return result;
}
/**
* Create a Popup which can be shown over a component to display what the
* problem is. The resulting popup will be word-wrapped and effort will be
* made to ensure it fits on-screen in the case of lengthy error messages.
*
* @param problem The problem to show
* @param target The target component
* @param relativeLocation The coordinates where the popup should appear,
* in the coordinate space of the target component, not the screen .
* @return A popup. Generally, use the returned popup once and get a new
* one if you want to show a message again. The returned popup will take
* care of hiding itself on component hierarchy changes.
*/
static Popup createProblemPopup (Problem problem, Component target, Point relativeLocation) {
return MultilineLabelUI.showPopup(problem, target, relativeLocation.x, relativeLocation.y);
}
/**
* Client property which can be set to provide a component's name
* for use in validation messages. If not set, the component's
* getName()
method is used.
*/
private static final String CLIENT_PROP_NAME = "_name";
/**
* Get a string name for a component using the following strategy:
*
* Check jc.getClientProperty(CLIENT_PROP_NAME)
* If that returned null, call jc.getName()
*
* @param jc The component
* @return its name, if any, or null
*/
public static String nameForComponent(JComponent jc) {
String result = (String) jc.getClientProperty(CLIENT_PROP_NAME);
if (result == null) {
result = jc.getName();
}
return result;
}
public static void setComponentName(JComponent comp, String localizedName) {
comp.putClientProperty (CLIENT_PROP_NAME, localizedName);
}
}
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/swing/MultilineLabel.java 0000644 0001750 0001750 00000014355 11654612134 030502 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui.swing;
import java.awt.Dimension;
import java.lang.ref.WeakReference;
import javax.swing.JLabel;
import javax.swing.ToolTipManager;
import org.netbeans.validation.api.Problem;
import org.netbeans.validation.api.ui.ValidationUI;
import org.openide.util.NbBundle;
/**
* Label which uses a fixed height based on its icon and text. Uses
* multiline label UI to render multi-line text
*
* @author Tim Boudreau
*/
final class MultilineLabel extends JLabel {
private final boolean isPopup;
MultilineLabel() {
this(false);
}
MultilineLabel(boolean isPopup) {
this.isPopup = isPopup;
}
boolean isPopup() {
return isPopup;
}
@Override
public void updateUI() {
setUI (new MultilineLabelUI());
}
private int tallest = Integer.MIN_VALUE;
@Override
public Dimension getPreferredSize() {
Dimension result = super.getPreferredSize();
if (!isPopup && !isPreferredSizeSet()) {
if (tallest < result.height) {
tallest = result.height;
}
result.height = tallest;
}
return result;
}
private int knownWidth = -1;
@Override
@SuppressWarnings("deprecation")
public void reshape(int x, int y, int w, int h) {
//May be deprecated, but AWT will call it internally - this is the
//place to intercept size changes other than a listener
if (!isPopup) {
if (w != knownWidth) {
knownWidth = w;
tallest = Integer.MIN_VALUE;
}
}
super.reshape(x, y, w, h);
}
@Override
public void addNotify() {
super.addNotify();
if (!isPopup) {
ToolTipManager.sharedInstance().registerComponent(this);
}
}
@Override
public void removeNotify() {
super.removeNotify();
if (!isPopup) {
ToolTipManager.sharedInstance().unregisterComponent(this);
}
}
@Override
public String getToolTipText() {
String s = getText();
if (s != null && !"".equals(s.trim())) {
return htmlize(s);
}
return super.getToolTipText();
}
private static String htmlize(String s) {
StringBuilder res = new StringBuilder("");
String[] words = s.split(" ");
boolean newline = false;
int ct = 0;
for (String word : words) {
ct += word.length();
newline = ct > 80;
if(newline) {
res.append (" ");
ct = 0;
}
res.append(word);
res.append(' ');
}
return res.toString();
}
ValidationUI createUI() {
return new LblUI(this);
}
private static final class LblUI implements ValidationUI {
//Don't allow the group to hold a reference to the label permanetly
private final WeakReference label;
LblUI(JLabel lbl) {
assert lbl != null;
this.label = new WeakReference(lbl);
}
@Override
public void showProblem(Problem problem) {
JLabel lbl = label.get();
if (lbl != null) {
if (problem == null) {
lbl.setText(" ");
lbl.setIcon(null);
lbl.getAccessibleContext().setAccessibleName(
NbBundle.getMessage(MultilineLabel.class,
"WARNING_LABEL"));
lbl.getAccessibleContext().setAccessibleDescription("");
} else {
lbl.setText(problem.getMessage());
lbl.setIcon(problem.severity().icon());
lbl.setForeground(problem.severity().color());
lbl.getAccessibleContext().setAccessibleName(
problem.severity().toString());
lbl.getAccessibleContext().setAccessibleDescription(
problem.severity().describeError(problem.getMessage()));
}
}
}
public void clearProblem() {
showProblem(null);
}
}
}
././@LongLink 0000000 0000000 0000000 00000000152 00000000000 011563 L ustar root root libsimple-validation-java-.orig/org/netbeans/validation/api/ui/swing/SwingComponentDecorationFactory.java libsimple-validation-java-.orig/org/netbeans/validation/api/ui/swing/SwingComponentDecorationFactory0000644 0001750 0001750 00000015737 11654612134 033177 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui.swing;
import org.netbeans.validation.api.ui.*;
import org.openide.util.Lookup;
import javax.swing.JComponent;
/**
* Factory class for creating {@link ValidationUI} instances that can decorate
* a Swing GUI-component when it has a Problem.
*
* By default, one instance of a class implementing this interface
* is used to create a
* ValidationUI for all components handled by the simplevalidation
* framework. This instance can be replaced with a custom one, as
* described below.
*
* For custom decoration, simply pass a different
* decorator factory in ValidationGroup.add() (and if necessary, proxy the
* default decorator factory for all but some specific kind of component).
*
* A rudimentary example of writing a component decorator: The code and
* description below show how to replace the default
* SwingComponentDecorationFactory with one that will create {@code ValidationUI}
* instances that draws a thick colored border around the component
* when there is an error.
*
*
{@code
* package com.foo.myapp;
* public class MySwingComponentDecorationFactory extends SwingComponentDecorationFactory {
* public ValidationUI decorationFor(final JComponent c) {
* return new ValidationUI() {
* private javax.swing.border.Border origBorder = c.getBorder();
* public void showProblem(Problem problem) {
* if( problem == null ) {
* c.setBorder(origBorder);
* } else {
* c.setBorder(javax.swing.BorderFactory.createLineBorder(problem.severity().color(), 3));
* }
* }
* };
* }
* };
* }
*
* Our MySwingComponentDecorationFactory
is then registered so that
* it can be found using JDK 6's ServiceLoader
(or NetBeans'
* Lookup
): Create a file named org.netbeans.validation.api.ui.swing.SwingComponentDecorationFactory
* in the folder META-INF/services
in your source root (so that
* it will be included in the JAR file). Add one line of text to this file -
* the fully qualified name of your class, e.g.
*
* com.foo.myapp.MySwingComponentDecorationFactory
*
*
* @author Tim Boudreau
* @author Hugo Heden
*/
public abstract class SwingComponentDecorationFactory {
private static SwingComponentDecorationFactory componentDecorator =
new SimpleDefaultDecorator();
private static final SwingComponentDecorationFactory noOpDecorationFactory = new SwingComponentDecorationFactory() {
@Override
public ValidationUI decorationFor(JComponent c) {
return ValidationUI.NO_OP;
}
};
/**
*
* Special decorator that does not decorate at all -- even if
* there is a problem -- a "null" decorator. This is useful if no
* component decorations are desired. For example application
* wide:
*
* {@code
* SwingComponentDecorationFactory.set(SwingComponentDecorationFactory.getNoOpDecorationFactory());
* }
* Or just for one specific group of components, here a SwingValidationGroup:
* {@code
* SwingValidationGroup group = SwingValidationGroup.create(SwingComponentDecorationFactory.getNoOpDecorationFactory());
* }
*
*
*/
public static final SwingComponentDecorationFactory getNoOpDecorationFactory() {
return noOpDecorationFactory;
}
/**
* Factory method that creates a {@code ValidationUI} visually attached to
* the Swing GUI-component when there is a {@code Problem}. When a
* {@code Problem} occurs in a component, this {@code ValidationUI} needs to be
* updated using {@link ValidationUI#showProblem} (this is
* typically done from within a {@code ValidationListener}) and
* will then apply some visual mark to the component. When the
* problem disappears, {@code ValidationListener} will pass {@code
* null} to {@code ValidationUI#showProblem},
* which makes sure that the visual cue is removed, so that the
* components is restored to its original visual state.
*
* @param c The component
* @return A ValidationUI, visually attached to the component.
*/
public abstract ValidationUI decorationFor(JComponent c);
/**
*
* Get the current application wide component decorator
*/
public static final SwingComponentDecorationFactory getDefault() {
SwingComponentDecorationFactory result = Lookup.getDefault().lookup(SwingComponentDecorationFactory.class);
if (result == null) {
result = componentDecorator;
}
return result;
}
}
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/swing/AbstractValidationListener.java0000644 0001750 0001750 00000011410 11654612134 033051 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui.swing;
import javax.swing.JComponent;
import org.netbeans.validation.api.Problem;
import org.netbeans.validation.api.Problems;
import org.netbeans.validation.api.Validator;
import org.netbeans.validation.api.ui.ValidationListener;
import org.netbeans.validation.api.ui.ValidationUI;
/**
* Base class for ValidationListeners.
*
* @author Tim Boudreau
*/
public abstract class AbstractValidationListener
extends ValidationListener {
private final Validator validator;
/**
* Create a new AbstractValidationListener for the single component
* passed here as an argument. If the component is not expected to
* live after the validator is detached, you can add this object as a
* listener to the component in the constructor (but remember that
* this means the component will reference this validator forever).
* @param comp
*/
public AbstractValidationListener(Class type, CompType comp, ValidationUI ui, Validator validator) {
super(type, ui, comp);
this.validator = validator;
}
/**
* Get the name of the component which should be passed to
* validate. The default implementation delegates to
* nameForComponent
which will either return the
* client-property based name or the result of getName() on
* the component.
*
* @param comp The component
* @return A localized name
*/
protected String findComponentName (CompType comp) {
return SwingValidationGroup.nameForComponent(comp);
}
/**
* Get the model object that will be passed to validate
* @param comp The component
* @return The model object
*/
protected abstract T getModelObject(CompType comp);
/**
* Called when validation runs. The default implementation does nothing;
* some validators may want to change the visual appearance of the component
* to indicate an error.
*
* @param component The component
* @param validationResult The result of validation
*/
protected void onValidate(CompType component, Problem validationResult){}
@Override
protected final void performValidation(Problems ps) {
CompType comp = getTarget();
if (!comp.isEnabled()) {
return;
}
Problems problems = new Problems();
validator.validate(problems, SwingValidationGroup.nameForComponent(comp),
getModelObject(comp)); //XXX generics quirk
onValidate(getTarget(), problems.getLeadProblem());
}
}
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/swing/SimpleDefaultDecorator.java 0000644 0001750 0001750 00000072164 11654612134 032203 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui.swing;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.HierarchyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JToolTip;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.HierarchyListener;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.RGBImageFilter;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.UIManager;
import org.netbeans.validation.api.Problem;
import org.netbeans.validation.api.Severity;
import org.netbeans.validation.api.ui.ValidationUI;
/**
* Default decorator class provided by simplevalidation.
*
* By default, one instance of this class is used to decorate all
* components validated by simplevalidation in the application. This
* instance can be replaced with a custom one, see {@link
* SwingComponentDecorationFactory}. Either a completely different {@code
* SwingComponentDecorationFactory} class or an instance of a class deriving
* from {@code SimpleDefaultDecorator} , overriding one or more of
* the protected methods.
*
*
{@code SimpleDefaultDecorator} adds an problem icon to the
* decorated component when there is a problem in it. The icon is
* added using the {@code JLayeredPane} mechanism in Swing, so that
* ends up "over" the decorated component (it partly covers the
* decorated component). {@code JLayeredPane} gives us the freedom to
* place the icon outside of the bounding rectangle of the decorated
* component. The exakt location of the icon can be customized by
* deriving from this class and overriding the {@code
* getDecorationLocation} method.
*
*
{@code SimpleDefaultDecorator} also provides with some toolTip
* management: The toolTip owned by the decoration icon is updated
* live if it happens to be visible when the problem changes (and the
* tooltip disappears if the problem disappears). The content of the
* tooltip is a JLabel, by default showing the {@code icon()} of the
* {@link Severity} of the current problem together with the problem
* message, in suitable colors. This can be overridden by deriving
* classes.
*
*
A customization example would be the following, which makes the
* icons a little bit bigger than the default, and the colors a little
* bit stronger.
*
*
{@code
* SwingComponentDecorationFactory.set(new SimpleDefaultDecorator(){
* protected Color getComponentOverlayColor(Severity s, JComponent decoratedComponent){
* if(s == Severity.INFO) {
* return null; // Skip the gray background for INFO
* }
* int alpha = 26; // Corresponds to 0.10f -- rather strong actually
* return new Color(s.color().getRed(), s.color().getGreen(), s.color().getBlue(), alpha);
* }
*
* protected Point getDecorationLocation(Severity s, JComponent decoratedComponent, Dimension decorationIconSize) {
* return new Point( decoratedComponent.getWidth() - (int)(0.6*decorationIconSize.width), -2);
* }
*
* protected Image getDecorationImage(Severity severity, JComponent decoratedComponent) {
* return severity.image(); // bigger than the small severity.badge() -- a bit too big actually, will need to be scaled down
* }
*
* protected Double getDecorationImageScaling(Severity s, JComponent decoratedComponent) {
* if (s == Severity.FATAL) {
* // Scale down the FATAL image a bit more
* return 0.75;
* }
* return 0.85;
* }
*
* protected Integer getDecorationOverlapTransparency(Severity s, JComponent decoratedComponent) {
* if (s == Severity.WARNING) {
* // Not much transparency for warning icon, which has a light color.
* return 0xAA;
* }
* return 0x77;
* }
*});
* }
*
* @author Tim Boudreau
* @author Hugo Heden
*/
final class SimpleDefaultDecorator extends SwingComponentDecorationFactory {
private Icon fatalIconTransp = null;
private Icon warningIconTransp = null;
private Icon infoIconTransp = null;
@Override
public ValidationUI decorationFor(JComponent c) {
return new ToolTippedIconLabel(c, this);
}
/**
* A problem has occured in a component, and this method the a way
* to specify what the tooltip owned by the decoration icon
* should contain from now on (until another problem occurs in
* this component)
*
* If no toolTip is desired, this method should just return
* false.
*
*
Otherwise, the toolTip will contain the JLabel passed to
* this method. An example implementation would be the following.
*
*
{@code
* ttLabel.setText(problem.getMessage());
* return true;
* }
*
* or perhaps (adjusting the ttLabel configured by the super
* class):
*
* {@code
* super.configureToolTipLabel(problem, decoratedComponent, ttLabel);
* ttLabel.setIcon(null);
* return true;
* }
*
*
* @param problem The problem that has occured.
* @param decoratedComponent The component in which the problem has occured.
* @param ttLabel label that will be contained within the tooltip
* @return false if no toolTip is to be shown at all , true otherwise
*/
protected boolean configureToolTipLabel(Problem problem, JComponent decoratedComponent, JLabel ttLabel){
// No good: color transparent, stuff "under" toolTip may leak through (the color chooser in ValidationDemo does so)
// ttLabel.setBackground(this.getComponentOverlayColor(problem.severity(), decoratedComponent));
//TDB: Try for JDK default theme if available
Color bg = UIManager.getColor("white");
//But may not be available on, e.g., GTK look and feel
ttLabel.setBackground(bg == null ? Color.WHITE : bg);
// The following works well, but creates garbage -- a new Border for every new Problem that occurs:
// ttLabel.setBorder(new ColorizingBorder(decoratedComponent, this));
ttLabel.setOpaque(true);
ttLabel.setIcon(problem.severity().icon());
ttLabel.setForeground(problem.severity().color());
Border b = BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(problem.severity().color(), 1),
BorderFactory.createMatteBorder(3, 3, 3, 3, bg));
ttLabel.setBorder(b);
ttLabel.setText(problem.getMessage());
return true;
}
/**
* A {@code Color} with which to paint over the decorated
* component -- a color overlay. The whole bounding rectangle of
* the component will be filled. It is recommended to make this
* color transparent to a high degree, or else the content of the
* decorated component will be hidden by the painted color. If
* the returned Color is null, the component will not get any
* color overlay.
*
*
* @param s The {@code Severity} of the problem the component is to be decorated for.
* @param decoratedComponent The component to be decorated
* @return A {@code Color} to be painted over the bounding rectangle over the component,
* or null if nothing is to be painted.
*/
protected Color getComponentOverlayColor(Severity s, JComponent decoratedComponent) {
int alpha = 13; // Corresponds to alpha of 0.05f [(int)(0.05*255+0.5) == 13]
return new Color(s.color().getRed(), s.color().getGreen(), s.color().getBlue(), alpha);
}
/**
* Specifies where the decorative icon is to be drawn, expressed
* in the coordinate system of the decoratedComponent. The
* decoration does not need to be drawn inside of the component
* bounds -- for example negative numbers are ok.
*
* For example, to have the top left corner of the icon
* located at the top left corner of the decorated component:
* {@code return new Point(0, 0); }
*
*
Or, to have the bottom right corner of the icon located at
* the top right corner of the decoratedComponent: {@code return
* new
* Point(decoratedComponent.getWidth()-decorationIconSize.width,
* -decorationIconSize.height); }
*
*
* @param s The Severity for which the returned decoration location is intended
* @param decorationIconSize Size of the decoration icon
* @param decoratedComponent Component to be decorated
* @return Location of the upper left corner of the icon, expressed in the decoratedComponent
* coordinate system.
*/
protected Point getDecorationLocation(Severity s, JComponent decoratedComponent, Dimension decorationIconSize) {
return new Point(decoratedComponent.getWidth() - decorationIconSize.width + 2, -2);
}
/**
* Specifies an {@code Image} to be used for the decorative icon. Would
* typically return {@code severity.image()} or {@code severity.badge()},
* but any custom image would of course be possible to use. The methods
* {@code getDecorationImageScaling} and
* {@code getDecorationOverlapTransparency} are used to process this image
* somewhat before rendering,
* @param severity The {@code Severity} for which this image is to be used.
* @param decoratedComponent {@code Component} to be decorated
* @return An {@code Image} with which to decorate the component, or null
* if no Icon is to be shown for this severity and/or decoratedComponent
*
*/
protected Image getDecorationImage(Severity severity, JComponent decoratedComponent) {
return severity.badge();
}
/**
* Specifies a scaling to apply to the icon returned by {@code
* getDecorationImage} before rendering it.
*
* @param s The severity for which this scaling will apply
* @param decoratedComponent The component being decorated
* @return A Double representing a positive number, or null if no scaling should be applied.
*/
protected Double getDecorationImageScaling(Severity s, JComponent decoratedComponent) {
return null;
}
/**
* Specifies a transparency to apply to the icon returned by
* {@code getDecorationImage} before rendering it. This
* transparency will only be applied to the part of the icon that
* overlaps/covers the decorated component .
*
*
The alpha value defines the transparency of a color and can
* be represented 0 - 255. An alpha value of 255 means that the
* color is completely opaque and an alpha value of 0 means that
* the color is completely transparent.
*
* @param s The severity for which this transparency will apply
* @param decoratedComponent The component being decorated
* @return An Integer representing a positive number between 0 and 255, or null if no transparency should be applied.
*/
protected Integer getDecorationOverlapTransparency(Severity s, JComponent decoratedComponent) {
return null;
}
/**
* Creates/gets a version of the Icon returned by {@code
* getDecorationImage} (for this severity and decoratedComponent)
* that has been scaled and made transparent according to what is
* returned by {@code getDecorationImageScaling} and {@code
* getDecorationOverlapTransparency}
*
*
Method is intended to be called internally from the {@code
* SimpleDefaultDecorator} infrastructure.
*
* @param severity The {@code Severity} for which this icon is to be applied
* @param decoratedComponent
* @return
*/
Icon getDecorationIcon(Severity severity, final JComponent decoratedComponent) {
// "singletons", only created once.
if (severity.equals(Severity.FATAL) && fatalIconTransp != null) {
return fatalIconTransp;
}
if (severity.equals(Severity.WARNING) && warningIconTransp != null) {
return warningIconTransp;
}
if (severity.equals(Severity.INFO) && infoIconTransp != null) {
return infoIconTransp;
}
Image image = getDecorationImage(severity, decoratedComponent);
if (image == null) {
return null;
}
ImageIcon icon = new ImageIcon(image);
Double scaling = getDecorationImageScaling(severity, decoratedComponent);
if (scaling != null) {
int scaledWidth = (int) (scaling * icon.getIconWidth());
int scaledHeight = (int) (scaling * icon.getIconHeight());
BufferedImage scaledImg =
new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = scaledImg.createGraphics();
// TODO: Better rescaling if downscaling? See code example on
// http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC); // Slowest but with highest quality
g2.drawImage(image, 0, 0, scaledWidth, scaledHeight, null);
g2.dispose();
image = scaledImg;
icon = new ImageIcon(image);
}
final Integer alpha = getDecorationOverlapTransparency(severity, decoratedComponent);
if (alpha != null) {
final Point translate =
this.getDecorationLocation(null, decoratedComponent,
new Dimension(icon.getIconWidth(), icon.getIconWidth()));
final int dcW = decoratedComponent.getWidth();
final int dcH = decoratedComponent.getHeight();
ImageFilter filter = new RGBImageFilter() {
@Override
public int filterRGB(int x, int y, int rgb) {
// If this x,y-coordinate covers the decorated component, make some transparency.
// The trailing FFFFFF means to keep all *colors* as is.
x += translate.x;
y += translate.y;
if (x > 0 && x < dcW && y > 0 && y < dcH) {
return (alpha << 24 | 0xFFFFFF) & rgb;
}
return rgb;
}
};
image = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), filter));
icon = new ImageIcon(image);
}
if (severity.equals(Severity.FATAL)) {
return fatalIconTransp = icon;
}
if (severity.equals(Severity.WARNING)) {
return warningIconTransp = icon;
}
assert severity.equals(Severity.INFO);
return infoIconTransp = icon;
}
/**
* A border to apply to the component which shows an error. A useful
* way to create custom borders is to wrap the original border and
* paint it, then paint over it. If the insets of the border returned
* by this method are different than the insets of the original
* border, then the UI layout will "jump".
Severity.color() and
* Severity.image() are handy here.
*/
static final class ColorizingBorder implements Border, ValidationUI {
private SimpleDefaultDecorator decorator;
private final JComponent decoratedComponent;
private final Border real;
private Severity severity = null;
public ColorizingBorder(JComponent c, SimpleDefaultDecorator decorator) {
this.decorator = decorator;
this.decoratedComponent = c;
this.real = (c.getBorder() != null ? c.getBorder() : BorderFactory.createEmptyBorder());
c.setBorder(this);
}
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
real.paintBorder(c, g, x, y, width, height);
if (severity == null) {
return;
}
Color niceTransparentColorForRectangle =
decorator.getComponentOverlayColor(severity, decoratedComponent);
if (niceTransparentColorForRectangle == null) {
return;
}
g.setColor(niceTransparentColorForRectangle);
g.fillRect(x, y, width, height);
// Graphics2D gg = (Graphics2D) g;
// Composite composite = gg.getComposite();
// AlphaComposite alpha =
// AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
// decorator.decorationBackgroundAlpha(severity, decoratedComponent));
// try {
// gg.setComposite(alpha);
// gg.fillRect(x, y, width, height);
// } finally {
// gg.setComposite(composite);
// }
// Insets ins = getBorderInsets(c);
// BufferedImage badge = severity.image();
// int by = (c.getHeight() / 2) - (badge.getHeight() / 2);
// int w = Math.max (2, ins.left);
// int bx = x + width - (badge.getHeight() + (w * 2));
// gg.drawRenderedImage(badge, AffineTransform.getTranslateInstance(bx, by));
}
@Override
public Insets getBorderInsets(Component c) {
return real.getBorderInsets(c);
}
@Override
public boolean isBorderOpaque() {
return false;
}
@Override
public void showProblem(Problem problem) {
if ( problem == null) {
severity = null;
} else {
severity = problem.severity();
//c.repaint();
}
}
public void clearProblem() {
severity = null;
}
}
/**
* A JLabel with a decorative icon (that will update when a new {@code
* Problem} appears) and that displays an informative tooltip.
* @author heden
*/
static final class ToolTippedIconLabel extends JLabel implements ValidationUI {
final private JToolTip tt = new JToolTip();
final private JLabel ttLabel = new JLabel();
final private JComponent decoratedComponent;
final private ValidationUI colorizingBorder;
private Problem currentProblem = null;
private MouseEvent lastMouseEvent = null;
private boolean hasAddedToPane = false;
private SimpleDefaultDecorator decorator;
ToolTippedIconLabel(final JComponent component, SimpleDefaultDecorator decorator) {
this.decorator = decorator;
this.decoratedComponent = component;
this.colorizingBorder = new ColorizingBorder(component, decorator);
this.setOpaque(false);
// Using HierarchyListener instead of ComponentListener.componentShown()
// and ComponentListener.componentHidden() to handle JTabbedPane, see
// issue 32
decoratedComponent.addHierarchyListener(new HierarchyListener() {
@Override
public void hierarchyChanged(HierarchyEvent e) {
if((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0){
tryDecorationIcon();
ToolTippedIconLabel.this.setVisible(
decoratedComponent.isShowing() &&
currentProblem != null
);
}
}
});
decoratedComponent.addComponentListener(new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent evt) {
tryDecorationIcon();
}
@Override
public void componentResized(ComponentEvent evt) {
tryDecorationIcon();
}
});
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
lastMouseEvent = e;
}
@Override
public void mouseExited(MouseEvent e) {
lastMouseEvent = null;
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
lastMouseEvent = e;
}
});
//////////////////////////////////////////
// Fiddle with tooltip
tt.setLayout(new BorderLayout());
tt.add(ttLabel);
tt.setBorder(null);
}
@Override
public JToolTip createToolTip() {
assert SwingUtilities.isEventDispatchThread() : "Not on EventDispatchThread";
assert tt != null;
return tt;
}
@Override
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible && currentProblem != null) {
colorizingBorder.showProblem(currentProblem);
} else {
colorizingBorder.clearProblem();
}
}
@Override
public void showProblem(final Problem problem) {
// JComponent has been newly validated.
assert SwingUtilities.isEventDispatchThread() : "Not on EventDispatchThread";
if (problem != null && problem.equals(currentProblem)) {
return;
}
colorizingBorder.showProblem(problem);
currentProblem = problem;
if (currentProblem == null) {
if (this.isVisible()) {
this.setVisible(false);
}
if (tt.isShowing()) {
// Bring down tooltip if it isShowing
final MouseEvent theEvent = lastMouseEvent; // lastEvent will be set to null in mouseExited, so hold a local reference here.
this.dispatchEvent(new MouseEvent(this, MouseEvent.MOUSE_EXITED, System.currentTimeMillis(), 0, 0, 0, 0, false));
lastMouseEvent = theEvent;
}
return;
}
////////////////////////////////////////////////////
// Fiddle with tooltip. We do not do this within tryDecorationIcon(),
// because it is only necessary to do this in updateProblem(). Also, we do
// this *before* calling tryDecorationIcon(), because that method can
// return false in cases when we still want to prepare the tooltip.
problemUpdateTooltip(problem);
if (!this.tryDecorationIcon()) {
return;
}
this.setVisible(true);
}
private void problemUpdateTooltip(Problem problem) {
if (decorator.getDecorationImage(problem.severity(), decoratedComponent) == null
|| !decorator.configureToolTipLabel(problem, decoratedComponent, ttLabel)) {
// No tooltip if no decoration, and also no toolTip if configureToolTipLabel
// returned false
tt.setVisible(false);
if(this.getToolTipText() != null) {
this.setToolTipText(null); // "Unregister" from ToolTipManager..
}
return;
}
tt.setVisible(true);
if(this.getToolTipText() == null) {
this.setToolTipText(""); // "Register" with ToolTipManager..
}
tt.setPreferredSize(ttLabel.getPreferredSize());
if (lastMouseEvent != null) {
// * If the tooltip is showing: "adapt" the *size* of the tooltip by bringing
// it down and up again -- by emulating some mouse movements.
// * If the tooltip is not showing but the mouse pointer seems to be
// above icon, fire up tooltip.
final MouseEvent theEvent = lastMouseEvent; // lastEvent will be set to null in mouseExited, so hold a local reference here.
this.dispatchEvent(new MouseEvent(this, MouseEvent.MOUSE_EXITED, System.currentTimeMillis() - 100, theEvent.getModifiers(), theEvent.getX(), theEvent.getY(), 0, false));
assert lastMouseEvent == null;
this.dispatchEvent(new MouseEvent(this, MouseEvent.MOUSE_ENTERED, System.currentTimeMillis() - 50, theEvent.getModifiers(), theEvent.getX(), theEvent.getY(), 0, false));
this.dispatchEvent(new MouseEvent(this, MouseEvent.MOUSE_MOVED, System.currentTimeMillis(), theEvent.getModifiers(), theEvent.getX(), theEvent.getY(), 0, false));
assert lastMouseEvent != null;
}
////////////////////////////////////////////////////
}
/**
* Set/Update the location of the icon so that it follows the
* component at resize etc.
*
* @return true if there is an icon and the state of the UI is
* such that it is ready to be set visible.
*
* @return false otherwise: If there is currently no problem,
* or if the UI has not finished laying out
* (so that the location of the decoration icon can not yet be
* calculated), or if the decorator has been configured in a way
* that there should be no Icon visible at all for the current
* severity (only the ColorizingBorder is to be used)
*/
private boolean tryDecorationIcon() {
assert SwingUtilities.isEventDispatchThread() : "Not on EventDispatchThread";
if (!decoratedComponent.isShowing()) {
// This is before UI has finished being laid out. Can't do
// anything now, wait until component listener gets notified.
// (problemUpdate() has been called during initialization --
// the UI has errors from the start.)
return false;
}
assert JLayeredPane.getLayeredPaneAbove(decoratedComponent) != null :
"JLayeredPane.getLayeredPaneAbove(decoratedComponent) unexpectedly returned null";
// Actually this is not so unexpected if we're not in a JFrame, JDialog, JApplet or JInternalFrame.
// See http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html .
// Should we account for this possibility somehow?
if (!hasAddedToPane) {
JLayeredPane.getLayeredPaneAbove(decoratedComponent).add(ToolTippedIconLabel.this,
new Integer(JLayeredPane.getLayer(decoratedComponent) + 10));
hasAddedToPane = true;
}
if (currentProblem == null) {
// No point in calculating location now, we don't know our size yet.
// (We have not encountered a problem yet so there's no icon. We're
// here because the ComponentListener has been notified about a resize or a move.)
return false;
}
Icon icon = decorator.getDecorationIcon(currentProblem.severity(), decoratedComponent);
if (icon == null) {
return false;
}
this.setIcon(icon);
this.setSize(new Dimension(getIcon().getIconWidth(), getIcon().getIconHeight()));
Point p = decoratedComponent.getLocationOnScreen();
SwingUtilities.convertPointFromScreen(p, this.getParent());
Point transl =
decorator.getDecorationLocation(null, decoratedComponent,
new Dimension(this.getIcon().getIconWidth(), this.getIcon().getIconHeight()));
p.translate(transl.x, transl.y);
this.setLocation(p);
return true;
}
public void clearProblem() {
showProblem(null);
}
}
}
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/swing/MultilineLabelUI.java 0000644 0001750 0001750 00000047473 11661314136 030746 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui.swing;
import java.awt.Color;
import java.awt.Component;
import java.awt.Component.BaselineResizeBehavior;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.HierarchyBoundsListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.Popup;
import javax.swing.PopupFactory;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.border.Border;
import javax.swing.plaf.LabelUI;
import org.netbeans.validation.api.Problem;
import org.netbeans.validation.api.Severity;
/**
* Label UI which renders multiline text
*
* @author Tim Boudreau
*/
final class MultilineLabelUI extends LabelUI {
private static Graphics2D createOffscreenGraphics(JComponent c) {
if (c == null || c.getGraphicsConfiguration() == null) {
return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().createCompatibleImage(1, 1).createGraphics();
}
return c.getGraphicsConfiguration().createCompatibleImage(1, 1).createGraphics();
}
@Override
public int getBaseline(JComponent c, int width, int height) {
return c.getInsets().top + createOffscreenGraphics(null).getFontMetrics(c.getFont()).getMaxAscent();
}
@Override
public BaselineResizeBehavior getBaselineResizeBehavior(JComponent c) {
return BaselineResizeBehavior.CONSTANT_DESCENT;
}
@Override
public void installUI(JComponent c) {
super.installUI(c);
((JLabel) c).setIconTextGap(5);
((JLabel) c).setOpaque(false);
}
@Override
public void update(Graphics g, JComponent c) {
if (c.isOpaque()) {
g.setColor (c.getBackground());
g.fillRect(0, 0, c.getWidth(), c.getHeight());
}
paint (g, c);
}
@Override
public Dimension getMaximumSize(JComponent c) {
GraphicsConfiguration gc = c.getGraphicsConfiguration();
if (gc == null) {
return super.getMaximumSize(c);
}
int maxw = gc.getDevice().getDisplayMode().getWidth();
String s = ((JLabel) c).getText();
Insets ins = c.getInsets();
Graphics2D g = createOffscreenGraphics(c);
int txtWidth = ins.left + g.getFontMetrics(c.getFont()).stringWidth(s);
int parentWidth = (c.getParent() == null ? maxw - (maxw / 4) : c.getParent().getWidth() - (c.getParent().getWidth() / 4)) - ins.right;
Dimension result;
if (txtWidth > parentWidth) {
int ht = renderPlainString(c, s, g, ins.left, ins.top, parentWidth, c.getFont(), Color.BLACK, false).requiredHeight;
result = new Dimension (parentWidth, ht);
} else {
result = new Dimension (txtWidth, g.getFontMetrics(c.getFont()).getHeight());
}
Icon icon = ((JLabel) c).getIcon();
if (icon != null) {
result.width += icon.getIconWidth();
result.height += icon.getIconHeight();
}
result.width += ins.left + ins.right;
result.height += ins.top + ins.bottom;
return result;
}
@Override
public Dimension getMinimumSize(JComponent c) {
JLabel lbl = (JLabel) c;
char[] dummy = new char[80];
Arrays.fill(dummy, 'X');
Graphics2D g = createOffscreenGraphics(c);
int testWidth = g.getFontMetrics(c.getFont()).stringWidth(new String(dummy));
GraphicsConfiguration gc = c.getGraphicsConfiguration();
if (gc == null) {
return super.getMinimumSize(c);
}
int maxw = gc.getDevice().getDisplayMode().getWidth();
Insets ins = c.getInsets();
int parentWidth = c.getWidth();
if (parentWidth == 0 && c.getParent() != null) {
Component parent = c.getParent();
while (parentWidth == 0 && parent != null) {
parentWidth = parent.getWidth();
if (parent instanceof JScrollPane) {
JScrollPane pane = (JScrollPane) parent;
JViewport port = pane.getViewport();
parentWidth = port.getWidth();
Insets paneInsets = pane.getInsets();
Insets portInsets = port.getInsets();
parentWidth -= paneInsets.left + paneInsets.right + portInsets.left + portInsets.right;
}
parent = parent.getParent();
}
}
if (parentWidth == 0) {
parentWidth = maxw + (maxw / 4);
}
parentWidth -= ins.left + ins.right;
boolean needWrap = parentWidth < testWidth;
int ht = Math.max(16, g.getFontMetrics(c.getFont()).getHeight());
if (!needWrap) {
//Always provide for 2 lines
ht *= 2;
}
int w = g.getFontMetrics(c.getFont()).stringWidth(lbl.getText());
Dimension result = new Dimension (ins.left + ins.right + w, ins.bottom + ins.top + ht);
return result;
}
private static final int MIN_CHARS = 100;
@Override
public Dimension getPreferredSize(JComponent c) {
JLabel lbl = (JLabel) c;
String s = lbl.getText();
boolean popup = c instanceof MultilineLabel && ((MultilineLabel) c).isPopup();
if (!popup) {
if (s == null || s.length() < MIN_CHARS) {
char[] dummy = new char[MIN_CHARS];
Arrays.fill(dummy, 'X');
s = new String(dummy);
}
}
int maxw = c.getGraphicsConfiguration() == null ? Toolkit.getDefaultToolkit().getScreenSize().width :
c.getGraphicsConfiguration().getDevice().getDisplayMode().getWidth();
Insets ins = c.getInsets();
int parentWidth = c.getWidth();
if (parentWidth == 0 && c.getParent() != null) {
Component parent = c.getParent();
while (parentWidth == 0 && parent != null) {
parentWidth = parent.getWidth();
parent = parent.getParent();
}
}
if (parentWidth <= 0) {
parentWidth = maxw + (maxw / 4);
}
parentWidth -= ins.left + ins.right;
return getPreferredSize(lbl, parentWidth).dim;
}
static Metrics getPreferredSize (JLabel lbl, int parentWidth) {
Icon icon = lbl.getIcon();
if (icon != null) {
parentWidth -= icon.getIconWidth();
}
Insets ins = lbl.getInsets();
int iconW = icon == null ? 0 : icon.getIconWidth() + lbl.getIconTextGap();
Graphics2D g = createOffscreenGraphics(lbl);
Metrics metrics = renderPlainString(lbl, lbl.getText(),
g, ins.left, ins.top, parentWidth, lbl.getFont(), Color.BLACK, false, iconW);
int ht = metrics.requiredHeight;
Dimension result = new Dimension();
if (icon != null) {
result.height = Math.max (metrics.lineheight * metrics.linecount, icon.getIconHeight());
} else {
result.height = metrics.lineheight * metrics.linecount;
}
result.width = metrics.widestLine;
result.width += ins.left + ins.right;
result.height += ins.top + ins.bottom;
metrics.dim = result;
return metrics;
}
@Override
public void paint(Graphics g, JComponent c) {
Insets ins = c.getInsets();
Graphics2D gg = (Graphics2D) g;
JLabel lbl = (JLabel) c;
Icon icon = lbl.getIcon();
int gap = lbl.getIconTextGap();
int startX = ins.left + gap;
int startY = ins.top;
if (icon != null) {
icon.paintIcon(c, g, ins.top, ins.left);
startX = icon.getIconWidth() + gap;
boolean popup = c instanceof MultilineLabel && ((MultilineLabel) c).isPopup();
int yHeight = popup ? g.getFontMetrics(c.getFont()).getHeight() : g.getFontMetrics(c.getFont()).getMaxAscent();
startY += (icon.getIconHeight() / 2) - (yHeight / 2);
}
String txt = ((JLabel) c).getText();
if (txt != null) {
renderPlainString(c, txt, gg, ins.left, startY, c.getWidth() - (ins.left + ins.right), c.getFont(), c.getForeground(), true, startX);
}
}
private static Metrics renderPlainString (JComponent c, String s, Graphics2D g, int x, int y, int w, Font f, Color foreground, boolean paint) {
return renderPlainString(c, s, g, x, y, w, f, foreground, paint, 0);
}
private static Metrics renderPlainString (JComponent comp, String s, Graphics2D g, int x, int y, int w, Font f, Color foreground, boolean paint, int startX) {
if (g == null) {
g = createOffscreenGraphics(comp);
}
if (f == null) {
f = UIManager.getFont("controlFont");
if (f == null) {
int fs = 11;
Object cfs = UIManager.get("customFontSize"); //NOI18N
if (cfs instanceof Integer) {
fs = ((Integer) cfs).intValue();
}
f = new Font("Dialog", Font.PLAIN, fs); //NOI18N
}
}
if (paint) {
g.setRenderingHints(getHints());
g.setFont(f);
g.setColor(foreground);
}
FontMetrics fm = g.getFontMetrics(f);
int baseline = y + fm.getMaxAscent();
int ht = fm.getHeight();
Metrics result = new Metrics(ht);
int dx = x + startX;
result.lineLength(dx);
String[] words = s.split(" ");
int spaceWidth = fm.stringWidth(" ");
wordloop: for (int i=0; i < words.length; i++) {
String word = words[i];
int wordWidth = fm.stringWidth(word);
boolean wrap = dx + wordWidth > w && i > 0;
boolean brutalWrap = wordWidth > w;
if (brutalWrap) {
char[] chars = word.toCharArray();
for (int j = 0; j < chars.length; j++) {
char c = chars[j];
int cwidth = fm.charWidth(c);
if (dx + cwidth > w) {
result.lineLength(dx);
dx = x;
baseline += ht;
result.wrap();
}
if (paint) {
g.drawChars(chars, j, 1, dx, baseline);
}
dx += cwidth;
result.lineLength(dx);
if (j == chars.length - 1) {
dx += spaceWidth;
result.lineLength(dx);
continue wordloop;
}
}
}
if (wrap) {
result.lineLength(dx);
result.wrap();
dx = x;
baseline += ht;
}
if (paint) {
g.drawString(word, dx, baseline);
}
dx += spaceWidth + wordWidth;
result.lineLength(dx);
}
// result.finished(baseline + fm.getMaxDescent() + y);
result.finished(baseline + y);
return result;
}
private static final boolean antialias = Boolean.getBoolean("nb.cellrenderer.antialiasing") // NOI18N
||Boolean.getBoolean("swing.aatext") // NOI18N
||(isGTK() && gtkShouldAntialias()) // NOI18N
|| isAqua();
static Map hintsMap;
@SuppressWarnings("unchecked")
static final Map,?> getHints() {
//XXX We REALLY need to put this in a graphics utils lib
if (hintsMap == null) {
//Thanks to Phil Race for making this possible
hintsMap = (Map)(Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints")); //NOI18N
if (hintsMap == null) {
hintsMap = new HashMap();
if (antialias) {
hintsMap.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
}
}
}
Map,?> ret = hintsMap;
assert ret != null; // does this method need to be synchronized?
return ret;
}
static boolean isAqua () {
return "Aqua".equals(UIManager.getLookAndFeel().getID());
}
static boolean isGTK () {
return "GTK".equals(UIManager.getLookAndFeel().getID());
}
static boolean isNimbus () {
return "Nimbus".equals(UIManager.getLookAndFeel().getID());
}
private static Boolean gtkAA;
static final boolean gtkShouldAntialias() {
if (gtkAA == null) {
Object o = Toolkit.getDefaultToolkit().getDesktopProperty("gnome.Xft/Antialias"); //NOI18N
gtkAA = new Integer(1).equals(o) ? Boolean.TRUE : Boolean.FALSE;
}
return gtkAA.booleanValue();
}
static Popup showPopup(Problem problem, Component parent, int x, int y) {
Severity severity = problem.severity();
Color bg = UIManager.getColor("white") == null ? Color.WHITE : UIManager.getColor("white");
Border b = BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(severity.color(), 1),
BorderFactory.createEmptyBorder(3, 3, 3, 3));
final MultilineLabel lbl = new MultilineLabel(true);
lbl.createUI().showProblem(problem);
lbl.setBorder(b);
lbl.setForeground(severity.color());
lbl.setBackground(bg);
Point screenLoc = parent.getLocationOnScreen();
int screenWidth = parent.getGraphicsConfiguration().getDevice().getDisplayMode().getWidth();
int screenX = screenLoc.x + x;
int screenY = screenLoc.y + y;
int availWidth = screenWidth - screenX;
Popup popup = PopupFactory.getSharedInstance().getPopup(parent, lbl, screenX, screenY);
Insets ins = b.getBorderInsets(lbl);
Metrics mm = getPreferredSize(lbl, availWidth);
System.err.println("METRICS:\n" + mm);
Dimension d = mm.dim;
d.width = mm.widestLine + ins.left + ins.right + severity.icon().getIconWidth() + lbl.getIconTextGap();
lbl.setPreferredSize(d);
return new WrapPopup(parent, popup);
}
private static final class WrapPopup extends Popup implements HierarchyListener, HierarchyBoundsListener {
private final Popup realPopup;
private final Component target;
WrapPopup(Component target, Popup realPopup) {
this.realPopup = realPopup;
this.target = target;
}
@Override
public void hide() {
realPopup.hide();
detach();
}
@Override
public void show() {
attach();
realPopup.show();
}
private void attach() {
target.addHierarchyListener(this);
target.addHierarchyBoundsListener(this);
}
private void detach() {
target.removeHierarchyListener(this);
target.removeHierarchyBoundsListener(this);
}
@Override
public void ancestorMoved(HierarchyEvent e) {
hide();
}
@Override
public void ancestorResized(HierarchyEvent e) {
hide();
}
@Override
public void hierarchyChanged(HierarchyEvent e) {
hide();
}
}
public static void main(String[] args) throws Exception {
JFrame jf = new JFrame();
final JLabel lbl = new JLabel("Hello");
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jf.setContentPane(lbl);
final String err = "This is a big honkin long error message, in fact its so long it will probably have to be wrapped to multiple lines whether " +
"we want it to or not - otherwise there will be much trouble.";
lbl.addMouseListener(new MouseAdapter() {
Popup popup;
@Override
public void mouseEntered(MouseEvent e) {
if (popup != null) {
popup.hide();
}
popup = MultilineLabelUI.showPopup(new Problem(err, Severity.FATAL), lbl, e.getX(), e.getY());
popup.show();
}
@Override
public void mouseExited(MouseEvent e) {
if (popup != null) popup.hide();
}
@Override
public void mouseMoved(MouseEvent e) {
mouseEntered(e);
}
});
jf.pack();
jf.setVisible(true);
}
private static final class Metrics {
int linecount = 1;
int widestLine;
int requiredHeight;
final int lineheight;
Dimension dim;
Metrics(int lineheight) {
this.lineheight = lineheight;
}
void wrap() {
linecount++;
}
void finished(int bottom) {
this.requiredHeight = bottom;
}
void lineLength(int pixels) {
widestLine = Math.max(pixels, widestLine);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append ("Line Count: " + linecount);
sb.append("\nWidest Line: " + widestLine);
sb.append("\nRequired Height " + requiredHeight);
sb.append("\nLine Height: " + lineheight);
return sb.toString();
}
}
}
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/JListValidationListenerImpl.java 0000644 0001750 0001750 00000011742 11654612134 032036 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui;
import javax.swing.event.ListSelectionEvent;
import org.netbeans.validation.api.Validator;
import org.netbeans.validation.api.ui.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.EventListener;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionListener;
import org.netbeans.validation.api.Problems;
import org.netbeans.validation.api.ui.swing.SwingValidationGroup;
import org.netbeans.validation.api.ui.swing.SwingValidationGroup;
/**
*
* @author Hugo Heden
*/
class JListValidationListenerImpl extends ValidationListener
implements EventListener, ListSelectionListener, FocusListener {
private Validator validator;
private boolean hasFatalProblem = false;
public JListValidationListenerImpl(JList component,
ValidationStrategy strategy,
ValidationUI validationUI,
Validator validator
) {
super(JList.class, validationUI, component);
this.validator = validator;
if (strategy == null) {
throw new NullPointerException("strategy null");
}
getTarget().addPropertyChangeListener("enabled", new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
performValidation();
}
});
switch (strategy) {
case DEFAULT:
case ON_CHANGE_OR_ACTION:
component.addListSelectionListener(this);
break;
case ON_FOCUS_LOSS:
component.addFocusListener(this);
break;
case INPUT_VERIFIER:
component.setInputVerifier( new InputVerifier() {
@Override
public boolean verify(JComponent input) {
performValidation();
return !hasFatalProblem;
}
});
break;
default:
throw new AssertionError();
}
performValidation(); // Make sure any initial errors are discovered immediately.
}
@Override
protected void performValidation(Problems ps){
JList component = getTarget();
if (!getTarget().isEnabled()) {
return;
}
validator.validate(ps, SwingValidationGroup.nameForComponent(component), component.getSelectionModel());
hasFatalProblem = ps.hasFatal();
}
@Override
public void focusLost(FocusEvent e) {
performValidation();
}
public void valueChanged(ListSelectionEvent lse) {
performValidation();
}
@Override
public void focusGained(FocusEvent e) {
}
}
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/ValidationGroupProvider.java 0000644 0001750 0001750 00000005304 11654612134 031265 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui;
import org.netbeans.validation.api.ui.ValidationGroup;
/**
* Optional interface which can be implemented on a component to
* indicate that it supplies validation.
*
* Useful for composing together panels that have validation groups -
* for example, if a panel implementing this interface is added to
* a ValidationPanel, then its SwingValidationGroup will tranparently
* be merged into that of the ValidationPanel.
*
* @author Tim Boudreau
*/
public interface ValidationGroupProvider {
public ValidationGroup getValidationGroup();
}
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/JComboBoxValidationListenerImpl.java 0000644 0001750 0001750 00000011525 11654612134 032632 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui;
import javax.swing.ComboBoxModel;
import org.netbeans.validation.api.Validator;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import java.util.EventListener;
import javax.swing.JComboBox;
import org.netbeans.validation.api.Problems;
import org.netbeans.validation.api.ui.swing.SwingValidationGroup;
/**
*
* @author Tim Boudreau
*/
class JComboBoxValidationListenerImpl extends ValidationListener
implements EventListener, ItemListener, FocusListener {
private Validator validator;
private boolean hasFatalProblem = false;
public JComboBoxValidationListenerImpl(JComboBox component,
ValidationStrategy strategy,
ValidationUI validationUI,
Validator validator
) {
super(JComboBox.class, validationUI, component);
this.validator = validator;
if (strategy == null) {
throw new NullPointerException("strategy null");
}
component.addPropertyChangeListener("enabled", new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
performValidation();
}
});
switch (strategy) {
case DEFAULT:
case ON_CHANGE_OR_ACTION:
component.addItemListener(this);
break;
case ON_FOCUS_LOSS:
component.addFocusListener(this);
break;
case INPUT_VERIFIER:
component.setInputVerifier( new InputVerifier() {
@Override
public boolean verify(JComponent input) {
performValidation();
return !hasFatalProblem;
}
});
break;
default:
throw new AssertionError();
}
performValidation(); // Make sure any initial errors are discovered immediately.
}
@Override
protected void performValidation(Problems ps){
JComboBox component = getTarget();
if (!component.isEnabled()) {
return;
}
validator.validate(ps, SwingValidationGroup.nameForComponent(component), component.getModel());
hasFatalProblem = ps.hasFatal();
}
@Override
public void focusLost(FocusEvent e) {
performValidation();
}
@Override
public void itemStateChanged(ItemEvent e) {
performValidation();
}
@Override
public void focusGained(FocusEvent e) {
}
}
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/MulticastValidationUI.java 0000644 0001750 0001750 00000010140 11654612134 030653 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.netbeans.validation.api.Problem;
/**
*
* @author Tim Boudreau
*/
final class MulticastValidationUI implements ValidationUI {
private final Set real;
MulticastValidationUI(ValidationUI... real) {
this.real = new HashSet(Arrays.asList(real));
assert validUIs(real);
}
public void add(ValidationUI ui) {
if (ui == null) {
throw new NullPointerException();
}
assert !contains(ui) : "Already a member: " + ui;
real.add (ui);
}
public void remove(ValidationUI ui) {
if (ui == null) {
throw new NullPointerException();
}
assert contains(ui) : "Not a member: " + ui;
real.remove(ui);
}
public boolean contains(ValidationUI check) {
boolean result = real.contains(check);
if (!result) {
for (ValidationUI ui : real) {
if (ui instanceof MulticastValidationUI) {
if (result = ((MulticastValidationUI) ui).contains(check)) {
break;
}
}
}
}
return result;
}
@Override
public void showProblem(Problem problem) {
assert real != null;
for (ValidationUI ui : real) {
ui.showProblem(problem);
}
}
public boolean validUIs(ValidationUI[] uis) {
for (int i = 0; i < uis.length; i++) {
ValidationUI ui = uis[i];
if (ui == null) {
throw new NullPointerException("Element " + i + " of ui " +
"array is null");
}
}
return true;
}
public void clearProblem() {
assert real != null;
for (ValidationUI ui : real) {
ui.clearProblem();
}
}
}
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/ValidationItem.java 0000644 0001750 0001750 00000024773 11654612134 027367 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui;
import org.netbeans.validation.api.Problem;
/**
* Common superclass for {@code ValidationGroup} and {@code ValidationListener}, providing a common API
* for forcing revalidation of the managed UI component or components, see {@link #performValidation()},
* and for temporarily suspending validation, see
* {@link #runWithValidationSuspended(java.lang.Runnable)}
*
* {@code ValidationItem}s can be added to a ValidationGroup using
* {@link ValidationGroup#addItem(org.netbeans.validation.api.ui.ValidationItem, boolean) }.
*
* @author Tim Boudreau
* @author Hugo Heden
*/
public abstract class ValidationItem {
private Problem currentLeadProblem = null;
private Problem currentProblemInUI = null;
private ValidationGroup parentValidationGroup = null;
private int suspendCount = 0;
private boolean uiEnabled = true;
private final MulticastValidationUI multicastValidationUI = new MulticastValidationUI();
ValidationItem(ValidationUI... uis) { // Package visibility to make class "final" outside of package
for (ValidationUI ui : uis) {
// Dont call addUI. This is superclass constructor, the subclass is not finished with creation yet, so this is too early.
// Instead, subclass is responsible for updating UI:s
multicastValidationUI.add(ui);
}
}
void addUI(ValidationUI ui) {
if (!containsUI(ui)) {
multicastValidationUI.add(ui);
if(uiEnabled){
if (currentProblemInUI == null) {
ui.clearProblem();
} else {
ui.showProblem(currentProblemInUI);
}
}
}
}
void removeUI(ValidationUI ui) {
if (containsUI(ui)) {
this.multicastValidationUI.remove(ui);
ui.clearProblem();
}
}
final void showIfUIEnabled( Problem problem ){
if( uiEnabled &&
(
(currentProblemInUI != null && !currentProblemInUI.equals(problem) )
||
( currentProblemInUI == null && problem != null )
)
){
currentProblemInUI = problem;
if ( problem == null) {
multicastValidationUI.clearProblem();
} else {
multicastValidationUI.showProblem( problem );
}
}
}
private boolean containsUI(ValidationUI ui) {
return this.multicastValidationUI.contains(ui);
}
/**
*
A request (to the simple-validation infrastructure) for revalidation of
* the component(s) managed by this ValidationListener/ValidationGroup, updating
* the {@code ValidationUI} as necessary.
*
*
This method can be called by client code (i.e non-subclasses), to manually
* request revalidation -- a "refresh". This can be useful if custom ValidationListeners are used that rely
* not only on the state of the managed component, but also on outside state
* that the listener does not know about
*
*
More typically , this method is called by {@code ValidationListener} subclasses
* to let the simple-validation infrastructure know
* that the user has interacted with the UI-component in a way that makes revalidation
* needed.
*
*
This will initiate the validation logic (unless the validation is suspended, see
* {@link ValidationItem#runWithValidationSuspended(java.lang.Runnable)}:
* A call to {@link ValidationListener#performValidation(org.netbeans.validation.api.Problems)}
* will occur.
*
*
If this results in a {@link Problem}, the {@link ValidationUI}
* managed by this {@code ValidationListener} (such as an error icon
* decorating the UI-component) will be activated, indicating the {@code Problem}
* to the user.
*
*
If this ValidationListener has been added to a {@link ValidationGroup},
* the latter will update its {@code ValidationUI}:s as well (unless there happens
* to be a more severe {@code Problem} somewhere else within that {@code ValidationGroup})
*
* @return The lead problem of the ValidationItem, null if there is no Problem
*
*
*/
public final Problem performValidation() {
if (isSuspended()) {
return this.getCurrentLeadProblem();
}
subtreeRevalidation();
if( getParentValidationGroup() != null ) {
getParentValidationGroup().validationTriggered(this);
} else {
showIfUIEnabled(getCurrentLeadProblem());
}
return getCurrentLeadProblem();
}
// Package private method. Intented to be a helper method for implementing performValidation().
// If the latter is called on a ValidationGroup, the whole subtree should revalidate
// recursively down to the leafs, with help from this method.
// So, if this is a ValidationGroup, this
// method should pass the call recursively down the tree of ValidationItem:s to
// the leafs (typically ValidationListener:s). A ValidationListener should
// perform revalidation, store the new lead problem (if any) and then
// just return -- i.e they should not call validationTriggered or update
// the UI. The calling parent ValidationGroup should then perform GroupValidation
// (if any) and then update the UI of each child as appropriate, and then
// return -- i.e it should not update its own UI.
abstract void subtreeRevalidation();
/**
* The current problem leading problem (if any) with this ValidationItem
* @return The current problem
* @return null if there currently is no problem.
*/
final Problem getCurrentLeadProblem() {
return this.currentLeadProblem;
}
final void setCurrentLeadProblem(Problem problem){
this.currentLeadProblem = problem;
}
/**
* Indicates whether this ValidationGroup is currently suspended.
* @see #runWithValidationSuspended(java.lang.Runnable)
* @return true if this ValidationGroup is currently suspended, false otherwise
*/
final boolean isSuspended() {
return suspendCount > 0 || (getParentValidationGroup() != null && ((ValidationItem)getParentValidationGroup()).isSuspended());
}
/**
* Disable validation and invoke a runnable. This method is useful
* in UIs where a change in one component can trigger changes in
* another component, and you do not want validation to be triggered
* because a component was programmatically updated.
*
* For example, say you have a dialog that lets you create a new
* Servlet source file. As the user types the servlet name, web.xml
* entries are updated to match, and these are also in fields in the same
* dialog. Since the updated web.xml entries are being programmatically
* (and presumably correctly) generated, those changes should not
* trigger a useless validation run. Wrap such generation code in
* a Runnable and pass it to this method when making programmatic
* changes to the contents of the UI.
*
* The runnable is run synchronously, but no changes made to components
* while the runnable is running will trigger validation.
*
* When the last runnable exits,
* validateAll(null) will be called to run validation
* against the entire newly updated UI.
*
* This method is reentrant - a call to updateComponents can trigger
* another call to updateComponents without triggering multiple
* calls to validateAll() on each Runnable's exit.
*
* @param run A runnable which makes changes to the contents of one
* or more components in the UI which should not trigger validation
*/
public final void runWithValidationSuspended(Runnable run) {
suspendCount++;
try {
run.run();
} finally {
suspendCount--;
if (!isSuspended()) {
performValidation();
}
}
}
/**
* @return null if this ValidationItem is not added to a ValidationGroup
*/
final ValidationGroup getParentValidationGroup() {
return parentValidationGroup;
}
/**
* @param parentGroup null allowed
*/
final void setParentValidationGroup(ValidationGroup parentGroup, boolean setUIEnabled) {
this.parentValidationGroup = parentGroup;
this.uiEnabled = setUIEnabled;
}
}
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/GroupValidator.java 0000644 0001750 0001750 00000025622 11654612134 027412 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui;
import org.netbeans.validation.api.Problems;
/**
* Encapsulates validation of the combination of several UI
* components within a {@link ValidationGroup}.
*
*
UI-components whose validity depends not only on their own state
* but on the state of each other as well, can be said to have
* validity interdependencies. In such cases not only the state of
* each component needs to be validated as a singular, but the
* combination of components needs to be validated as well.
*
*
The following items outline what needs to be done to achieve this.
*
*
*
* The UI components with interdependencies need to be added to
* the same {@code ValidationGroup}
*
* This {@code ValidationGroup} needs to be prepared at creation time
* with an instance of {@code GroupValidator}.
*
* In this {@code GroupValidator}, the method {@link
* #performGroupValidation(org.netbeans.validation.api.Problems) }
* needs to be overridden to perform the custom interdependency
* validation.
*
*
*
* When a UI component is changed (either programmatically or by
* having been interacted with by the user) the following will happen:
*
*
*
* As usual, the UI component will be revalidated using its
* connected validators.
*
* Now, only if there is no fatal {@link org.netbeans.validation.api.Problem}
* in any of the UI components within the {@code ValidationGroup}, the validation in
* the {@code GroupValidator} will be invoked as well.
*
* If it turns out that the latter yields a {@code Problem} more
* severe (i.e strictly worse) than any other {@code Problem} in the
* {@code ValidationGroup}, then this {@code Problem} will become the
* lead problem in the group.
*
* The lead problem of the group (whichever it may be) is shown
* as usual in the {@link ValidationUI}(s) of the {@code ValidationGroup}.
*
* If the lead {@code Problem} happens to be the one caused by the
* {@code GroupValidator}, then the default behavior is that this
* {@code Problem} will cause all UI components within the
* ValidationGroup to be decorated. This behavior can however be
* disabled by passing {@code false} to the constructor {@link
* #GroupValidator(boolean) }
*
*
*
* The following code example illustrates how this class can be
* used.
*
class SumValidation extends GroupValidator {
SumValidation() {
super (true );
}
@Override
protected void performGroupValidation(Problems problems) {
try {
int desiredSum = Integer.parseInt(sumComboBox.getModel().getSelectedItem().toString());
int val1 = Integer.parseInt(aField.getText());
int val2 = Integer.parseInt(bField.getText());
int val3 = Integer.parseInt(cField.getText());
int sum = val1 + val2 + val3;
if (sum != desiredSum) {
problems.add( new Problem (val1 + " + " + val2 + " + " + val3 +
" equals " + sum + " , not " + desiredSum, Severity.FATAL));
} else if (val1 == desiredSum || val2 == desiredSum || val3 == desiredSum) {
problems.add( new Problem (" Hey...that's cheating! " ,
Severity.WARNING) );
}
} catch (NumberFormatException e) {
}
}
}
SwingValidationGroup bunch = SwingValidationGroup.create(new SumValidation());
Validator<String> fieldValidator =
StringValidators.trimString(StringValidators.REQUIRE_NON_EMPTY_STRING,
StringValidators.NO_WHITESPACE,
StringValidators.REQUIRE_VALID_NUMBER,
StringValidators.REQUIRE_VALID_INTEGER,
StringValidators.REQUIRE_NON_NEGATIVE_NUMBER);
bunch.add(aField, fieldValidator);
bunch.add(bField, fieldValidator);
bunch.add(cField, fieldValidator);
bunch.add(SwingValidationListenerFactory.createJComboBoxValidationListener(sumComboBox, ValidationUI.NoOp.get()));
*
*
*
* @author Hugo Heden
*/
public abstract class GroupValidator {
private final boolean shallShowProblemInChildrenUIs;
private boolean isCurrentlyLeadingProblem = false;
/**
* Default constructor, calls {@code this(true)}
*/
protected GroupValidator() {
this( true );
}
/**
* @param shallShowProblemInChildrenUIs specifies whether a
* Problem generated by the {@code GroupValidator} (if it happens
* to be the lead {@code Problem}) should cause the UI-components
* in the {@code ValidationGroup} to be decorated (showing the
* {@code Problem}) or not
*/
protected GroupValidator(boolean shallShowProblemInChildrenUIs ) {
this.shallShowProblemInChildrenUIs = shallShowProblemInChildrenUIs;
}
final boolean isCurrentlyLeadingProblem() {
return isCurrentlyLeadingProblem;
}
final void setIsCurrentlyLeadingProblem(boolean isCurrentlyLeadingProblem) {
this.isCurrentlyLeadingProblem = isCurrentlyLeadingProblem;
}
final boolean shallShowProblemInChildrenUIs() {
return shallShowProblemInChildrenUIs;
}
/**
* Validate the state of the combination of the UI components
* within the ValidationGroup. If invalid
* this method shall add one or more {@code Problem}s to
* the passed list.
*
* @param problems A list of problems.
*/
protected abstract void performGroupValidation(Problems problems);
}
libsimple-validation-java-.orig/org/netbeans/validation/api/ui/ValidationGroup.java 0000644 0001750 0001750 00000051011 11654612134 027546 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui;
import java.util.LinkedList;
import java.util.List;
import org.netbeans.validation.api.Problem;
import org.netbeans.validation.api.Problems;
import org.netbeans.validation.api.Validator;
import org.netbeans.validation.api.ValidatorUtils;
import org.netbeans.validation.api.builtin.stringvalidation.StringValidators;
/**
* A {@code ValidationGroup} logically groups a set of GUI-components,
* such as text fields, lists, tables, comboboxes etc, each validated
* by one or more validators (such as the built-in ones provided by
* the framework in {@link StringValidators}).
*
* Note: If you are validating Swing components, you will probably
* want to use {@link
* org.netbeans.validation.api.ui.swing.SwingValidationGroup} which contains
* convenience add methods for common Swing components, and performs
* Swing-specific threading correctness checks.
*
*
A {@code ValidationGroup} is typically associated with a panel
* containing GUI-components (such as a {@code JPanel} or {@code
* JDialog} in Swing). The idea with logically grouping GUI-components
* (as opposed to treating them completely separately) is to to
* indicate the most severe {@link Problem} in the panel (graded
* by {@link org.netbeans.validation.api.Severity}) -- the "lead
* problem" of the group -- to the user in various ways. Even if the
* user happens to currently be interacting with another GUI component
* that has no error in it, the lead problem of the panel/group will
* be visible to the user.
*
*
If there is more than one Problem that is the most severe (they
* have equal Severity) in the group of UI-components, then the one in
* the UI-component that has been most recently interacted with will
* be the lead problem.
*
*
The way for the {@code ValidationGroup} to show the lead
* problem in the UI is by using one or more instances of the {@link
* ValidationUI} interface. {@code ValidationUI} instances can be
* added by client code using the {@link
* #addUI(org.netbeans.validation.api.ui.ValidationUI) } method.
* One {@code ValidationUI} instance could indicate the lead
* problem for example by showing a message in some status
* bar. Another one could disable some OK-button (which could be
* suitable if the lead problems has {@code Severity.FATAL}) etc. All
* these {@code ValidationUI}s are updated whenever the lead problem
* of the group changes.
*
* If the ValidationGroup contains UI-components whose validity
* depends not only on their own state but on the state of each other
* as well, they can be said to have validity interdependencies. In
* such cases not only the state of each component needs to be
* validated, but the combination of components as well. This is done
* by passing a {@code GroupValidator} object when creating the
* ValidationGroup. For more on that, see {@link GroupValidator}.
*
*
Now, to add a GUI-component to the {@code ValidationGroup},
* client code would wrap it (together with the desired Validators)
* into a {@link ValidationListener} that is then added to the {@code
* ValidationGroup} using the {@link
* #addItem(org.netbeans.validation.api.ui.ValidationItem, boolean) } method. Note
* that this is the generic but perhaps inconvenient case -- the
* subclass {@link
* org.netbeans.validation.api.ui.swing.SwingValidationGroup} contains
* a number of {@code add}-methods for convenience, to simplify this
* procedure for common Swing components.
*
*
Each {@code ValidationListener} listens to suitable GUI-events
* (often key-press events or mouse-events). When such an event occurs
* the {@code ValidationListener} will perform revalidation and then
* notify its parent {@code ValidationGroup} so that it can reevaluate
* its lead problem.
*
*
Not only ValidationListener:s can be added to ValidationGroup,
* but so can other ValdiationGroups as well. (This is the reason why
* ValidationListener and ValidationGroup share a common superclass,
* {@link ValidationItem}, and that this is the type of the argument
* of {@code ValidationGroup#add}.) This is useful when there are two
* separate panels with their own {@code ValidationGroup}s, and one of
* the panels is (perhaps temporarily) to be embedded into the other.
* Whenever there is a change in one of the added child
* ValidationGroup's components, it will drive the UI(s) belonging to
* the parent group, as well as (optionally) its own. (The latter can
* be disabled by passing {@code true} as second parameter to {@link
* #addItem(org.netbeans.validation.api.ui.ValidationItem, boolean) }
* instead of {@code false}
*
*
*
The core functionality of the {@code ValidationGroup} with
* added {@code ValidationItem}:s works as follows:
*
*
*
* When an appropriate change in a UI component occurs, a {@code
* ValidationListener} will observe that and make sure the component
* is validated (by invoking the {@code Validator}(s)) and then
* decorate the UI component if there is a Problem in it. This is
* unless the ValidationListener is suspended, in which case nothing
* at all will happen, see {@link
* ValidationItem#runWithValidationSuspended }
*
* The ValidationListener will notify its parent ValidationGroup
* about the validation. If there was a fatal {@code Problem} in that
* UI component, then this will also become the lead problem of the
* whole group because it is the most recent of the most severe
* problems in the groups.
*
* If not, the most recent of the most severe of the problems of
* the UI components in the ValidationGroup will be the lead
* problem. (This does not involve actual revalidation of these
* components, the problem that occured when the component last
* triggered validation is assumed to still be there).
*
* When the lead problem of the ValidationGroup has been
* determined, the showProblem
method of the
* ValidationUI
:s of the group will be called. This may
* for example involve disabling an OK-button if the lead problem is
* fatal (and enabling it if not) and showing an error message. This
* is unless this ValidationGroup has been added "with disabled UI" to
* another ValidationGroup, in which case the Problem will not be
* shown in the ValidationUI.
*
* If this ValidationGroup has been added to another one then the
* parent is notified. The parent ValidationGroup will then check if
* its lead problem needs to be updated, update its ValidationUI:s
* accordingly (unless it has a disabled UI) and notify its parent if
* there is one -- and so on.
*
*
*
* @author Tim Boudreau
*/
public class ValidationGroup extends ValidationItem {
private final GroupValidator additionalGroupValidation;
private final List validationItems = new LinkedList();
private boolean isAncestorToSelf = false;
protected ValidationGroup(GroupValidator additionalGroupValidation, ValidationUI... ui) {
super(ui);
this.additionalGroupValidation = additionalGroupValidation;
if (ui == null) {
throw new NullPointerException ("UI null");
}
}
protected ValidationGroup(ValidationUI... ui) {
this(null, ui);
}
/**
* Create a new validation group
* @param ui Zero or more initial UIs which will display errors
* @return A validation group
*/
public static ValidationGroup create (ValidationUI... ui) {
return new ValidationGroup(ui);
}
/**
* Create a new validation group
* @param additionalGroupValidation
* @param ui Zero or more initial UIs which will display errors
* @return A validation group
*/
public static ValidationGroup create(GroupValidator additionalGroupValidation, ValidationUI... ui) {
return new ValidationGroup(additionalGroupValidation, ui);
}
/**
*
* @param
* @param
* @param comp
* @param validators
*/
public final void add (ComponentType comp, Validator... validators) {
this.addItem (ValidationListenerFactory.createValidationListener(comp, ValidationStrategy.DEFAULT, decorationFor(comp), ValidatorUtils.merge(validators)), false);
}
/**
*
* @param
* @param
* @param comp
* @param validator
*/
public final void add (ComponentType comp, Validator validator) {
this.addItem (ValidationListenerFactory.createValidationListener(comp, ValidationStrategy.DEFAULT, decorationFor(comp), validator), false);
}
protected ValidationUI decorationFor(T component) {
return ValidationUI.NO_OP;
}
/**
* Add a UI which should be called on validation of this group or
* any components within it.
*
*
This is useful in the case that you have multiple
* components which are provided separately and each want to
* respond to validation problems (for example, one UI controlling
* a dialog's OK button, another controlling display of error
* text).
*
* @param ui An implementation of ValidationUI
*/
@Override
public final void addUI(ValidationUI ui) {
super.addUI(ui);
}
/**
* Remove a delegate UI which is being controlled by this
* validation item. Will clear the UI from any Problem as well.
*
* @param ui The UI
*/
@Override
public final void removeUI(ValidationUI ui) {
super.removeUI(ui);
}
/**
* Adds a ValidationItem (i.e a ValidationListener or another
* ValidationGroup) to this ValidationGroup.
*
* The purpose of being able to disable a ValidationUI is so
* you can compose together reusable panels which have their own
* ValidationUI, but only let the outer ValidationUI show the lead
* problem when one is inside another. Typically, without the
* ability to turn off the inner panel's ValidationUI, when
* there's a problem in the inner panel the error message is going
* to be shown twice -- once at the bottom of the dialog and one
* in the middle of the screen inside the inner panel -- which would look bad.
*
*
Note that the subclass {@link
* org.netbeans.validation.api.ui.swing.SwingValidationGroup}
* contains a number of {@code add}-methods for convenience, to
* simplify this procedure for common Swing components
* @param validationItem item to add
* @param disableUI indicates that the validation UI of the parent panel
* should not be notified
*
*/
public final void addItem(ValidationItem validationItem, boolean disableUI){
if( validationItem.getParentValidationGroup() != null ){
throw new IllegalArgumentException("Added item already has parent group"); //NOI18N
}
validationItem.setParentValidationGroup(this, !disableUI);
// Add first in list to make this the most recent one,
// as if the user would have interacted with it.. (not sure about this,
// but shouldn't be a big deal..?)
validationItems.add(0, validationItem);
// A check to make sure a child validation group cannot have an
// ancestor of itself added to itself - i.e. preemptively avoid endless loops:
if( this.detectAncestryToSelf() ){
validationItems.remove(0);
validationItem.setParentValidationGroup(null, true);
throw new IllegalArgumentException("Ancestry to self"); //NOI18N
}
// This is like validationTriggered just happened for the added child.
// This is probably reasonable, because when a child that has a problem is added to a group,
// and this problem happens to be the worst problem in the group, the group UI should be updated.
if (!isSuspended()) {
/* Don't pass the child to update, because we do not want to update its UI (it has problably already done so itself)*/
update(false, null);
if (getParentValidationGroup() != null) {
getParentValidationGroup().validationTriggered(this);
} else {
showIfUIEnabled(this.getCurrentLeadProblem());
}
}
}
/**
* Intended to be used by {@link ValidationGroup#add(org.netbeans.validation.api.ui.ValidationItem) }
* to detect self-ancestry (fail-fast-detection of infinite loop problems)
* @return true if detected ancestry to self -- i.e bad news.
* @return false if good news
*/
boolean detectAncestryToSelf() {
if( isAncestorToSelf ) {
return true;
}
isAncestorToSelf = true;
boolean badNews = false;
if(getParentValidationGroup() != null){
badNews = getParentValidationGroup().detectAncestryToSelf();
}
isAncestorToSelf = false;
return badNews;
}
/**
* Removes a previously added ValidationItem (i.e a
* ValidationListener or another ValidationGroup) to this
* ValidationGroup.
*
*
If the ValidationItem to be removed has the current lead
* problem of the ValidationGroup, the ValidationGroup will remove
* that and evaluate a new lead problem
*
* @param validationItem item to remove
*/
public final void remove(ValidationItem validationItem) {
if( validationItems.remove(validationItem) ) {
validationItem.setParentValidationGroup(null, true);
if( this.getCurrentLeadProblem() != null && this.getCurrentLeadProblem() == validationItem.getCurrentLeadProblem() ){
if( !isSuspended() ) {
this.update( false, null );
if( getParentValidationGroup() != null ) {
getParentValidationGroup().validationTriggered(this);
} else {
showIfUIEnabled(this.getCurrentLeadProblem());
}
}
}
}
}
@Override
final void subtreeRevalidation(){
if (isSuspended()) {
return ;
}
update( true, null );
}
// Intended to be called from child ValidationItem that has triggered validation.
final void validationTriggered(final ValidationItem triggeringChild) {
// Never "touch" the trigger (do not call performValidation on it). The trigger takes care of itself.
assert triggeringChild != null;
assert !isSuspended(); // child should have noticed.
// Put trigger first in list, because it's the most recent trigger.
// This way, if there are more than one problem with
// equal severity, we ensure that the lead problem of this
// ValidationGroup (see update()) is always the more recent one (rather than an arbitary
// one)
validationItems.remove(triggeringChild);
validationItems.add(0, triggeringChild);
update( false, triggeringChild );
if( getParentValidationGroup() != null ) {
getParentValidationGroup().validationTriggered(this);
} else {
showIfUIEnabled(this.getCurrentLeadProblem());
}
}
private void update(final boolean childrenShallPerformValidation, final ValidationItem triggerThatHasAlreadyPerformedValidation) {
assert !isSuspended();
assert ! ( childrenShallPerformValidation && triggerThatHasAlreadyPerformedValidation!=null ); // This would be unexpected
final Problems ps = new Problems();
// Iterate from first to last, so that the most recent problems will be
// added first to the Problems. Problems.getLeadProblem() will return:
// (1) the most severe problem,
// (2) the problem *added* first (the one triggered most recently)
if (childrenShallPerformValidation) {
for (ValidationItem vi : validationItems) {
if (vi != triggerThatHasAlreadyPerformedValidation) {
vi.subtreeRevalidation();
}
ps.add(vi.getCurrentLeadProblem());
}
} else {
for (ValidationItem vi : validationItems) {
final Problem p = vi.getCurrentLeadProblem();
ps.add(p);
if( p != null && p.isFatal() ){
break; // Optimization: We already found a fatal problem, no need to keep looking.
}
}
}
Problem leadProblem = ps.getLeadProblem();
boolean haveUpdatedRelevantChildrenUI = false;
if (additionalGroupValidation != null) {
boolean theAdditionalProblemIsLeading = false;
if (leadProblem == null || !leadProblem.isFatal()) {
additionalGroupValidation.performGroupValidation(ps);
final Problem nue = ps.getLeadProblem();
if (nue != null && !nue.equals(leadProblem)) {
theAdditionalProblemIsLeading = true;
leadProblem = nue;
}
}
if (additionalGroupValidation.shallShowProblemInChildrenUIs()) {
if (theAdditionalProblemIsLeading) {
for (ValidationItem vi : validationItems) {
vi.showIfUIEnabled(leadProblem);
}
haveUpdatedRelevantChildrenUI = true;
} else if(additionalGroupValidation.isCurrentlyLeadingProblem()) {
// The "additional" problem of this group has been showing
// in the children UI:s (and it's time to overwrite it with
// each childs own respective Problem)
for (ValidationItem vi : validationItems) {
vi.showIfUIEnabled(vi.getCurrentLeadProblem());
}
haveUpdatedRelevantChildrenUI = true;
}
additionalGroupValidation.setIsCurrentlyLeadingProblem(theAdditionalProblemIsLeading);
}
}
if ( !haveUpdatedRelevantChildrenUI ){
if( triggerThatHasAlreadyPerformedValidation != null ) {
triggerThatHasAlreadyPerformedValidation.showIfUIEnabled(triggerThatHasAlreadyPerformedValidation.getCurrentLeadProblem());
} else if (childrenShallPerformValidation) {
for (ValidationItem vi : validationItems) {
vi.showIfUIEnabled(vi.getCurrentLeadProblem());
}
}
}
super.setCurrentLeadProblem(leadProblem);
}
}
././@LongLink 0000000 0000000 0000000 00000000151 00000000000 011562 L ustar root root libsimple-validation-java-.orig/org/netbeans/validation/api/ui/JTextComponentValidationListenerImpl.java libsimple-validation-java-.orig/org/netbeans/validation/api/ui/JTextComponentValidationListenerImpl.0000644 0001750 0001750 00000012717 11654612134 033073 0 ustar tony tony /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.validation.api.ui;
import org.netbeans.validation.api.ui.*;
import java.awt.EventQueue;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import org.netbeans.validation.api.Problems;
import org.netbeans.validation.api.Validator;
import org.netbeans.validation.api.ui.swing.SwingValidationGroup;
import org.netbeans.validation.api.ui.swing.SwingValidationGroup;
/**
*
* @author Tim Boudreau
*/
class JTextComponentValidationListenerImpl extends ValidationListener
implements DocumentListener, FocusListener, Runnable {
private Validator validator;
private boolean hasFatalProblem = false;
public JTextComponentValidationListenerImpl(JTextComponent component,
ValidationStrategy strategy,
ValidationUI validationUI,
Validator validator
) {
super(JTextComponent.class, validationUI, component);
this.validator = validator;
if (strategy == null) {
throw new NullPointerException("strategy null");
}
component.addPropertyChangeListener("enabled", new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
performValidation();
}
});
switch (strategy) {
case DEFAULT:
case ON_CHANGE_OR_ACTION:
component.getDocument().addDocumentListener(this);
break;
case INPUT_VERIFIER:
component.setInputVerifier( new InputVerifier() {
@Override
public boolean verify(JComponent input) {
performValidation();
return !hasFatalProblem;
}
});
break;
case ON_FOCUS_LOSS:
component.addFocusListener(this);
break;
}
performValidation(); // Make sure any initial errors are discovered immediately.
}
@Override
protected final void performValidation(Problems ps){
JTextComponent component = getTarget();
if (!component.isEnabled()) {
return;
}
validator.validate(ps, SwingValidationGroup.nameForComponent(component), component.getDocument());
hasFatalProblem = ps.hasFatal();
}
@Override
public void focusLost(FocusEvent e) {
performValidation();
}
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void insertUpdate(DocumentEvent e) {
removeUpdate(e);
}
@Override
public void removeUpdate(DocumentEvent e) {
//Documents can be legally updated from another thread,
//but we will not run validation outside the EDT
if (!EventQueue.isDispatchThread()) {
EventQueue.invokeLater(this);
} else {
performValidation();
}
}
@Override
public void changedUpdate(DocumentEvent e) {
removeUpdate(e);
}
// See removeUpdate..
@Override
public void run() {
performValidation();
}
}
libsimple-validation-java-.orig/org/netbeans/validation/api/warning.png 0000644 0001750 0001750 00000001133 11654612134 025332 0 ustar tony tony PNG
IHDR a gAMA 7 tEXtSoftware Adobe ImageReadyqe<