Java/Swing Components/Data Validation
Содержание
- 1 Component Hints Example
- 2 Different configurations of JFormattedTextField
- 3 different configurations of JFormattedTextField: Number
- 4 Different styles how to indicate that a component contains invalid data
- 5 Different styles to mark mandatory fields
- 6 Different validation result views
- 7 different validation times: key-typed, focus lost, commit (OK pressed)
- 8 Error Dialog Example
- 9 Field List Validator Example
- 10 how to provide input hints
- 11 Info Assist Example
- 12 Input Verifier Example
- 13 Validating Domain Object Example
- 14 Validating On Focus Lost Example
- 15 Validating On Key Typed Example
- 16 Validating Presentation Model Example
- 17 Validation How to Example
- 18 Validation Icons Example
- 19 Validation Results View Example
Component Hints Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.jgoodies.binding.PresentationModel;
import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.validation.ValidationCapable;
import com.jgoodies.validation.ValidationResult;
import com.jgoodies.validation.util.DefaultValidationResultModel;
import com.jgoodies.validation.util.PropertyValidationSupport;
import com.jgoodies.validation.util.ValidationResultModel;
import com.jgoodies.validation.util.ValidationUtils;
import com.jgoodies.validation.view.ValidationComponentUtils;
import com.jgoodies.validation.view.ValidationResultViewFactory;
public class ComponentHintsExample extends JPanel {
private Feed feed;
private FeedPresentationModel feedPresentationModel;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
private JComponent iconPanel;
private ValidationResultModel validationModel;
public ComponentHintsExample() {
this.validationModel = new DefaultValidationResultModel();
createFeed();
this.feedPresentationModel = new FeedPresentationModel(this.feed);
ValueModel nameModel = this.feedPresentationModel.getModel("name");
DefaultFormBuilder formBuilder1 = new DefaultFormBuilder(new FormLayout("right:pref, 3dlu, p:g"));
JTextField nameField1 = BasicComponentFactory.createTextField(nameModel, false);
ValidationComponentUtils.setMandatory(nameField1, true);
ValidationComponentUtils.setMessageKey(nameField1, "form.name_key");
formBuilder1.append("Name:", nameField1);
DefaultFormBuilder formBuilder2 = new DefaultFormBuilder(new FormLayout("right:pref, 3dlu, p:g"));
JTextField nameField2 = BasicComponentFactory.createTextField(nameModel, false);
ValidationComponentUtils.setMandatory(nameField2, true);
ValidationComponentUtils.setMessageKey(nameField2, "form.name_key");
formBuilder2.append("Name:", nameField2);
DefaultFormBuilder formBuilder3 = new DefaultFormBuilder(new FormLayout("right:pref, 3dlu, p:g"));
JTextField nameField3 = BasicComponentFactory.createTextField(nameModel, false);
ValidationComponentUtils.setMandatory(nameField3, true);
ValidationComponentUtils.setMessageKey(nameField3, "form.name_key");
formBuilder3.append("Name:", nameField3);
DefaultFormBuilder formBuilder4 = new DefaultFormBuilder(new FormLayout("right:pref, 4dlu, p:g"));
JTextField nameField4 = BasicComponentFactory.createTextField(nameModel, false);
ValidationComponentUtils.setMandatory(nameField4, true);
ValidationComponentUtils.setMessageKey(nameField4, "form.name_key");
formBuilder4.append("Name:", nameField4);
//Padding for overlay icon
formBuilder4.appendRow("5dlu");
this.panel1 = formBuilder1.getPanel();
this.panel2 = formBuilder2.getPanel();
this.panel3 = formBuilder3.getPanel();
this.iconPanel = new IconFeedbackPanel(this.validationModel, formBuilder4.getPanel());
PanelBuilder builder = new PanelBuilder(new FormLayout("p:g"));
builder.setDefaultDialogBorder();
builder.appendRow("p");
builder.add(this.panel1);
builder.nextLine();
builder.appendRow("p");
builder.add(this.panel2);
builder.nextLine();
builder.appendRow("p");
builder.add(this.panel3);
builder.nextLine();
builder.appendRow("4dlu");
builder.nextLine();
builder.appendRow("p");
builder.add(this.iconPanel);
builder.nextLine();
builder.appendRow("4dlu");
builder.nextLine();
builder.appendRow("p:g");
builder.nextLine();
builder.appendRow("p");
builder.addLabel("Results");
builder.nextLine();
builder.appendRow("50dlu");
builder.add(ValidationResultViewFactory.createReportList(this.validationModel));
add(builder.getPanel());
}
private void createFeed() {
this.feed = new Feed();
this.feed.setName("ClientJava.ru");
this.feed.setSiteUrl("http://www.clientjava.ru/blog");
this.feed.setFeedUrl("http://www.clientjava.ru/blog/rss.xml");
}
public class FeedPresentationModel extends PresentationModel implements ValidationCapable {
private ValidationResultModel validationResultModel;
public FeedPresentationModel(Object bean) {
super(bean);
this.validationResultModel = new DefaultValidationResultModel();
initEventHandling();
}
public ValidationResultModel getValidationModel() {
return this.validationResultModel;
}
public ValidationResult validate() {
PropertyValidationSupport support = new PropertyValidationSupport(feed, "form");
String name = (String) getModel("name").getValue();
if (!ValidationUtils.isEmpty(name)) {
if (!"ClientJava.ru".equals(name)) {
support.addWarning("name_key", "is not ClientJava.ru");
}
if (name.length() < 5) {
support.addError("name_key", "must be more than 4 characters long.");
}
}
return support.getResult();
}
private void initEventHandling() {
PropertyChangeListener handler = new ValueUpdateHandler();
addBeanPropertyChangeListener(handler);
getBeanChannel().addValueChangeListener(handler);
}
public class ValueUpdateHandler implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
updateComponents();
}
private void updateComponents() {
ValidationResult result = validate();
validationModel.setResult(result);
ValidationComponentUtils.updateComponentTreeMandatoryAndBlankBackground(panel1);
ValidationComponentUtils.updateComponentTreeMandatoryBackground(panel2);
ValidationComponentUtils.updateComponentTreeMandatoryBorder(panel3);
ValidationComponentUtils.updateComponentTreeValidationBackground(panel1, result);
}
}
}
public static void main(String[] a){
JFrame f = new JFrame("Component Hints Example");
f.setDefaultCloseOperation(2);
f.add(new ComponentHintsExample());
f.pack();
f.setVisible(true);
}
}
Different configurations of JFormattedTextField
/*
* Copyright (c) 2003-2005 JGoodies Karsten Lentzsch. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* o Neither the name of JGoodies Karsten Lentzsch nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jgoodies.validation.tutorial.formatted;
import java.text.DateFormat;
import java.text.Format;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.swing.*;
import javax.swing.text.DateFormatter;
import javax.swing.text.DefaultFormatter;
import javax.swing.text.DefaultFormatterFactory;
import com.jgoodies.binding.value.ValueHolder;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.validation.formatter.EmptyDateFormatter;
import com.jgoodies.validation.formatter.RelativeDateFormatter;
import com.jgoodies.validation.tutorial.formatted.format.DisplayFormat;
import com.jgoodies.validation.tutorial.formatted.format.RelativeDateFormat;
import com.jgoodies.validation.tutorial.util.ExampleComponentFactory;
import com.jgoodies.validation.tutorial.util.MyFocusTraversalPolicy;
import com.jgoodies.validation.tutorial.util.TutorialUtils;
/**
* Demonstrates different configurations of <code>JFormattedTextField</code>
* to display and edit numbers. Shows <ul>
* <li>how to use a custom DateFormat
* <li>how to use a custom DateFormatter
* <li>how to use a custom FormatterFactory
* <li>how to reset a date to <code>null</code>
* <li>how to map the empty string to a special date
* <li>how to commit values on valid texts
* </ul><p>
*
* To look under the hood of this component, this class exposes
* the bound properties <em>text</em>, <em>value</em> and <em>editValid</em>.
*
* @author Karsten Lentzsch
* @version $Revision: 1.8 $
*
* @see JFormattedTextField
* @see JFormattedTextField.AbstractFormatter
*/
public class DateExample {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
} catch (Exception e) {
// Likely Plastic is not in the classpath; ignore it.
}
JFrame frame = new JFrame();
frame.setTitle("Formatted :: Dates");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JComponent panel = new DateExample()
.buildPanel();
frame.getContentPane().add(panel);
frame.pack();
TutorialUtils.locateOnScreenCenter(frame);
frame.setVisible(true);
}
/**
* Builds and returns a panel with a header row and the sample rows.
*
* @return the example panel with a header and the sample rows
*/
public JComponent buildPanel() {
FormLayout layout = new FormLayout(
"r:max(80dlu;pref), 4dlu, 45dlu, 1dlu, pref, 4dlu, pref, 0:grow");
DefaultFormBuilder builder = new DefaultFormBuilder(layout);
builder.setDefaultDialogBorder();
builder.getPanel().setFocusTraversalPolicy(
MyFocusTraversalPolicy.INSTANCE);
Utils.appendTitleRow(builder, "Description");
List fields = appendDemoRows(builder);
String validText = DateFormat.getDateInstance().format(new Date(67, 11, 5));
String invalidText = "aa" + validText;
Utils.appendButtonBar(builder, fields, validText, invalidText);
return builder.getPanel();
}
/**
* Appends the demo rows to the given builder and returns the List of
* formatted text fields.
*
* @param builder the builder used to add components to
* @return the List of formatted text fields
*/
private List appendDemoRows(DefaultFormBuilder builder) {
// The Formatter is choosen by the initial value.
JFormattedTextField defaultDateField =
new JFormattedTextField(new Date());
// The Formatter is choosen by the given Format.
JFormattedTextField noInitialValueField =
new JFormattedTextField(DateFormat.getDateInstance());
// Uses a custom DateFormat.
DateFormat customFormat = DateFormat.getDateInstance(DateFormat.SHORT);
JFormattedTextField customFormatField =
new JFormattedTextField(new DateFormatter(customFormat));
// Uses a RelativeDateFormat.
DateFormat relativeFormat = new RelativeDateFormat();
JFormattedTextField relativeFormatField =
new JFormattedTextField(new DateFormatter(relativeFormat));
// Uses a custom DateFormatter that allows relative input and
// prints natural language strings.
JFormattedTextField relativeFormatterField =
new JFormattedTextField(new RelativeDateFormatter());
// Uses a custom FormatterFactory that used different formatters
// for the display and while editing.
DefaultFormatterFactory formatterFactory =
new DefaultFormatterFactory(new RelativeDateFormatter(false, true),
new RelativeDateFormatter(true, true));
JFormattedTextField relativeFactoryField =
new JFormattedTextField(formatterFactory);
// Wraps a DateFormatter to map empty strings to null and vice versa.
JFormattedTextField numberOrNullField =
new JFormattedTextField(new EmptyDateFormatter());
// Wraps a DateFormatter to map empty strings to -1 and vice versa.
Date epoch = new Date(0); // January 1, 1970
JFormattedTextField numberOrEmptyValueField =
new JFormattedTextField(new EmptyDateFormatter(epoch));
numberOrEmptyValueField.setValue(epoch);
// Commits value on valid edit text
DefaultFormatter formatter = new RelativeDateFormatter();
formatter.setCommitsOnValidEdit(true);
JFormattedTextField commitOnValidEditField =
new JFormattedTextField(formatter);
// A date field as created by the BasicComponentFactory:
// Uses relative date input, and maps empty strings to null.
ValueModel dateHolder = new ValueHolder();
JFormattedTextField componentFactoryField =
ExampleComponentFactory.createDateField(dateHolder);
Format displayFormat = new DisplayFormat(DateFormat.getDateInstance());
List fields = new LinkedList();
fields.add(Utils.appendRow(builder, "Default", defaultDateField, displayFormat));
fields.add(Utils.appendRow(builder, "No initial value", noInitialValueField, displayFormat));
fields.add(Utils.appendRow(builder, "Empty <-> null", numberOrNullField, displayFormat));
fields.add(Utils.appendRow(builder, "Empty <-> epoch", numberOrEmptyValueField, displayFormat));
fields.add(Utils.appendRow(builder, "Short format", customFormatField, displayFormat));
fields.add(Utils.appendRow(builder, "Relative format", relativeFormatField, displayFormat));
fields.add(Utils.appendRow(builder, "Relative formatter", relativeFormatterField, displayFormat));
fields.add(Utils.appendRow(builder, "Relative factory", relativeFactoryField, displayFormat));
fields.add(Utils.appendRow(builder, "Commits on valid edit", commitOnValidEditField, displayFormat));
fields.add(Utils.appendRow(builder, "Relative, maps null", componentFactoryField, displayFormat));
return fields;
}
}
different configurations of JFormattedTextField: Number
/*
* Copyright (c) 2003-2005 JGoodies Karsten Lentzsch. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* o Neither the name of JGoodies Karsten Lentzsch nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jgoodies.validation.tutorial.formatted;
import java.text.Format;
import java.text.NumberFormat;
import java.util.LinkedList;
import java.util.List;
import javax.swing.*;
import javax.swing.text.DefaultFormatter;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.NumberFormatter;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.validation.formatter.EmptyNumberFormatter;
import com.jgoodies.validation.tutorial.formatted.format.DisplayFormat;
import com.jgoodies.validation.tutorial.formatted.formatter.CustomNumberFormatter;
import com.jgoodies.validation.tutorial.util.MyFocusTraversalPolicy;
import com.jgoodies.validation.tutorial.util.TutorialUtils;
/**
* Demonstrates different configurations of <code>JFormattedTextField</code>
* to display and edit numbers. Shows<ul>
* <li>how to use a custom NumberFormat
* <li>how to use a custom NumberFormatter
* <li>how to use a custom FormatterFactory
* <li>how to reset a number to <code>null</code>
* <li>how to map the empty string to a special number
* <li>how to commit values on valid texts
* <li>how to set the class of the result
* </ul><p>
*
* To look under the hood of this component, this class exposes
* the bound properties <em>text</em>, <em>value</em> and <em>editValid</em>.
*
* @author Karsten Lentzsch
* @version $Revision: 1.9 $
*
* @see JFormattedTextField
* @see JFormattedTextField.AbstractFormatter
*/
public class NumberExample {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
} catch (Exception e) {
// Likely Plastic is not in the classpath; ignore it.
}
JFrame frame = new JFrame();
frame.setTitle("Formatted :: Numbers");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JComponent panel = new NumberExample()
.buildPanel();
frame.getContentPane().add(panel);
frame.pack();
TutorialUtils.locateOnScreenCenter(frame);
frame.setVisible(true);
}
/**
* Builds and returns a panel with a header row and the sample rows.
*
* @return the example panel with a header and the sample rows
*/
public JComponent buildPanel() {
FormLayout layout = new FormLayout(
"r:max(80dlu;pref), 4dlu, 45dlu, 1dlu, pref, 4dlu, pref, 0:grow");
DefaultFormBuilder builder = new DefaultFormBuilder(layout);
builder.setDefaultDialogBorder();
builder.getPanel().setFocusTraversalPolicy(
MyFocusTraversalPolicy.INSTANCE);
Utils.appendTitleRow(builder, "Description");
List fields = appendDemoRows(builder);
Utils.appendButtonBar(builder, fields, "42", "aa42");
return builder.getPanel();
}
/**
* Appends the demo rows to the given builder and returns the List of
* formatted text fields.
*
* @param builder the builder used to add components to
* @return the List of formatted text fields
*/
private List appendDemoRows(DefaultFormBuilder builder) {
// The Formatter is choosen by the initial value.
JFormattedTextField defaultNumberField =
new JFormattedTextField(new Long(42));
// The Formatter is choosen by the given Format.
JFormattedTextField noInitialValueField =
new JFormattedTextField(NumberFormat.getIntegerInstance());
// Uses a custom NumberFormat.
NumberFormat customFormat = NumberFormat.getIntegerInstance();
customFormat.setMinimumIntegerDigits(3);
JFormattedTextField customFormatField =
new JFormattedTextField(new NumberFormatter(customFormat));
// Uses a custom NumberFormatter that prints natural language strings.
JFormattedTextField customFormatterField =
new JFormattedTextField(new CustomNumberFormatter());
// Uses a custom FormatterFactory that used different formatters
// for the display and while editing.
DefaultFormatterFactory formatterFactory =
new DefaultFormatterFactory(new NumberFormatter(),
new CustomNumberFormatter());
JFormattedTextField formatterFactoryField =
new JFormattedTextField(formatterFactory);
// Wraps a NumberFormatter to map empty strings to null and vice versa.
JFormattedTextField numberOrNullField =
new JFormattedTextField(new EmptyNumberFormatter());
// Wraps a NumberFormatter to map empty strings to -1 and vice versa.
Integer emptyValue = new Integer(-1);
JFormattedTextField numberOrEmptyValueField =
new JFormattedTextField(new EmptyNumberFormatter(emptyValue));
numberOrEmptyValueField.setValue(emptyValue);
// Commits values on valid edit texts.
DefaultFormatter formatter = new NumberFormatter();
formatter.setCommitsOnValidEdit(true);
JFormattedTextField commitOnValidEditField =
new JFormattedTextField(formatter);
// Returns number values of type Integer
NumberFormatter numberFormatter = new NumberFormatter();
numberFormatter.setValueClass(Integer.class);
JFormattedTextField integerField =
new JFormattedTextField(numberFormatter);
Format displayFormat = new DisplayFormat(NumberFormat.getIntegerInstance());
Format typedDisplayFormat = new DisplayFormat(NumberFormat.getIntegerInstance(), true);
List fields = new LinkedList();
fields.add(Utils.appendRow(builder, "Default", defaultNumberField, typedDisplayFormat));
fields.add(Utils.appendRow(builder, "No initial value", noInitialValueField, displayFormat));
fields.add(Utils.appendRow(builder, "Empty <-> null", numberOrNullField, displayFormat));
fields.add(Utils.appendRow(builder, "Empty <-> -1", numberOrEmptyValueField, displayFormat));
fields.add(Utils.appendRow(builder, "Custom format", customFormatField, displayFormat));
fields.add(Utils.appendRow(builder, "Custom formatter", customFormatterField, displayFormat));
fields.add(Utils.appendRow(builder, "Formatter factory", formatterFactoryField, displayFormat));
fields.add(Utils.appendRow(builder, "Commits on valid edit", commitOnValidEditField, displayFormat));
fields.add(Utils.appendRow(builder, "Integer Result", integerField, typedDisplayFormat));
return fields;
}
}
Different styles how to indicate that a component contains invalid data
/*
* Copyright (c) 2003-2005 JGoodies Karsten Lentzsch. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* o Neither the name of JGoodies Karsten Lentzsch nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jgoodies.validation.tutorial.basics;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.validation.ValidationResult;
import com.jgoodies.validation.tutorial.shared.Order;
import com.jgoodies.validation.tutorial.shared.OrderModel;
import com.jgoodies.validation.tutorial.util.ExampleComponentFactory;
import com.jgoodies.validation.tutorial.util.IconFeedbackPanel;
import com.jgoodies.validation.tutorial.util.TutorialUtils;
import com.jgoodies.validation.util.ValidationResultModel;
import com.jgoodies.validation.view.ValidationComponentUtils;
/**
* Demonstrates different styles how to indicate that a component
* contains invalid data:
* background changes if empty,
* background reflects the severity,
* overlayed icons the reflect the severity.
*
* @author Karsten Lentzsch
* @version $Revision: 1.8 $
*/
public class ComponentFeedbackExample {
private final OrderModel orderModel;
private JTextField mandatoryOrderNoField;
private JTextField mandatoryOrderDateField;
private JTextField mandatoryDeliveryDateField;
private JTextArea mandatoryDeliveryNotesArea;
private JComponent mandatoryPanel;
private JTextField severityOrderNoField;
private JTextField severityOrderDateField;
private JTextField severityDeliveryDateField;
private JTextArea severityDeliveryNotesArea;
private JComponent severityPanel;
private JTextField iconOrderNoField;
private JTextField iconOrderDateField;
private JTextField iconDeliveryDateField;
private JTextArea iconDeliveryNotesArea;
private JComponent iconOverlayPanel;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
} catch (Exception e) {
// Likely Plastic is not in the classpath; ignore it.
}
JFrame frame = new JFrame();
frame.setTitle("Basics :: Component Feedback");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JComponent panel = new ComponentFeedbackExample().buildPanel();
frame.getContentPane().add(panel);
frame.pack();
TutorialUtils.locateOnScreenCenter(frame);
frame.setVisible(true);
}
// Instance Creation ******************************************************
public ComponentFeedbackExample() {
orderModel = new OrderModel(new Order());
}
// Component Creation and Initialization **********************************
private void initComponents() {
mandatoryOrderNoField = ExampleComponentFactory.createTextField(
orderModel.getModel(Order.PROPERTYNAME_ORDER_NO), false);
mandatoryOrderDateField = ExampleComponentFactory.createDateField(
orderModel.getModel(Order.PROPERTYNAME_ORDER_DATE),
true);
mandatoryDeliveryDateField = ExampleComponentFactory.createDateField(
orderModel.getModel(Order.PROPERTYNAME_DELIVERY_DATE),
true);
mandatoryDeliveryNotesArea = ExampleComponentFactory.createTextArea(
orderModel.getModel(Order.PROPERTYNAME_DELIVERY_NOTES), false);
severityOrderNoField = ExampleComponentFactory.createTextField(
orderModel.getModel(Order.PROPERTYNAME_ORDER_NO), false);
severityOrderDateField = ExampleComponentFactory.createDateField(
orderModel.getModel(Order.PROPERTYNAME_ORDER_DATE));
severityDeliveryDateField = ExampleComponentFactory.createDateField(
orderModel.getModel(Order.PROPERTYNAME_DELIVERY_DATE),
true);
severityDeliveryNotesArea = ExampleComponentFactory.createTextArea(
orderModel.getModel(Order.PROPERTYNAME_DELIVERY_NOTES), false);
iconOrderNoField = ExampleComponentFactory.createTextField(
orderModel.getModel(Order.PROPERTYNAME_ORDER_NO), false);
iconOrderDateField = ExampleComponentFactory.createDateField(
orderModel.getModel(Order.PROPERTYNAME_ORDER_DATE));
iconDeliveryDateField = ExampleComponentFactory.createDateField(
orderModel.getModel(Order.PROPERTYNAME_DELIVERY_DATE),
true);
iconDeliveryNotesArea = ExampleComponentFactory.createTextArea(
orderModel.getModel(Order.PROPERTYNAME_DELIVERY_NOTES), false);
}
private void initComponentAnnotations() {
ValidationComponentUtils.setMandatory(mandatoryOrderNoField, true);
ValidationComponentUtils.setMessageKey(mandatoryOrderNoField, "Order.Order No");
ValidationComponentUtils.setMandatory(mandatoryOrderDateField, true);
ValidationComponentUtils.setMessageKey(mandatoryOrderDateField, "Order.Order Date");
ValidationComponentUtils.setMessageKey(mandatoryDeliveryDateField, "Order.Delivery Date");
ValidationComponentUtils.setMessageKey(mandatoryDeliveryNotesArea, "Order.Notes");
ValidationComponentUtils.setMandatory(severityOrderNoField, true);
ValidationComponentUtils.setMessageKey(severityOrderNoField, "Order.Order No");
ValidationComponentUtils.setMandatory(severityOrderDateField, true);
ValidationComponentUtils.setMessageKey(severityOrderDateField, "Order.Order Date");
ValidationComponentUtils.setMessageKey(severityDeliveryDateField, "Order.Delivery Date");
ValidationComponentUtils.setMessageKey(severityDeliveryNotesArea, "Order.Notes");
ValidationComponentUtils.setMandatory(iconOrderNoField, true);
ValidationComponentUtils.setMessageKey(iconOrderNoField, "Order.Order No");
ValidationComponentUtils.setMandatory(iconOrderDateField, true);
ValidationComponentUtils.setMessageKey(iconOrderDateField, "Order.Order Date");
ValidationComponentUtils.setMessageKey(iconDeliveryDateField, "Order.Delivery Date");
ValidationComponentUtils.setMessageKey(iconDeliveryNotesArea, "Order.Notes");
}
private void initEventHandling() {
orderModel.getValidationResultModel().addPropertyChangeListener(
ValidationResultModel.PROPERTYNAME_RESULT,
new ValidationChangeHandler());
}
// Building ***************************************************************
/**
* Builds and returns the whole editor with 3 sections
* for the different validation times.
*/
public JComponent buildPanel() {
initComponents();
initComponentAnnotations();
initEventHandling();
mandatoryPanel = buildMandatoryPanel();
severityPanel = buildSeverityPanel();
iconOverlayPanel = buildIconOverlayPanel();
FormLayout layout = new FormLayout(
"fill:pref:grow",
"p, 3dlu, p, 17dlu, p, 3dlu, p, 17dlu, p, 3dlu, p");
PanelBuilder builder = new PanelBuilder(layout);
builder.setDefaultDialogBorder();
CellConstraints cc = new CellConstraints();
builder.addSeparator("Background Indicates Blank Mandatory Fields", cc.xy(1, 1));
builder.add(mandatoryPanel, cc.xy(1, 3));
builder.addSeparator("Background Indicates Invalid Input", cc.xy(1, 5));
builder.add(severityPanel, cc.xy(1, 7));
builder.addSeparator("Icons Indicate Invalid Input", cc.xy(1, 9));
builder.add(iconOverlayPanel, cc.xy(1, 11));
// Synchronize the presentation with the current validation state.
// If you want to show no validation info before the user has typed
// anything in the form, use the commented EMPTY result
// instead of the model"s validation result.
updateComponentTreeMandatoryAndSeverity(
orderModel.getValidationResultModel().getResult()
// ValidationResult.EMPTY
);
return builder.getPanel();
}
private JComponent buildMandatoryPanel() {
FormLayout layout = new FormLayout(
"right:max(65dlu;pref), 4dlu, 40dlu, 2dlu, 40dlu, 80dlu:grow",
"p, 3dlu, p, 3dlu, p, 3dlu, p");
layout.setRowGroups(new int[][]{{1, 3, 5, 7}});
PanelBuilder builder = new PanelBuilder(layout);
CellConstraints cc = new CellConstraints();
builder.addLabel("Order No", cc.xy (1, 1));
builder.add(mandatoryOrderNoField, cc.xyw (3, 1, 3));
builder.addLabel("Order-/Delivery Date", cc.xy (1, 3));
builder.add(mandatoryOrderDateField, cc.xy (3, 3));
builder.add(mandatoryDeliveryDateField, cc.xy (5, 3));
builder.add(new JScrollPane(mandatoryDeliveryNotesArea),
cc.xywh(3, 5, 4, 3));
return builder.getPanel();
}
private JComponent buildSeverityPanel() {
FormLayout layout = new FormLayout(
"right:max(65dlu;pref), 4dlu, 40dlu, 2dlu, 40dlu, 80dlu:grow",
"p, 3dlu, p, 3dlu, p, 3dlu, p");
layout.setRowGroups(new int[][]{{1, 3, 5, 7}});
PanelBuilder builder = new PanelBuilder(layout);
CellConstraints cc = new CellConstraints();
builder.addLabel("Order No", cc.xy (1, 1));
builder.add(severityOrderNoField, cc.xyw (3, 1, 3));
builder.addLabel("Order-/Delivery Date", cc.xy (1, 3));
builder.add(severityOrderDateField, cc.xy (3, 3));
builder.add(severityDeliveryDateField, cc.xy (5, 3));
builder.add(new JScrollPane(severityDeliveryNotesArea),
cc.xywh(3, 5, 4, 3));
return builder.getPanel();
}
private JComponent buildIconOverlayPanel() {
FormLayout layout = new FormLayout(
"right:max(65dlu;pref), 4dlu, 40dlu, 2dlu, 40dlu, 80dlu:grow",
"p, 3dlu, p, 3dlu, p, 3dlu, p, 4px"); // extra bottom space for icons
layout.setRowGroups(new int[][]{{1, 3, 5, 7}});
PanelBuilder builder = new PanelBuilder(layout);
CellConstraints cc = new CellConstraints();
builder.addLabel("Order No", cc.xy (1, 1));
builder.add(iconOrderNoField, cc.xyw (3, 1, 3));
builder.addLabel("Order-/Delivery Date", cc.xy (1, 3));
builder.add(iconOrderDateField, cc.xy (3, 3));
builder.add(iconDeliveryDateField, cc.xy (5, 3));
builder.addLabel("Notes", cc.xy (1, 5));
builder.add(new JScrollPane(iconDeliveryNotesArea),
cc.xywh(3, 5, 4, 3));
return new IconFeedbackPanel(
orderModel.getValidationResultModel(),
builder.getPanel()
);
}
// Event Handling *********************************************************
private void updateComponentTreeMandatoryAndSeverity(ValidationResult result) {
ValidationComponentUtils.updateComponentTreeMandatoryAndBlankBackground(
mandatoryPanel);
ValidationComponentUtils.updateComponentTreeSeverityBackground(
severityPanel,
result);
}
/**
* Updates the component background in the mandatory panel and the
* validation background in the severity panel. Invoked whenever
* the observed validation result changes.
*/
private class ValidationChangeHandler implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
updateComponentTreeMandatoryAndSeverity(
(ValidationResult) evt.getNewValue());
}
}
}
Different styles to mark mandatory fields
/*
* Copyright (c) 2003-2005 JGoodies Karsten Lentzsch. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* o Neither the name of JGoodies Karsten Lentzsch nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jgoodies.validation.tutorial.basics;
import javax.swing.*;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.validation.tutorial.util.TutorialUtils;
import com.jgoodies.validation.view.ValidationComponentUtils;
/**
* Demonstrates different styles how to mark mandatory fields.
* The fields in this demo are not bound and not validated.
*
* @author Karsten Lentzsch
* @version $Revision: 1.4 $
*/
public class MandatoryMarkerExample {
private JLabel orderNoLabel;
private JLabel orderDateLabel;
private JTextField backgroundOrderNoField;
private JTextField backgroundOrderDateField;
private JTextField backgroundDeliveryDateField;
private JTextField borderOrderNoField;
private JTextField borderOrderDateField;
private JTextField borderDeliveryDateField;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
} catch (Exception e) {
// Likely Plastic is not in the classpath; ignore it.
}
JFrame frame = new JFrame();
frame.setTitle("Basics :: Mandatory Marker");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JComponent panel = new MandatoryMarkerExample().buildPanel();
frame.getContentPane().add(panel);
frame.pack();
TutorialUtils.locateOnScreenCenter(frame);
frame.setVisible(true);
}
// Component Creation and Initialization **********************************
private void initComponents() {
orderNoLabel = createMandatoryLabel("Order No");
orderDateLabel = createMandatoryLabel("Order-");
backgroundOrderNoField = new JTextField();
backgroundOrderDateField = new JTextField();
backgroundDeliveryDateField = new JTextField();
borderOrderNoField = new JTextField();
borderOrderDateField = new JTextField();
borderDeliveryDateField = new JTextField();
}
private void initComponentAnnotations() {
ValidationComponentUtils.setMandatory(backgroundOrderNoField, true);
ValidationComponentUtils.setMandatory(backgroundOrderDateField, true);
ValidationComponentUtils.setMandatory(borderOrderNoField, true);
ValidationComponentUtils.setMandatory(borderOrderDateField, true);
}
// Building ***************************************************************
/**
* Builds and returns the whole editor with 3 sections
* for the different validation times.
*/
public JComponent buildPanel() {
initComponents();
initComponentAnnotations();
FormLayout layout = new FormLayout(
"fill:pref:grow",
"p, 3dlu, p, 17dlu, p, 3dlu, p, 17dlu, p, 3dlu, p, 17dlu, p, 3dlu, p");
PanelBuilder builder = new PanelBuilder(layout);
builder.setDefaultDialogBorder();
CellConstraints cc = new CellConstraints();
builder.addSeparator("Label with *", cc.xy(1, 1));
builder.add(buildLabelWithStarPanel(), cc.xy(1, 3));
builder.addSeparator("Label Foreground", cc.xy(1, 5));
builder.add(buildLabelForegroundPanel(), cc.xy(1, 7));
builder.addSeparator("Component Background", cc.xy(1, 9));
builder.add(buildComponentBackgroundPanel(), cc.xy(1, 11));
builder.addSeparator("Component Border", cc.xy(1, 13));
builder.add(buildComponentBorderPanel(), cc.xy(1, 15));
return builder.getPanel();
}
private JComponent buildLabelWithStarPanel() {
FormLayout layout = new FormLayout(
"right:max(65dlu;pref), 4dlu, 40dlu, 2dlu, 40dlu",
"p, 3dlu, p");
PanelBuilder builder = new PanelBuilder(layout);
CellConstraints cc = new CellConstraints();
builder.addLabel("Order No*", cc.xy (1, 1));
builder.add(new JTextField(), cc.xyw(3, 1, 3));
builder.addLabel("Order-*/Delivery Date", cc.xy (1, 3));
builder.add(new JTextField(), cc.xy (3, 3));
builder.add(new JTextField(), cc.xy (5, 3));
return builder.getPanel();
}
private JComponent buildLabelForegroundPanel() {
FormLayout layout = new FormLayout(
"right:max(65dlu;pref), 4dlu, 40dlu, 2dlu, 40dlu",
"p, 3dlu, p");
PanelBuilder builder = new PanelBuilder(layout);
CellConstraints cc = new CellConstraints();
builder.add(orderNoLabel, cc.xy (1, 1));
builder.add(new JTextField(), cc.xyw(3, 1, 3));
builder.add(buildDateLabelBar(), cc.xy (1, 3));
builder.add(new JTextField(), cc.xy (3, 3));
builder.add(new JTextField(), cc.xy (5, 3));
return builder.getPanel();
}
private JComponent buildDateLabelBar() {
FormLayout layout = new FormLayout("pref, pref", "pref");
PanelBuilder builder = new PanelBuilder(layout);
builder.add(orderDateLabel);
builder.nextColumn();
builder.addLabel("/Delivery Date");
return builder.getPanel();
}
private JComponent buildComponentBackgroundPanel() {
FormLayout layout = new FormLayout(
"right:max(65dlu;pref), 4dlu, 40dlu, 2dlu, 40dlu",
"p, 3dlu, p");
PanelBuilder builder = new PanelBuilder(layout);
CellConstraints cc = new CellConstraints();
builder.addLabel("Order No", cc.xy (1, 1));
builder.add(backgroundOrderNoField, cc.xyw(3, 1, 3));
builder.addLabel("Order-/Delivery Date", cc.xy (1, 3));
builder.add(backgroundOrderDateField, cc.xy (3, 3));
builder.add(backgroundDeliveryDateField, cc.xy (5, 3));
ValidationComponentUtils.updateComponentTreeMandatoryBackground(
builder.getPanel());
return builder.getPanel();
}
private JComponent buildComponentBorderPanel() {
FormLayout layout = new FormLayout(
"right:max(65dlu;pref), 4dlu, 40dlu, 2dlu, 40dlu",
"p, 3dlu, p");
PanelBuilder builder = new PanelBuilder(layout);
CellConstraints cc = new CellConstraints();
builder.addLabel("Order No", cc.xy (1, 1));
builder.add(borderOrderNoField, cc.xyw(3, 1, 3));
builder.addLabel("Order-/Delivery Date", cc.xy (1, 3));
builder.add(borderOrderDateField, cc.xy (3, 3));
builder.add(borderDeliveryDateField, cc.xy (5, 3));
ValidationComponentUtils.updateComponentTreeMandatoryBorder(
builder.getPanel());
return builder.getPanel();
}
// Helper Code ************************************************************
private static JLabel createMandatoryLabel(String text) {
JLabel label = new JLabel(text);
label.setForeground(ValidationComponentUtils.getMandatoryForeground());
return label;
}
}
Different validation result views
/*
* Copyright (c) 2003-2005 JGoodies Karsten Lentzsch. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* o Neither the name of JGoodies Karsten Lentzsch nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jgoodies.validation.tutorial.basics;
import java.awt.event.ActionEvent;
import javax.swing.*;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.factories.ButtonBarFactory;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.validation.ValidationResult;
import com.jgoodies.validation.tutorial.util.TutorialUtils;
import com.jgoodies.validation.util.DefaultValidationResultModel;
import com.jgoodies.validation.util.ValidationResultModel;
import com.jgoodies.validation.view.ValidationResultViewFactory;
/**
* Demonstrates the different validation result views created by the
* {@link com.jgoodies.validation.view.ValidationResultViewFactory}.
* Provides buttons to set a couple of valid and invalid results.
*
* @author Karsten Lentzsch
* @version $Revision: 1.5 $
*/
public class ValidationResultViewExample {
private final ValidationResultModel resultModel;
private JButton validButton;
private JButton errorsButton;
private JButton warningsButton;
private JButton mixedButton;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
} catch (Exception e) {
// Likely Plastic is not in the classpath; ignore it.
}
JFrame frame = new JFrame();
frame.setTitle("Basics :: Validation Result Views");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JComponent panel = new ValidationResultViewExample().buildPanel();
frame.getContentPane().add(panel);
frame.pack();
TutorialUtils.locateOnScreenCenter(frame);
frame.setVisible(true);
}
// Instance Creation ******************************************************
public ValidationResultViewExample() {
resultModel = new DefaultValidationResultModel();
resultModel.setResult(TutorialUtils.getMixedResult());
}
// Component Creation and Initialization **********************************
private void initComponents() {
validButton = new JButton(new SetResultAction("Valid", ValidationResult.EMPTY));
errorsButton = new JButton(new SetResultAction("Errors", TutorialUtils.getErrorsResult()));
warningsButton = new JButton(new SetResultAction("Warnings", TutorialUtils.getWarningsResult()));
mixedButton = new JButton(new SetResultAction("Mixed", TutorialUtils.getMixedResult()));
}
// Building ***************************************************************
/**
* Builds and returns the whole editor with 3 sections
* for the different validation times.
*/
public JComponent buildPanel() {
initComponents();
FormLayout layout = new FormLayout(
"right:max(65dlu;pref), 4dlu, 160dlu:grow",
"p, 9dlu, p, 9dlu, fill:max(34dlu;p), 9dlu, fill:34dlu, 9dlu, fill:34dlu, 9dlu:grow, p");
PanelBuilder builder = new PanelBuilder(layout);
builder.setDefaultDialogBorder();
CellConstraints cc = new CellConstraints();
builder.addLabel("Icon Summary", cc.xy (1, 1));
builder.add(ValidationResultViewFactory.
createReportIconLabel(resultModel), cc.xy (3, 1));
builder.addLabel("Icon and Text Summary", cc.xy (1, 3));
builder.add(ValidationResultViewFactory.
createReportIconAndTextLabel(resultModel), cc.xy (3, 3));
builder.addLabel("Texts and Summary Icon", cc.xy (1, 5, "r, t"));
builder.add(ValidationResultViewFactory.
createReportIconAndTextPane(resultModel), cc.xy (3, 5));
builder.addLabel("List", cc.xy (1, 7, "r, t"));
builder.add(ValidationResultViewFactory.
createReportList(resultModel), cc.xy (3, 7));
builder.addLabel("Text Pane", cc.xy (1, 9, "r, t"));
builder.add(ValidationResultViewFactory.
createReportTextPane(resultModel), cc.xy (3, 9));
builder.add(buildButtonBar(), cc.xyw(1, 11, 3));
return builder.getPanel();
}
private JComponent buildButtonBar() {
return ButtonBarFactory.buildRightAlignedBar(
validButton, errorsButton, warningsButton, mixedButton);
}
// Helper Code ************************************************************
/**
* Sets the given ValidationResult as the resultModel"s result
* when performed. Used to create the 4 command buttons.
*/
private class SetResultAction extends AbstractAction {
private final ValidationResult result;
SetResultAction(String name, ValidationResult result) {
super(name);
this.result = result;
}
public void actionPerformed(ActionEvent e) {
resultModel.setResult(result);
}
}
}
different validation times: key-typed, focus lost, commit (OK pressed)
/*
* Copyright (c) 2003-2005 JGoodies Karsten Lentzsch. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* o Neither the name of JGoodies Karsten Lentzsch nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jgoodies.validation.tutorial.basics;
import java.awt.event.ActionEvent;
import javax.swing.*;
import com.jgoodies.binding.PresentationModel;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.factories.ButtonBarFactory;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.validation.ValidationResult;
import com.jgoodies.validation.tutorial.shared.Order;
import com.jgoodies.validation.tutorial.shared.OrderModel;
import com.jgoodies.validation.tutorial.shared.OrderValidator;
import com.jgoodies.validation.tutorial.util.ExampleComponentFactory;
import com.jgoodies.validation.tutorial.util.TutorialUtils;
import com.jgoodies.validation.util.DefaultValidationResultModel;
import com.jgoodies.validation.util.ValidationResultModel;
import com.jgoodies.validation.view.ValidationResultViewFactory;
/**
* Demonstrates and compares different validation times:
* key-typed, focus lost, commit (OK pressed).
*
* @author Karsten Lentzsch
* @version $Revision: 1.5 $
*/
public class ValidationTimeExample {
private OrderModel keyTypedModel;
private JTextField keyTypedOrderNoField;
private JTextField keyTypedOrderDateField;
private JComponent keyTypedResultView;
private OrderModel focusLostModel;
private JTextField focusLostOrderNoField;
private JTextField focusLostOrderDateField;
private JComponent focusLostResultView;
private CommitOrderModel commitModel;
private JTextField commitOrderNoField;
private JTextField commitOrderDateField;
private JComponent commitResultView;
private JButton commitOKButton;
private JButton commitCancelButton;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
} catch (Exception e) {
// Likely Plastic is not in the classpath; ignore it.
}
JFrame frame = new JFrame();
frame.setTitle("Basics :: Validation Time");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JComponent panel = new ValidationTimeExample().buildPanel();
frame.getContentPane().add(panel);
frame.pack();
TutorialUtils.locateOnScreenCenter(frame);
frame.setVisible(true);
}
// Instance Creation ******************************************************
public ValidationTimeExample() {
keyTypedModel = new OrderModel(new Order());
focusLostModel = new OrderModel(new Order());
commitModel = new CommitOrderModel(new Order());
}
// Component Creation and Initialization **********************************
private void initComponents() {
// To commit on key typed we invoke #createTextField
// with the optional boolean parameter set to false.
keyTypedOrderNoField = ExampleComponentFactory.createTextField(
keyTypedModel.getModel(Order.PROPERTYNAME_ORDER_NO),
false);
// We can"t commit Dates on key typed, only on valid edit.
keyTypedOrderDateField = ExampleComponentFactory.createDateField(
keyTypedModel.getModel(Order.PROPERTYNAME_ORDER_DATE),
true,
true);
keyTypedResultView = ValidationResultViewFactory.createReportIconAndTextPane(
keyTypedModel.getValidationResultModel());
// By default #createTextField commits on focus lost
focusLostOrderNoField = ExampleComponentFactory.createTextField(
focusLostModel.getModel(Order.PROPERTYNAME_ORDER_NO));
focusLostOrderDateField = ExampleComponentFactory.createDateField(
focusLostModel.getModel(Order.PROPERTYNAME_ORDER_DATE));
focusLostResultView = ValidationResultViewFactory.createReportIconAndTextPane(
focusLostModel.getValidationResultModel());
// Here we delay commits by using the Binding buffering support.
commitOrderNoField = ExampleComponentFactory.createTextField(
commitModel.getBufferedModel(Order.PROPERTYNAME_ORDER_NO));
commitOrderDateField = ExampleComponentFactory.createDateField(
commitModel.getBufferedModel(Order.PROPERTYNAME_ORDER_DATE));
commitResultView = ValidationResultViewFactory.createReportIconAndTextPane(
commitModel.getValidationResultModel());
commitOKButton = new JButton(commitModel.getOKAction());
commitCancelButton = new JButton(commitModel.getCancelAction());
}
// Building ***************************************************************
/**
* Builds and returns the whole editor with 3 sections
* for the different validation times.
*/
public JComponent buildPanel() {
initComponents();
FormLayout layout = new FormLayout(
"fill:pref:grow",
"p, 3dlu, p, 6dlu, p, 3dlu, p, 6dlu, p, 3dlu, p");
PanelBuilder builder = new PanelBuilder(layout);
builder.setDefaultDialogBorder();
CellConstraints cc = new CellConstraints();
builder.addSeparator("Validate on Key Typed", cc.xy(1, 1));
builder.add(buildKeyTypedPanel(), cc.xy(1, 3));
builder.addSeparator("Validate on Focus Lost", cc.xy(1, 5));
builder.add(buildFocusLostPanel(), cc.xy(1, 7));
builder.addSeparator("Validate on Commit (OK)", cc.xy(1, 9));
builder.add(buildCommitPanel(), cc.xy(1, 11));
return builder.getPanel();
}
private JComponent buildKeyTypedPanel() {
FormLayout layout = new FormLayout(
"right:max(65dlu;pref), 4dlu, 40dlu, 2dlu, 40dlu, 80dlu:grow",
"p, 3dlu, p, 9dlu, fill:max(22dlu;p)");
PanelBuilder builder = new PanelBuilder(layout);
CellConstraints cc = new CellConstraints();
builder.addLabel("Order No", cc.xy (1, 1));
builder.add(keyTypedOrderNoField, cc.xyw(3, 1, 3));
builder.addLabel("Order Date", cc.xy (1, 3));
builder.add(keyTypedOrderDateField, cc.xy (3, 3));
builder.addLabel("(commits on valid edit)", cc.xyw(5, 3, 2));
builder.add(keyTypedResultView, cc.xyw(3, 5, 4));
return builder.getPanel();
}
private JComponent buildFocusLostPanel() {
FormLayout layout = new FormLayout(
"right:max(65dlu;pref), 4dlu, 40dlu, 2dlu, 40dlu, 80dlu:grow",
"p, 3dlu, p, 9dlu, fill:max(22dlu;p)");
PanelBuilder builder = new PanelBuilder(layout);
CellConstraints cc = new CellConstraints();
builder.addLabel("Order No", cc.xy (1, 1));
builder.add(focusLostOrderNoField, cc.xyw(3, 1, 3));
builder.addLabel("Order Date", cc.xy (1, 3));
builder.add(focusLostOrderDateField, cc.xy (3, 3));
builder.add(focusLostResultView, cc.xyw(3, 5, 4));
return builder.getPanel();
}
private JComponent buildCommitPanel() {
FormLayout layout = new FormLayout(
"right:max(65dlu;pref), 4dlu, 40dlu, 2dlu, 40dlu, 80dlu:grow",
"p, 3dlu, p, 9dlu, fill:max(22dlu;p), 2dlu:grow, p");
PanelBuilder builder = new PanelBuilder(layout);
CellConstraints cc = new CellConstraints();
builder.addLabel("Order No", cc.xy (1, 1));
builder.add(commitOrderNoField, cc.xyw(3, 1, 3));
builder.addLabel("Order Date", cc.xy (1, 3));
builder.add(commitOrderDateField, cc.xy (3, 3));
builder.add(commitResultView, cc.xyw(3, 5, 4));
builder.add(buildCommitButtonBar(), cc.xyw(3, 7, 4));
return builder.getPanel();
}
private JComponent buildCommitButtonBar() {
return ButtonBarFactory.buildRightAlignedBar(
commitOKButton, commitCancelButton);
}
// Domain Classes *********************************************************
/**
* Provides the validation result model and actions necessary to
* build a presentation.
*/
private static final class CommitOrderModel extends PresentationModel {
private final ValidationResultModel validationResultModel;
private final Action okAction;
private final Action cancelAction;
// Instance Creation -------------------------------------
CommitOrderModel(Order order) {
super(order);
validationResultModel = new DefaultValidationResultModel();
okAction = new OKAction();
cancelAction = new CancelAction();
}
// Exposing Models -------------------------------------------
ValidationResultModel getValidationResultModel() {
return validationResultModel;
}
Action getOKAction() {
return okAction;
}
Action getCancelAction() {
return cancelAction;
}
// Validation ------------------------------------------------
private void updateValidationResult() {
Order order = (Order) getBean();
ValidationResult result = new OrderValidator(order).validate();
validationResultModel.setResult(result);
}
// -------------------------------------------------------
/**
* Commits buffered changes and updates the validation result.
*/
private final class OKAction extends AbstractAction {
private OKAction() { super("OK"); }
public void actionPerformed(ActionEvent evt) {
triggerCommit();
updateValidationResult();
}
}
/**
* Flushes buffered changes and updates the validation result.
*/
private final class CancelAction extends AbstractAction {
private CancelAction() { super("Cancel"); }
public void actionPerformed(ActionEvent evt) {
triggerFlush();
updateValidationResult();
}
}
}
}
Error Dialog Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class ErrorDialogExample extends JPanel {
JTextField nameField;
JTextField siteField;
JTextField feedField;
Feed feed;
public ErrorDialogExample() {
DefaultFormBuilder formBuilder = new DefaultFormBuilder(new FormLayout(""));
formBuilder.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
formBuilder.appendColumn("right:pref");
formBuilder.appendColumn("3dlu");
formBuilder.appendColumn("fill:p:g");
this.nameField = new JTextField();
formBuilder.append("Name:", this.nameField);
this.siteField = new JTextField();
formBuilder.append("Site Url:", this.siteField);
this.feedField = new JTextField();
formBuilder.append("Feed Url:", this.feedField);
formBuilder.append(new JButton(new ShowFeedInformationAction()), 3);
createFeed();
initializeFormElements();
add(formBuilder.getPanel());
}
private void createFeed() {
this.feed = new Feed();
this.feed.setName("ClientJava.ru");
this.feed.setSiteUrl("http://www.clientjava.ru/blog");
this.feed.setFeedUrl("http://www.clientjava.ru/blog/rss.xml");
}
private void initializeFormElements() {
this.nameField.setText(this.feed.getName());
this.siteField.setText(this.feed.getSiteUrl());
this.feedField.setText(this.feed.getFeedUrl());
}
private void synchFormAndFeed() {
this.feed.setName(this.nameField.getText());
this.feed.setSiteUrl(this.siteField.getText());
this.feed.setFeedUrl(this.feedField.getText());
}
private boolean validateFeed() {
boolean valid = true;
if (this.nameField.getText().trim().length() == 0) {
JOptionPane.showMessageDialog(null, "Name must not be empty.", "Error", JOptionPane.ERROR_MESSAGE);
valid = false;
}
if (this.siteField.getText().trim().length() == 0) {
JOptionPane.showMessageDialog(null, "Site URL must not be empty.", "Error", JOptionPane.ERROR_MESSAGE);
valid = false;
}
if (this.feedField.getText().trim().length() == 0) {
JOptionPane.showMessageDialog(null, "Feed URL must not be empty.", "Error", JOptionPane.ERROR_MESSAGE);
valid = false;
}
return valid;
}
private Feed getFeed() {
return this.feed;
}
private class ShowFeedInformationAction extends AbstractAction {
public ShowFeedInformationAction() {
super("Show Feed Information");
}
public void actionPerformed(ActionEvent event) {
if (validateFeed()) {
synchFormAndFeed();
StringBuffer message = new StringBuffer();
message.append("<html>");
message.append("<b>Name:</b> ");
message.append(getFeed().getName());
message.append("<br>");
message.append("<b>Site URL:</b> ");
message.append(getFeed().getSiteUrl());
message.append("<br>");
message.append("<b>Feed URL:</b> ");
message.append(getFeed().getFeedUrl());
message.append("</html>");
JOptionPane.showMessageDialog(null, message.toString());
}
}
}
public static void main(String[] a){
JFrame f = new JFrame("Error Dialog Example");
f.setDefaultCloseOperation(2);
f.add(new ErrorDialogExample());
f.pack();
f.setVisible(true);
}
}
Field List Validator Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.validation.ValidationResult;
import com.jgoodies.validation.util.DefaultValidationResultModel;
import com.jgoodies.validation.util.ValidationResultModel;
import com.jgoodies.validation.view.ValidationResultViewFactory;
public class FieldListValidatorExample extends JPanel {
private Feed feed;
private ShowFeedInformationAction showFeedInformationAction;
private FeedPresentationModel feedPresentationModel;
private FeedSpecificValidator feedValidator;
public FieldListValidatorExample() {
DefaultFormBuilder formBuilder = new DefaultFormBuilder(new FormLayout("right:pref, 3dlu, p:g"));
formBuilder.setDefaultDialogBorder();
createFeed();
this.feedPresentationModel = new FeedPresentationModel(this.feed);
ValueModel nameModel = this.feedPresentationModel.getFieldModel("name");
ValueModel feedModel = this.feedPresentationModel.getFieldModel("feedUrl");
ValueModel siteModel = this.feedPresentationModel.getFieldModel("siteUrl");
JTextField nameField = BasicComponentFactory.createTextField(nameModel);
JTextField feedField = BasicComponentFactory.createTextField(feedModel);
JTextField siteField = BasicComponentFactory.createTextField(siteModel);
formBuilder.append("Name:", nameField);
formBuilder.append("Site Url:", siteField);
formBuilder.append("Feed Url:", feedField);
this.feedPresentationModel.getValidationModel().addPropertyChangeListener(ValidationResultModel.PROPERTYNAME_RESULT, new ValidationListener());
this.feedValidator = new FeedSpecificValidator(this.feedPresentationModel);
JComponent validationResultsComponent = ValidationResultViewFactory.createReportList(this.feedPresentationModel.getValidationModel());
formBuilder.appendRow("top:30dlu:g");
CellConstraints cc = new CellConstraints();
formBuilder.add(validationResultsComponent, cc.xywh(1, formBuilder.getRow() + 1, 3, 1, "fill, fill"));
formBuilder.nextLine(2);
formBuilder.append(new JButton(new ValidateAction()), 3);
this.showFeedInformationAction = new ShowFeedInformationAction();
formBuilder.append(new JButton(this.showFeedInformationAction), 3);
add(formBuilder.getPanel());
}
private class ValidationListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName() == ValidationResultModel.PROPERTYNAME_RESULT) {
showFeedInformationAction.setEnabled(!feedPresentationModel.getValidationModel().hasErrors());
}
}
}
private class ValidateAction extends AbstractAction {
public ValidateAction() {
super("Validate");
}
public void actionPerformed(ActionEvent e) {
ValidationResult validationResult = feedValidator.validate();
feedPresentationModel.setValidationResults(validationResult);
}
}
private class ShowFeedInformationAction extends AbstractAction {
public ShowFeedInformationAction() {
super("Show Feed Information");
setEnabled(false);
}
public void actionPerformed(ActionEvent event) {
StringBuffer message = new StringBuffer();
message.append("<html>");
message.append("<b>Name:</b> ");
message.append(feed.getName());
message.append("<br>");
message.append("<b>Site URL:</b> ");
message.append(feed.getSiteUrl());
message.append("<br>");
message.append("<b>Feed URL:</b> ");
message.append(feed.getFeedUrl());
message.append("</html>");
JOptionPane.showMessageDialog(null, message.toString());
}
}
private class FeedPresentationModel extends FieldListModel {
private ValidationResultModel validationResultModel;
public FeedPresentationModel(Object bean) {
super(bean);
this.validationResultModel = new DefaultValidationResultModel();
}
public ValidationResultModel getValidationModel() {
return this.validationResultModel;
}
public void setValidationResults(ValidationResult result) {
getValidationModel().setResult(result);
}
}
private void createFeed() {
this.feed = new Feed();
this.feed.setName("ClientJava.ru");
this.feed.setSiteUrl("http://www.clientjava.ru/blog");
this.feed.setFeedUrl("http://www.clientjava.ru/blog/rss.xml");
}
public static void main(String[] a){
JFrame f = new JFrame("Field List Model Validation Example");
f.setDefaultCloseOperation(2);
f.add(new FieldListValidatorExample());
f.pack();
f.setVisible(true);
}
}
how to provide input hints
/*
* Copyright (c) 2003-2005 JGoodies Karsten Lentzsch. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* o Neither the name of JGoodies Karsten Lentzsch nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jgoodies.validation.tutorial.basics;
import java.awt.ruponent;
import java.awt.KeyboardFocusManager;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
import com.jgoodies.binding.value.ValueHolder;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.validation.tutorial.util.ExampleComponentFactory;
import com.jgoodies.validation.tutorial.util.TutorialUtils;
import com.jgoodies.validation.view.ValidationComponentUtils;
import com.jgoodies.validation.view.ValidationResultViewFactory;
/**
* Demonstrates a style how to provide input hints,
* so that users can avoid entering invalid data.
*
* @author Karsten Lentzsch
* @version $Revision: 1.4 $
*/
public class InfoOnFocusExample {
private JLabel infoLabel;
private JTextArea infoArea;
private JComponent infoAreaPane;
private JTextField orderNoField;
private JTextField orderDateField;
private JTextField deliveryDateField;
private JTextArea deliveryNotesArea;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
} catch (Exception e) {
// Likely Plastic is not in the classpath; ignore it.
}
JFrame frame = new JFrame();
frame.setTitle("Basics :: Hints on Focus");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JComponent panel = new InfoOnFocusExample().buildPanel();
frame.getContentPane().add(panel);
frame.pack();
TutorialUtils.locateOnScreenCenter(frame);
frame.setVisible(true);
}
// Component Creation and Initialization **********************************
/**
* Creates and intializes the UI components.
*/
private void initComponents() {
orderNoField = new JTextField();
orderDateField = ExampleComponentFactory.createDateField(new ValueHolder());
deliveryDateField = ExampleComponentFactory.createDateField(new ValueHolder());
deliveryNotesArea = new JTextArea();
}
private void initComponentAnnotations() {
ValidationComponentUtils.setInputHint(orderNoField, "Mandatory, length in [5, 10]");
ValidationComponentUtils.setInputHint(orderDateField, "Mandatory, before delivery date");
ValidationComponentUtils.setInputHint(deliveryDateField, "After delivery date");
ValidationComponentUtils.setInputHint(deliveryNotesArea, "Length <= 30");
}
private void initEventHandling() {
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addPropertyChangeListener(new FocusChangeHandler());
}
// Building ***************************************************************
/**
* Builds and returns the whole editor.
*/
public JComponent buildPanel() {
initComponents();
initComponentAnnotations();
initEventHandling();
FormLayout layout = new FormLayout(
"fill:default:grow",
"max(14dlu;pref), 6dlu, pref, 3dlu, pref");
PanelBuilder builder = new PanelBuilder(layout);
builder.setDefaultDialogBorder();
CellConstraints cc = new CellConstraints();
builder.add(buildInfoAreaPane(), cc.xy(1, 1));
builder.addSeparator("Order", cc.xy(1, 3));
builder.add(buildEditorPanel(), cc.xy(1, 5));
return builder.getPanel();
}
private JComponent buildEditorPanel() {
FormLayout layout = new FormLayout(
"right:max(65dlu;pref), 4dlu, 40dlu, 2dlu, 40dlu, 80dlu:grow",
"p, 3dlu, p, 3dlu, p, 3dlu, p, 2px"); // extra bottom space for icons
layout.setRowGroups(new int[][]{{1, 3, 5, 7}});
PanelBuilder builder = new PanelBuilder(layout);
CellConstraints cc = new CellConstraints();
builder.addLabel("Order No", cc.xy (1, 1));
builder.add(orderNoField, cc.xyw (3, 1, 3));
builder.addLabel("Order-/Delivery Date", cc.xy (1, 3));
builder.add(orderDateField, cc.xy (3, 3));
builder.add(deliveryDateField, cc.xy (5, 3));
builder.addLabel("Notes", cc.xy (1, 5));
builder.add(new JScrollPane(deliveryNotesArea),
cc.xywh(3, 5, 4, 3));
return builder.getPanel();
}
private JComponent buildInfoAreaPane() {
infoLabel = new JLabel(ValidationResultViewFactory.getInfoIcon());
infoArea = new JTextArea(1, 38);
infoArea.setEditable(false);
infoArea.setOpaque(false);
FormLayout layout = new FormLayout("pref, 2dlu, default", "pref");
PanelBuilder builder = new PanelBuilder(layout);
CellConstraints cc = new CellConstraints();
builder.add(infoLabel, cc.xy(1, 1));
builder.add(infoArea, cc.xy(3, 1));
infoAreaPane = builder.getPanel();
infoAreaPane.setVisible(false);
return infoAreaPane;
}
// Validation Handler *****************************************************
/**
* Displays an input hint for components that get the focus permanently.
*/
private class FocusChangeHandler implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if (!"permanentFocusOwner".equals(propertyName))
return;
Component focusOwner = KeyboardFocusManager
.getCurrentKeyboardFocusManager().getFocusOwner();
String focusHint = (focusOwner instanceof JComponent)
? (String) ValidationComponentUtils
.getInputHint((JComponent) focusOwner)
: null;
infoArea.setText(focusHint);
infoAreaPane.setVisible(focusHint != null);
}
}
}
Info Assist Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.ruponent;
import java.awt.KeyboardFocusManager;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.validation.view.ValidationComponentUtils;
import com.jgoodies.validation.view.ValidationResultViewFactory;
public class InfoAssistExample extends JPanel {
private JLabel infoLabel;
public InfoAssistExample() {
DefaultFormBuilder formBuilder = new DefaultFormBuilder(new FormLayout("right:pref, 3dlu, p:g"));
formBuilder.setDefaultDialogBorder();
JTextField nameField = new JTextField();
JTextField feedField = new JTextField();
JTextField siteField = new JTextField();
ValidationComponentUtils.setInputHint(nameField, "Enter a name.");
ValidationComponentUtils.setInputHint(feedField, "Enter a valid rss feed url.");
ValidationComponentUtils.setInputHint(siteField, "Enter a site url.");
this.infoLabel = new JLabel();
this.infoLabel.setIcon(ValidationResultViewFactory.getInfoIcon());
this.infoLabel.setVisible(false);
KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener(new FocusChangeHandler());
formBuilder.append(this.infoLabel, 3);
formBuilder.append("Name:", nameField);
formBuilder.append("Site Url:", siteField);
formBuilder.append("Feed Url:", feedField);
add(formBuilder.getPanel());
}
private class FocusChangeHandler implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if (!"permanentFocusOwner".equals(propertyName))
return;
Component focusOwner = KeyboardFocusManager
.getCurrentKeyboardFocusManager().getFocusOwner();
String focusHint = (focusOwner instanceof JComponent)
? (String) ValidationComponentUtils
.getInputHint((JComponent) focusOwner)
: null;
infoLabel.setText(focusHint);
infoLabel.setVisible(focusHint != null);
}
}
public static void main(String[] a){
JFrame f = new JFrame("Info Assist Example");
f.setDefaultCloseOperation(2);
f.add(new InfoAssistExample());
f.pack();
f.setVisible(true);
}
}
Input Verifier Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import javax.swing.BorderFactory;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class InputVerifierExample extends JPanel {
private JLabel validationLabel;
public InputVerifierExample() {
DefaultFormBuilder formBuilder = new DefaultFormBuilder(new FormLayout("right:pref, 3dlu, p:g"));
formBuilder.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JTextField javaField = new JTextField();
JTextField swingField = new JTextField();
this.validationLabel = new JLabel();
javaField.setInputVerifier(new StrictInputVerifier("Java"));
swingField.setInputVerifier(new StrictInputVerifier("Swing"));
formBuilder.append("Java Field:", javaField);
formBuilder.append("Swing Field:", swingField);
formBuilder.appendParagraphGapRow();
formBuilder.append(validationLabel, 3);
add(formBuilder.getPanel());
}
private class StrictInputVerifier extends InputVerifier {
private String validString;
public StrictInputVerifier(String validString) {
this.validString = validString;
}
public boolean verify(JComponent input) {
JTextField textField = (JTextField) input;
if (validString.equals(textField.getText())) {
validationLabel.setText("");
return true;
} else {
validationLabel.setText("Field must only contain " + this.validString);
return false;
}
}
}
public static void main(String[] a){
JFrame f = new JFrame("Input Verifier Example");
f.setDefaultCloseOperation(2);
f.add(new InputVerifierExample());
f.pack();
f.setVisible(true);
}
}
Validating Domain Object Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.jgoodies.binding.PresentationModel;
import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.validation.ValidationCapable;
import com.jgoodies.validation.ValidationResult;
import com.jgoodies.validation.util.DefaultValidationResultModel;
import com.jgoodies.validation.util.ValidationResultModel;
import com.jgoodies.validation.util.ValidationUtils;
import com.jgoodies.validation.view.ValidationResultViewFactory;
public class ValidatingDomainObjectExample extends JPanel {
private Feed feed;
private ShowFeedInformationAction showFeedInformationAction;
private FeedPresentationModel feedPresentationModel;
public ValidatingDomainObjectExample() {
DefaultFormBuilder formBuilder = new DefaultFormBuilder(new FormLayout("right:pref, 3dlu, p:g"));
formBuilder.setDefaultDialogBorder();
createFeed();
this.feedPresentationModel = new FeedPresentationModel(this.feed);
ValueModel nameModel = this.feedPresentationModel.getModel("name");
ValueModel feedModel = this.feedPresentationModel.getModel("feedUrl");
ValueModel siteModel = this.feedPresentationModel.getModel("siteUrl");
JTextField nameField = BasicComponentFactory.createTextField(nameModel);
JTextField feedField = BasicComponentFactory.createTextField(feedModel);
JTextField siteField = BasicComponentFactory.createTextField(siteModel);
formBuilder.append("Name:", nameField);
formBuilder.append("Site Url:", siteField);
formBuilder.append("Feed Url:", feedField);
this.feedPresentationModel.getValidationModel().addPropertyChangeListener(ValidationResultModel.PROPERTYNAME_RESULT, new ValidationListener());
JComponent validationResultsComponent = ValidationResultViewFactory.createReportList(this.feedPresentationModel.getValidationModel());
formBuilder.appendRow("top:30dlu:g");
CellConstraints cc = new CellConstraints();
formBuilder.add(validationResultsComponent, cc.xywh(1, formBuilder.getRow() + 1, 3, 1, "fill, fill"));
formBuilder.nextLine(2);
formBuilder.append(new JButton(new ValidateAction()), 3);
this.showFeedInformationAction = new ShowFeedInformationAction();
formBuilder.append(new JButton(this.showFeedInformationAction), 3);
add(formBuilder.getPanel());
}
private class ValidationListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName() == ValidationResultModel.PROPERTYNAME_RESULT) {
showFeedInformationAction.setEnabled(!feedPresentationModel.getValidationModel().hasErrors());
}
}
}
private void createFeed() {
this.feed = new Feed();
this.feed.setName("ClientJava.ru");
this.feed.setSiteUrl("http://www.clientjava.ru/blog");
this.feed.setFeedUrl("http://www.clientjava.ru/blog/rss.xml");
}
private class ValidateAction extends AbstractAction {
public ValidateAction() {
super("Validate");
}
public void actionPerformed(ActionEvent e) {
feedPresentationModel.performValidation();
}
}
private class ShowFeedInformationAction extends AbstractAction {
public ShowFeedInformationAction() {
super("Show Feed Information");
setEnabled(false);
}
public void actionPerformed(ActionEvent event) {
StringBuffer message = new StringBuffer();
message.append("<html>");
message.append("<b>Name:</b> ");
message.append(feed.getName());
message.append("<br>");
message.append("<b>Site URL:</b> ");
message.append(feed.getSiteUrl());
message.append("<br>");
message.append("<b>Feed URL:</b> ");
message.append(feed.getFeedUrl());
message.append("</html>");
JOptionPane.showMessageDialog(null, message.toString());
}
}
private class FeedPresentationModel extends PresentationModel {
private ValidationResultModel validationResultModel;
public FeedPresentationModel(Object bean) {
super(bean);
this.validationResultModel = new DefaultValidationResultModel();
}
public ValidationResultModel getValidationModel() {
return this.validationResultModel;
}
public void performValidation() {
ValidationResult validationResult = ((ValidationCapable) getBean()).validate();
getValidationModel().setResult(validationResult);
}
}
public class ValidatingFeed extends Feed implements ValidationCapable {
public ValidationResult validate() {
ValidationResult validationResult = new ValidationResult();
String name = getName();
String feedUrl = getFeedUrl();
String siteUrl = getSiteUrl();
if (ValidationUtils.isEmpty(name)) {
validationResult.addError("The name field can not be blank.");
} else if (!ValidationUtils.hasBoundedLength(name, 5, 14)) {
validationResult.addError("The name field must be between 5 and 14 characters.");
}
if (!"ClientJava.ru".equals(name)) {
validationResult.addWarning("This form prefers the feed ClientJava.ru");
}
if (ValidationUtils.isEmpty(feedUrl)) {
validationResult.addError("The feed field can not be blank.");
}
if (ValidationUtils.isEmpty(siteUrl)) {
validationResult.addError("The site field can not be blank.");
}
return validationResult;
}
}
public static void main(String[] a){
JFrame f = new JFrame("Domain Object Validation Example");
f.setDefaultCloseOperation(2);
f.add(new ValidatingDomainObjectExample());
f.pack();
f.setVisible(true);
}
}
Validating On Focus Lost Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.jgoodies.binding.PresentationModel;
import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.validation.ValidationCapable;
import com.jgoodies.validation.ValidationResult;
import com.jgoodies.validation.util.DefaultValidationResultModel;
import com.jgoodies.validation.util.ValidationResultModel;
import com.jgoodies.validation.util.ValidationUtils;
import com.jgoodies.validation.view.ValidationResultViewFactory;
public class ValidatingOnFocusLostExample extends JPanel {
private Feed feed;
private FeedPresentationModel feedPresentationModel;
public ValidatingOnFocusLostExample() {
DefaultFormBuilder formBuilder = new DefaultFormBuilder(new FormLayout("right:pref, 3dlu, p:g"));
formBuilder.setDefaultDialogBorder();
createFeed();
this.feedPresentationModel = new FeedPresentationModel(this.feed);
ValueModel nameModel = this.feedPresentationModel.getModel("name");
ValueModel feedModel = this.feedPresentationModel.getModel("feedUrl");
ValueModel siteModel = this.feedPresentationModel.getModel("siteUrl");
JTextField nameField = BasicComponentFactory.createTextField(nameModel);
JTextField feedField = BasicComponentFactory.createTextField(feedModel);
JTextField siteField = BasicComponentFactory.createTextField(siteModel);
formBuilder.append("Name:", nameField);
formBuilder.append("Site Url:", siteField);
formBuilder.append("Feed Url:", feedField);
JComponent validationResultsComponent = ValidationResultViewFactory.createReportList(this.feedPresentationModel.getValidationModel());
formBuilder.appendRow("top:30dlu:g");
CellConstraints cc = new CellConstraints();
formBuilder.add(validationResultsComponent, cc.xywh(1, formBuilder.getRow() + 1, 3, 1, "fill, fill"));
add(formBuilder.getPanel());
}
private void createFeed() {
this.feed = new Feed();
this.feed.setName("ClientJava.ru");
this.feed.setSiteUrl("http://www.clientjava.ru/blog");
this.feed.setFeedUrl("http://www.clientjava.ru/blog/rss.xml");
}
private class FeedPresentationModel extends PresentationModel implements ValidationCapable {
private ValidationResultModel validationResultModel;
public FeedPresentationModel(Object bean) {
super(bean);
this.validationResultModel = new DefaultValidationResultModel();
initEventHandling();
}
public ValidationResultModel getValidationModel() {
return this.validationResultModel;
}
public ValidationResult validate() {
ValidationResult validationResult = new ValidationResult();
String name = (String) getModel("name").getValue();
String feedUrl = (String) getModel("feedUrl").getValue();
String siteUrl = (String) getModel("siteUrl").getValue();
if (ValidationUtils.isEmpty(name)) {
validationResult.addError("The name field can not be blank.");
} else if (!ValidationUtils.hasBoundedLength(name, 5, 14)) {
validationResult.addError("The name field must be between 5 and 14 characters.");
}
if (!"ClientJava.ru".equals(name)) {
validationResult.addWarning("This form prefers the feed ClientJava.ru");
}
if (ValidationUtils.isEmpty(feedUrl)) {
validationResult.addError("The feed field can not be blank.");
}
if (ValidationUtils.isEmpty(siteUrl)) {
validationResult.addError("The site field can not be blank.");
}
return validationResult;
}
private void initEventHandling() {
PropertyChangeListener handler = new ValidationUpdateHandler();
addBeanPropertyChangeListener(handler);
getBeanChannel().addValueChangeListener(handler);
}
// Event Handling *********************************************************
class ValidationUpdateHandler implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
updateValidationResult();
}
private void updateValidationResult() {
ValidationResult result = validate();
getValidationModel().setResult(result);
}
}
}
public static void main(String[] a){
JFrame f = new JFrame("Validation on Focus Lost Example");
f.setDefaultCloseOperation(2);
f.add(new ValidatingOnFocusLostExample());
f.pack();
f.setVisible(true);
}
}
Validating On Key Typed Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.jgoodies.binding.PresentationModel;
import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.validation.ValidationCapable;
import com.jgoodies.validation.ValidationResult;
import com.jgoodies.validation.util.DefaultValidationResultModel;
import com.jgoodies.validation.util.ValidationResultModel;
import com.jgoodies.validation.util.ValidationUtils;
import com.jgoodies.validation.view.ValidationResultViewFactory;
public class ValidatingOnKeyTypedExample extends JPanel {
private Feed feed;
private FeedPresentationModel feedPresentationModel;
public ValidatingOnKeyTypedExample() {
DefaultFormBuilder formBuilder = new DefaultFormBuilder(new FormLayout("right:pref, 3dlu, p:g"));
formBuilder.setDefaultDialogBorder();
createFeed();
this.feedPresentationModel = new FeedPresentationModel(this.feed);
ValueModel nameModel = this.feedPresentationModel.getModel("name");
ValueModel feedModel = this.feedPresentationModel.getModel("feedUrl");
ValueModel siteModel = this.feedPresentationModel.getModel("siteUrl");
JTextField nameField = BasicComponentFactory.createTextField(nameModel, false);
JTextField feedField = BasicComponentFactory.createTextField(feedModel, false);
JTextField siteField = BasicComponentFactory.createTextField(siteModel, false);
formBuilder.append("Name:", nameField);
formBuilder.append("Site Url:", siteField);
formBuilder.append("Feed Url:", feedField);
JComponent validationResultsComponent = ValidationResultViewFactory.createReportList(this.feedPresentationModel.getValidationModel());
formBuilder.appendRow("top:30dlu:g");
CellConstraints cc = new CellConstraints();
formBuilder.add(validationResultsComponent, cc.xywh(1, formBuilder.getRow() + 1, 3, 1, "fill, fill"));
add(formBuilder.getPanel());
}
private void createFeed() {
this.feed = new Feed();
this.feed.setName("ClientJava.ru");
this.feed.setSiteUrl("http://www.clientjava.ru/blog");
this.feed.setFeedUrl("http://www.clientjava.ru/blog/rss.xml");
}
private class FeedPresentationModel extends PresentationModel implements ValidationCapable {
private ValidationResultModel validationResultModel;
public FeedPresentationModel(Object bean) {
super(bean);
this.validationResultModel = new DefaultValidationResultModel();
initEventHandling();
}
public ValidationResultModel getValidationModel() {
return this.validationResultModel;
}
public ValidationResult validate() {
ValidationResult validationResult = new ValidationResult();
String name = (String) getModel("name").getValue();
String feedUrl = (String) getModel("feedUrl").getValue();
String siteUrl = (String) getModel("siteUrl").getValue();
if (ValidationUtils.isEmpty(name)) {
validationResult.addError("The name field can not be blank.");
} else if (!ValidationUtils.hasBoundedLength(name, 5, 14)) {
validationResult.addError("The name field must be between 5 and 14 characters.");
}
if (!"ClientJava.ru".equals(name)) {
validationResult.addWarning("This form prefers the feed ClientJava.ru");
}
if (ValidationUtils.isEmpty(feedUrl)) {
validationResult.addError("The feed field can not be blank.");
}
if (ValidationUtils.isEmpty(siteUrl)) {
validationResult.addError("The site field can not be blank.");
}
return validationResult;
}
private void initEventHandling() {
PropertyChangeListener handler = new ValidationUpdateHandler();
addBeanPropertyChangeListener(handler);
getBeanChannel().addValueChangeListener(handler);
}
// Event Handling *********************************************************
class ValidationUpdateHandler implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
updateValidationResult();
}
private void updateValidationResult() {
ValidationResult result = validate();
getValidationModel().setResult(result);
}
}
}
public static void main(String[] a){
JFrame f = new JFrame("Validation on Key Typed Example");
f.setDefaultCloseOperation(2);
f.add(new ValidatingOnKeyTypedExample());
f.pack();
f.setVisible(true);
}
}
Validating Presentation Model Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.jgoodies.binding.PresentationModel;
import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.validation.ValidationCapable;
import com.jgoodies.validation.ValidationResult;
import com.jgoodies.validation.util.DefaultValidationResultModel;
import com.jgoodies.validation.util.ValidationResultModel;
import com.jgoodies.validation.util.ValidationUtils;
import com.jgoodies.validation.view.ValidationResultViewFactory;
public class ValidatingPresentationModelExample extends JPanel {
private Feed feed;
private ShowFeedInformationAction showFeedInformationAction;
private FeedPresentationModel feedPresentationModel;
public ValidatingPresentationModelExample() {
DefaultFormBuilder formBuilder = new DefaultFormBuilder(new FormLayout("right:pref, 3dlu, p:g"));
formBuilder.setDefaultDialogBorder();
createFeed();
this.feedPresentationModel = new FeedPresentationModel(this.feed);
ValueModel nameModel = this.feedPresentationModel.getModel("name");
ValueModel feedModel = this.feedPresentationModel.getModel("feedUrl");
ValueModel siteModel = this.feedPresentationModel.getModel("siteUrl");
JTextField nameField = BasicComponentFactory.createTextField(nameModel);
JTextField feedField = BasicComponentFactory.createTextField(feedModel);
JTextField siteField = BasicComponentFactory.createTextField(siteModel);
formBuilder.append("Name:", nameField);
formBuilder.append("Site Url:", siteField);
formBuilder.append("Feed Url:", feedField);
this.feedPresentationModel.getValidationModel().addPropertyChangeListener(ValidationResultModel.PROPERTYNAME_RESULT, new ValidationListener());
JComponent validationResultsComponent = ValidationResultViewFactory.createReportList(this.feedPresentationModel.getValidationModel());
formBuilder.appendRow("top:30dlu:g");
CellConstraints cc = new CellConstraints();
formBuilder.add(validationResultsComponent, cc.xywh(1, formBuilder.getRow() + 1, 3, 1, "fill, fill"));
formBuilder.nextLine(2);
formBuilder.append(new JButton(new ValidateAction()), 3);
this.showFeedInformationAction = new ShowFeedInformationAction();
formBuilder.append(new JButton(this.showFeedInformationAction), 3);
add(formBuilder.getPanel());
}
private class ValidationListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName() == ValidationResultModel.PROPERTYNAME_RESULT) {
showFeedInformationAction.setEnabled(!feedPresentationModel.getValidationModel().hasErrors());
}
}
}
private void createFeed() {
this.feed = new Feed();
this.feed.setName("ClientJava.ru");
this.feed.setSiteUrl("http://www.clientjava.ru/blog");
this.feed.setFeedUrl("http://www.clientjava.ru/blog/rss.xml");
}
private class ValidateAction extends AbstractAction {
public ValidateAction() {
super("Validate");
}
public void actionPerformed(ActionEvent e) {
feedPresentationModel.performValidation();
}
}
private class ShowFeedInformationAction extends AbstractAction {
public ShowFeedInformationAction() {
super("Show Feed Information");
setEnabled(false);
}
public void actionPerformed(ActionEvent event) {
StringBuffer message = new StringBuffer();
message.append("<html>");
message.append("<b>Name:</b> ");
message.append(feed.getName());
message.append("<br>");
message.append("<b>Site URL:</b> ");
message.append(feed.getSiteUrl());
message.append("<br>");
message.append("<b>Feed URL:</b> ");
message.append(feed.getFeedUrl());
message.append("</html>");
JOptionPane.showMessageDialog(null, message.toString());
}
}
private class FeedPresentationModel extends PresentationModel implements ValidationCapable {
private ValidationResultModel validationResultModel;
public FeedPresentationModel(Object bean) {
super(bean);
this.validationResultModel = new DefaultValidationResultModel();
}
public ValidationResultModel getValidationModel() {
return this.validationResultModel;
}
public ValidationResult validate() {
ValidationResult validationResult = new ValidationResult();
String name = (String) getModel("name").getValue();
String feedUrl = (String) getModel("feedUrl").getValue();
String siteUrl = (String) getModel("siteUrl").getValue();
if (ValidationUtils.isEmpty(name)) {
validationResult.addError("The name field can not be blank.");
} else if (!ValidationUtils.hasBoundedLength(name, 5, 14)) {
validationResult.addError("The name field must be between 5 and 14 characters.");
}
if (!"ClientJava.ru".equals(name)) {
validationResult.addWarning("This form prefers the feed ClientJava.ru");
}
if (ValidationUtils.isEmpty(feedUrl)) {
validationResult.addError("The feed field can not be blank.");
}
if (ValidationUtils.isEmpty(siteUrl)) {
validationResult.addError("The site field can not be blank.");
}
return validationResult;
}
public void performValidation() {
ValidationResult validationResult = validate();
getValidationModel().setResult(validationResult);
}
}
public static void main(String[] a){
JFrame f = new JFrame("Presentation Model Validation Example");
f.setDefaultCloseOperation(2);
f.add(new ValidatingPresentationModelExample());
f.pack();
f.setVisible(true);
}
}
Validation How to Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.validation.ValidationResult;
import com.jgoodies.validation.util.DefaultValidationResultModel;
import com.jgoodies.validation.util.ValidationResultModel;
import com.jgoodies.validation.util.ValidationUtils;
import com.jgoodies.validation.view.ValidationResultViewFactory;
public class ValidationHowExample extends JPanel {
private JTextField nameField;
private JTextField siteField;
private JTextField feedField;
private Feed feed;
private ValidationResultModel validationResultModel;
private ShowFeedInformationAction showFeedInformationAction;
public ValidationHowExample() {
DefaultFormBuilder formBuilder = new DefaultFormBuilder(new FormLayout(""));
formBuilder.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
formBuilder.appendColumn("right:pref");
formBuilder.appendColumn("3dlu");
formBuilder.appendColumn("fill:p:g");
this.nameField = new JTextField();
formBuilder.append("Name:", this.nameField);
this.siteField = new JTextField();
formBuilder.append("Site Url:", this.siteField);
this.feedField = new JTextField();
formBuilder.append("Feed Url:", this.feedField);
this.validationResultModel = new DefaultValidationResultModel();
this.validationResultModel.addPropertyChangeListener(new ValidationListener());
JComponent validationResultsComponent = ValidationResultViewFactory.createReportList(validationResultModel);
formBuilder.appendRow("top:30dlu:g");
CellConstraints cc = new CellConstraints();
formBuilder.add(validationResultsComponent, cc.xywh(1, formBuilder.getRow() + 1, 3, 1, "fill, fill"));
formBuilder.nextLine(2);
formBuilder.append(new JButton(new ValidateAction()), 3);
this.showFeedInformationAction = new ShowFeedInformationAction();
formBuilder.append(new JButton(this.showFeedInformationAction), 3);
createFeed();
initializeFormElements();
add(formBuilder.getPanel());
}
private ValidationResult validateIt() {
ValidationResult validationResult = new ValidationResult();
if (ValidationUtils.isEmpty(this.nameField.getText())) {
validationResult.addError("The name field can not be blank.");
} else if (!ValidationUtils.hasBoundedLength(this.nameField.getText(), 5, 14)) {
validationResult.addError("The name field must be between 5 and 14 characters.");
}
if (!"ClientJava.ru".equals(this.nameField.getText())) {
validationResult.addWarning("This form prefers the feed ClientJava.ru");
}
if (ValidationUtils.isEmpty(this.feedField.getText())) {
validationResult.addError("The feed field can not be blank.");
}
if (ValidationUtils.isEmpty(this.siteField.getText())) {
validationResult.addError("The site field can not be blank.");
}
return validationResult;
}
private class ValidationListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName() == ValidationResultModel.PROPERTYNAME_RESULT) {
JOptionPane.showMessageDialog(null, "Validation has been performed");
showFeedInformationAction.setEnabled(!validationResultModel.hasErrors());
} else if (evt.getPropertyName() == ValidationResultModel.PROPERTYNAME_MESSAGES) {
if (Boolean.TRUE.equals(evt.getNewValue())) {
JOptionPane.showMessageDialog(null, "Messages have been found.");
}
}
}
}
private Feed getFeed() {
return this.feed;
}
private void createFeed() {
this.feed = new Feed();
this.feed.setName("ClientJava.ru");
this.feed.setSiteUrl("http://www.clientjava.ru/blog");
this.feed.setFeedUrl("http://www.clientjava.ru/blog/rss.xml");
}
private void initializeFormElements() {
this.nameField.setText(this.feed.getName());
this.siteField.setText(this.feed.getSiteUrl());
this.feedField.setText(this.feed.getFeedUrl());
}
private void synchFormAndFeed() {
this.feed.setName(this.nameField.getText());
this.feed.setSiteUrl(this.siteField.getText());
this.feed.setFeedUrl(this.feedField.getText());
}
private class ValidateAction extends AbstractAction {
public ValidateAction() {
super("Validate");
}
public void actionPerformed(ActionEvent e) {
synchFormAndFeed();
ValidationResult validationResult = validateIt();
validationResultModel.setResult(validationResult);
}
}
private class ShowFeedInformationAction extends AbstractAction {
public ShowFeedInformationAction() {
super("Show Feed Information");
setEnabled(false);
}
public void actionPerformed(ActionEvent event) {
StringBuffer message = new StringBuffer();
message.append("<html>");
message.append("<b>Name:</b> ");
message.append(getFeed().getName());
message.append("<br>");
message.append("<b>Site URL:</b> ");
message.append(getFeed().getSiteUrl());
message.append("<br>");
message.append("<b>Feed URL:</b> ");
message.append(getFeed().getFeedUrl());
message.append("</html>");
JOptionPane.showMessageDialog(null, message.toString());
}
}
public static void main(String[] a){
JFrame f = new JFrame("How To Validate Example");
f.setDefaultCloseOperation(2);
f.add(new ValidationHowExample());
f.pack();
f.setVisible(true);
}
}
Validation Icons Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.validation.Severity;
import com.jgoodies.validation.view.ValidationResultViewFactory;
public class ValidationIconsExample extends JPanel {
public ValidationIconsExample() {
DefaultFormBuilder formBuilder = new DefaultFormBuilder(new FormLayout("right:pref, 3dlu, p:g"));
formBuilder.setDefaultDialogBorder();
formBuilder.append("Check Icon", new JLabel(ValidationResultViewFactory.getCheckIcon()));
formBuilder.appendSeparator();
formBuilder.append("Error Icon", new JLabel(ValidationResultViewFactory.getErrorIcon()));
formBuilder.appendSeparator();
formBuilder.append("Info Icon", new JLabel(ValidationResultViewFactory.getInfoIcon()));
formBuilder.appendSeparator();
formBuilder.append("Warning Icon", new JLabel(ValidationResultViewFactory.getWarningIcon()));
formBuilder.appendSeparator();
formBuilder.append("Severity.ERROR Icon", new JLabel(ValidationResultViewFactory.getIcon(Severity.ERROR)));
formBuilder.appendSeparator();
formBuilder.append("Small Error Icon", new JLabel(ValidationResultViewFactory.getSmallErrorIcon()));
formBuilder.appendSeparator();
formBuilder.append("Small Info Icon", new JLabel(ValidationResultViewFactory.getSmallInfoIcon()));
formBuilder.appendSeparator();
formBuilder.append("Small Warning Icon", new JLabel(ValidationResultViewFactory.getSmallWarningIcon()));
formBuilder.appendSeparator();
formBuilder.append("Small Severity.ERROR Icon", new JLabel(ValidationResultViewFactory.getSmallIcon(Severity.ERROR)));
add(formBuilder.getPanel());
}
public static void main(String[] a){
JFrame f = new JFrame("Validation Icons Example");
f.setDefaultCloseOperation(2);
f.add(new ValidationIconsExample());
f.pack();
f.setVisible(true);
}
}
Validation Results View Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.validation.ValidationResult;
import com.jgoodies.validation.util.DefaultValidationResultModel;
import com.jgoodies.validation.util.ValidationResultModel;
import com.jgoodies.validation.view.ValidationResultViewFactory;
public class ValidationResultsViewExample extends JPanel {
private ValidationResultModel validationResultModel;
public ValidationResultsViewExample() {
PanelBuilder panelBuilder = new PanelBuilder(new FormLayout("right:pref, 3dlu, p:g"));
panelBuilder.setDefaultDialogBorder();
this.validationResultModel = new DefaultValidationResultModel();
CellConstraints cc = new CellConstraints();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 4));
panel.add(new JButton(new SetValidationResults("Empty")));
panel.add(new JButton(new SetValidationResults("Errors")));
panel.add(new JButton(new SetValidationResults("Warnings")));
panel.add(new JButton(new SetValidationResults("Mixed")));
panelBuilder.appendRow("t:30dlu");
panelBuilder.add(panel, cc.xywh(1, panelBuilder.getRow(), 3, 1));
panelBuilder.nextLine();
panelBuilder.appendRow("t:30dlu");
panelBuilder.addLabel("Icon and Text Label", cc.xy(1, panelBuilder.getRow()));
panelBuilder.add(ValidationResultViewFactory.createReportIconAndTextLabel(this.validationResultModel), cc.xy(3, panelBuilder.getRow()));
panelBuilder.nextLine();
panelBuilder.appendRow("2dlu");
panelBuilder.nextLine();
panelBuilder.appendRow("t:30dlu");
panelBuilder.addLabel("Icon and TextPane", cc.xy(1, panelBuilder.getRow()));
panelBuilder.add(ValidationResultViewFactory.createReportIconAndTextPane(this.validationResultModel), cc.xy(3, panelBuilder.getRow()));
panelBuilder.nextLine();
panelBuilder.appendRow("2dlu");
panelBuilder.nextLine();
panelBuilder.appendRow("t:30dlu");
panelBuilder.addLabel("Icon Label", cc.xy(1, panelBuilder.getRow()));
panelBuilder.add(ValidationResultViewFactory.createReportIconLabel(this.validationResultModel), cc.xy(3, panelBuilder.getRow()));
panelBuilder.nextLine();
panelBuilder.appendRow("2dlu");
panelBuilder.nextLine();
panelBuilder.appendRow("t:30dlu");
panelBuilder.addLabel("Report List", cc.xy(1, panelBuilder.getRow()));
panelBuilder.add(ValidationResultViewFactory.createReportList(this.validationResultModel), cc.xy(3, panelBuilder.getRow()));
panelBuilder.nextLine();
panelBuilder.appendRow("2dlu");
panelBuilder.nextLine();
panelBuilder.appendRow("t:30dlu");
panelBuilder.addLabel("Report List with Color", cc.xy(1, panelBuilder.getRow()));
panelBuilder.add(ValidationResultViewFactory.createReportList(this.validationResultModel, Color.white), cc.xy(3, panelBuilder.getRow()));
panelBuilder.nextLine();
panelBuilder.appendRow("2dlu");
panelBuilder.nextLine();
panelBuilder.appendRow("t:30dlu");
panelBuilder.addLabel("Text Area", cc.xy(1, panelBuilder.getRow()));
panelBuilder.add(ValidationResultViewFactory.createReportTextArea(this.validationResultModel), cc.xy(3, panelBuilder.getRow()));
panelBuilder.nextLine();
panelBuilder.appendRow("2dlu");
panelBuilder.nextLine();
panelBuilder.appendRow("t:30dlu");
panelBuilder.addLabel("Text Area with Color", cc.xy(1, panelBuilder.getRow()));
panelBuilder.add(ValidationResultViewFactory.createReportTextArea(this.validationResultModel, Color.white), cc.xy(3, panelBuilder.getRow()));
panelBuilder.nextLine();
panelBuilder.appendRow("2dlu");
panelBuilder.nextLine();
panelBuilder.appendRow("t:30dlu");
panelBuilder.addLabel("Text Pane", cc.xy(1, panelBuilder.getRow()));
panelBuilder.add(ValidationResultViewFactory.createReportTextPane(this.validationResultModel), cc.xy(3, panelBuilder.getRow()));
panelBuilder.nextLine();
panelBuilder.appendRow("2dlu");
panelBuilder.nextLine();
panelBuilder.appendRow("t:30dlu");
panelBuilder.addLabel("Text Pane with Color", cc.xy(1, panelBuilder.getRow()));
panelBuilder.add(ValidationResultViewFactory.createReportTextPane(this.validationResultModel, Color.white), cc.xy(3, panelBuilder.getRow()));
panelBuilder.nextLine();
add(panelBuilder.getPanel());
}
private class SetValidationResults extends AbstractAction {
public SetValidationResults(String name) {
super(name);
}
public void actionPerformed(ActionEvent e) {
if ("Errors".equals(this.getValue(Action.NAME))) {
validationResultModel.setResult(createErrorResult());
} else if ("Mixed".equals(this.getValue(Action.NAME))) {
validationResultModel.setResult(createMixedResult());
} else if ("Warnings".equals(this.getValue(Action.NAME))) {
validationResultModel.setResult(createWarningResult());
} else if ("Empty".equals(this.getValue(Action.NAME))) {
validationResultModel.setResult(createEmptyResult());
}
}
}
private ValidationResult createEmptyResult() {
return ValidationResult.EMPTY;
}
private ValidationResult createErrorResult() {
ValidationResult validationResult = new ValidationResult();
validationResult.addError("Error message one.");
validationResult.addError("Error message two.");
validationResult.addError("Error message three.");
return validationResult;
}
private ValidationResult createWarningResult() {
ValidationResult validationResult = new ValidationResult();
validationResult.addWarning("Warning message one.");
validationResult.addWarning("Warning message two.");
validationResult.addWarning("Warning message three.");
return validationResult;
}
private ValidationResult createMixedResult() {
ValidationResult validationResult = new ValidationResult();
validationResult.addError("Error message one.");
validationResult.addWarning("Warning message one.");
validationResult.addWarning("Warning message two.");
validationResult.addError("Error message two.");
validationResult.addError("Error message three.");
validationResult.addWarning("Warning message three.");
return validationResult;
}
public static void main(String[] a){
JFrame f = new JFrame("Validation Results View Example");
f.setDefaultCloseOperation(2);
f.add(new ValidationResultsViewExample());
f.pack();
f.setVisible(true);
}
}