Java/Swing Components/Data Binding
Содержание
- 1 Builds an editor that copies data from the domain back and forth
- 2 Builds an editor with components bound to the domain object properties
- 3 Demonstrates three different styles when to commit changes
- 4 JGoodies Binding: Abstract Table Model Example
- 5 JGoodies Binding: Basic Component Factory Example
- 6 JGoodies Binding: Bean Adapter Example
- 7 JGoodies Binding: Bounded Range Adapter Example
- 8 JGoodies Binding: Buffering Presentation Model Example
- 9 JGoodies Binding: ComboBox Adapter Example
- 10 JGoodies Binding: Converter Factory Example
- 11 JGoodies Binding: Feed Bean Example 1
- 12 JGoodies Binding: Feed Bean Example 2
- 13 JGoodies Binding: Feed Bean Example 3
- 14 JGoodies Binding: Presentation Bean Channel Example
- 15 JGoodies Binding: Presentation Bean Property Change Listener Example
- 16 JGoodies Binding: Presentation Model Property Change Example
- 17 JGoodies Binding: Property Adapter Example 1
- 18 JGoodies Binding: Property Adapter Example 2
- 19 JGoodies Binding: Property Adapter Example 3
- 20 JGoodies Binding: Property Connector Example
- 21 JGoodies Binding: Radio Button Adapter Example
- 22 JGoodies Binding: Selection In List Bean Channel Example
- 23 JGoodies Binding: Selection In List Example
- 24 JGoodies Binding: Selection In List Model Example
- 25 JGoodies Binding: Toggle Button Adapter Example
- 26 JGoodies Binding: Value Holder Example
- 27 Swingx: Swing Data Binding
- 28 Using buffered adapting ValueModels created by a PresentationModel
Builds an editor that copies data from the domain back and forth
/*
* Copyright (c) 2002-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.binding.tutorial.basics;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.JTextComponent;
import com.jgoodies.binding.tutorial.Album;
import com.jgoodies.binding.tutorial.TutorialUtils;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.factories.ButtonBarFactory;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
/**
* Builds an editor that copies data from the domain back and forth.
* This approach is known as the "copying" approach or "push/pull".<p>
*
* The event handling used to enable and disable the composer text field
* is invoked by a ChangeListener that hooks into the classical check box.
* Note that this lacks the domain logic, where the composer is set to
* <code>null</code> if the classical property is set to false.
* This logic is deferred until the component values are written to the
* edited Album via <code>#updateModel</code> when OK is pressed.
*
* @author Karsten Lentzsch
* @version $Revision: 1.6 $
*/
public class EditorCopyingExample {
/**
* Refers to the Album that is to be edited by this example editor.
*/
private final Album editedAlbum;
private JTextComponent titleField;
private JTextComponent artistField;
private JCheckBox classicalBox;
private JTextComponent composerField;
private JButton okButton;
private JButton cancelButton;
private JButton resetButton;
// Launching **************************************************************
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
} catch (Exception e) {
// Likely PlasticXP is not in the class path; ignore.
}
JFrame frame = new JFrame();
frame.setTitle("Binding Tutorial :: Editor (Copying)");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
EditorCopyingExample example = new EditorCopyingExample();
JComponent panel = example.build();
example.updateView();
frame.getContentPane().add(panel);
frame.pack();
TutorialUtils.locateOnScreenCenter(frame);
frame.setVisible(true);
}
// Instance Creation ******************************************************
/**
* Constructs an editor for an example Album.
*/
public EditorCopyingExample() {
this(Album.ALBUM1);
}
/**
* Constructs an editor for an Album to be edited.
*
* @param album the Album to be edited
*/
public EditorCopyingExample(Album album) {
this.editedAlbum = album;
}
// Initialization *********************************************************
/**
* Creates and intializes the UI components.
*/
private void initComponents() {
titleField = new JTextField();
artistField = new JTextField();
classicalBox = new JCheckBox("Classical");
composerField = new JTextField();
okButton = new JButton(new OKAction());
cancelButton = new JButton(new CancelAction());
resetButton = new JButton(new ResetAction());
updateComposerField();
}
/**
* Observes the classical check box to update the composer field"s
* enablement and contents. For demonstration purposes a listener
* is registered that writes all changes to the console.
*/
private void initEventHandling() {
classicalBox.addChangeListener(new ClassicalChangeHandler());
// Report changes in all bound Album properties.
editedAlbum.addPropertyChangeListener(
TutorialUtils.createDebugPropertyChangeListener());
}
// Copying Data Back and Forth ********************************************
/**
* Reads the property values from the edited Album
* and sets them in this editor"s components.
*/
private void updateView() {
titleField.setText(editedAlbum.getTitle());
artistField.setText(editedAlbum.getArtist());
classicalBox.setSelected(editedAlbum.isClassical());
composerField.setText(editedAlbum.getComposer());
}
/**
* Reads the values from this editor"s components
* and set the associated Album properties.
*/
private void updateModel() {
editedAlbum.setTitle(titleField.getText());
editedAlbum.setArtist(artistField.getText());
editedAlbum.setClassical(classicalBox.isSelected());
editedAlbum.setComposer(composerField.getText());
}
// Building ***************************************************************
/**
* Builds and returns the editor panel.
*
* @return the built panel
*/
public JComponent build() {
initComponents();
initEventHandling();
FormLayout layout = new FormLayout(
"right:pref, 3dlu, 150dlu:grow",
"p, 3dlu, p, 3dlu, p, 3dlu, p, 9dlu, p");
PanelBuilder builder = new PanelBuilder(layout);
builder.setDefaultDialogBorder();
CellConstraints cc = new CellConstraints();
builder.addLabel("Title", cc.xy (1, 1));
builder.add(titleField, cc.xy (3, 1));
builder.addLabel("Artist", cc.xy (1, 3));
builder.add(artistField, cc.xy (3, 3));
builder.add(classicalBox, cc.xy (3, 5));
builder.addLabel("Composer", cc.xy (1, 7));
builder.add(composerField, cc.xy (3, 7));
builder.add(buildButtonBar(), cc.xyw(1, 9, 3));
return builder.getPanel();
}
private JComponent buildButtonBar() {
return ButtonBarFactory.buildRightAlignedBar(
okButton, cancelButton, resetButton);
}
// Event Handling *********************************************************
/**
* Updates the composer field"s enablement and contents.
* Sets the enablement according to the selection state
* of the classical check box. If the composer is not enabled,
* we copy the domain logic and clear the composer field"s text.
*/
private void updateComposerField() {
boolean composerEnabled = classicalBox.isSelected();
composerField.setEnabled(composerEnabled);
if (!composerEnabled) {
composerField.setText("");
}
}
private class ClassicalChangeHandler implements ChangeListener {
/**
* The selection state of the classical check box has changed.
* Updates the enablement and contents of the composer field.
*/
public void stateChanged(ChangeEvent evt) {
updateComposerField();
}
}
// Actions ****************************************************************
private final class OKAction extends AbstractAction {
private OKAction() {
super("OK");
}
public void actionPerformed(ActionEvent e) {
updateModel();
System.out.println(editedAlbum);
System.exit(0);
}
}
private final class CancelAction extends AbstractAction {
private CancelAction() {
super("Cancel");
}
public void actionPerformed(ActionEvent e) {
// Just ignore the current content.
System.out.println(editedAlbum);
System.exit(0);
}
}
private final class ResetAction extends AbstractAction {
private ResetAction() {
super("Reset");
}
public void actionPerformed(ActionEvent e) {
updateView();
System.out.println(editedAlbum);
}
}
}
Builds an editor with components bound to the domain object properties
/*
* Copyright (c) 2002-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.binding.tutorial.basics;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.text.JTextComponent;
import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.beans.PropertyConnector;
import com.jgoodies.binding.tutorial.Album;
import com.jgoodies.binding.tutorial.AlbumPresentationModel;
import com.jgoodies.binding.tutorial.TutorialUtils;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.factories.ButtonBarFactory;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
/**
* Builds an editor with components bound to the domain object properties
* using adapting ValueModels created by a PresentationModel.
*
* @author Karsten Lentzsch
* @version $Revision: 1.7 $
*
* @see com.jgoodies.binding.PresentationModel
*/
public class EditorBoundExample {
/**
* Holds the edited Album and vends ValueModels that adapt Album properties.
*/
private final AlbumPresentationModel presentationModel;
private JTextComponent titleField;
private JTextComponent artistField;
private JCheckBox classicalBox;
private JTextComponent composerField;
private JButton closeButton;
// Launching **************************************************************
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
} catch (Exception e) {
// Likely PlasticXP is not in the class path; ignore.
}
JFrame frame = new JFrame();
frame.setTitle("Binding Tutorial :: Editor (Bound)");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
EditorBoundExample example = new EditorBoundExample();
JComponent panel = example.build();
frame.getContentPane().add(panel);
frame.pack();
TutorialUtils.locateOnScreenCenter(frame);
frame.setVisible(true);
}
// Instance Creation ******************************************************
/**
* Constructs an editor on an Album example instance.
*/
public EditorBoundExample() {
this(Album.ALBUM1);
}
/**
* Constructs an editor for an Album to be edited.
*
* @param album the Album to be edited
*/
public EditorBoundExample(Album album) {
this.presentationModel = new AlbumPresentationModel(album);
}
// Initialization *********************************************************
/**
* Creates, binds and configures the UI components.
* Changes are committed to the value models on focus lost.<p>
*
* The coding style used here is based on standard Swing components.
* Therefore we can create and bind the components in one step.
* And that"s the purpose of the BasicComponentFactory class.<p>
*
* If you need to bind custom components, for example MyTextField,
* MyCheckBox, MyComboBox, you can use the more basic Bindings class.
* The code would then read:<pre>
* titleField = new MyTextField();
* Bindings.bind(titleField,
* presentationModel.getModel(Album.PROPERTYNAME_TITLE));
* </pre><p>
*
* I strongly recommend to use a custom ComponentFactory,
* the BasicComponentFactory or the Bindings class. These classes
* hide details of the binding.
* So you better <em>not</em> write the following code:<pre>
* titleField = new JTextField();
* titleField.setDocument(new DocumentAdapter(
* presentationModel.getModel(Album.PROPERTYNAME_TITLE)));
* </pre>
*/
private void initComponents() {
titleField = BasicComponentFactory.createTextField(
presentationModel.getModel(Album.PROPERTYNAME_TITLE));
artistField = BasicComponentFactory.createTextField(
presentationModel.getModel(Album.PROPERTYNAME_ARTIST));
classicalBox = BasicComponentFactory.createCheckBox(
presentationModel.getModel(Album.PROPERTYNAME_CLASSICAL),
"Classical");
composerField = BasicComponentFactory.createTextField(
presentationModel.getModel(Album.PROPERTYNAME_COMPOSER));
closeButton = new JButton(new CloseAction());
boolean composerEnabled = presentationModel.isComposerEnabled();
composerField.setEnabled(composerEnabled);
}
/**
* Registers a listener with the presentation model"s "composerEnabled"
* property to switch the composer field"s enablement. For demonstration
* purposes a listener is registered that writes changes to the console.
*/
private void initEventHandling() {
// Synchronize the composer field enablement with "composerEnabled".
PropertyConnector.connect(
composerField, "enabled",
presentationModel, AlbumPresentationModel.PROPERTYNAME_COMPOSER_ENABLED);
// Report changes in all bound Album properties.
presentationModel.addBeanPropertyChangeListener(
TutorialUtils.createDebugPropertyChangeListener());
}
// Building ***************************************************************
/**
* Builds and returns the panel.
*
* @return the built panel
*/
public JComponent build() {
initComponents();
initEventHandling();
FormLayout layout = new FormLayout(
"right:pref, 3dlu, 150dlu:grow",
"p, 3dlu, p, 3dlu, p, 3dlu, p, 9dlu, p");
PanelBuilder builder = new PanelBuilder(layout);
builder.setDefaultDialogBorder();
CellConstraints cc = new CellConstraints();
builder.addLabel("Title", cc.xy (1, 1));
builder.add(titleField, cc.xy (3, 1));
builder.addLabel("Artist", cc.xy (1, 3));
builder.add(artistField, cc.xy (3, 3));
builder.add(classicalBox, cc.xy (3, 5));
builder.addLabel("Composer", cc.xy (1, 7));
builder.add(composerField, cc.xy (3, 7));
builder.add(buildButtonBar(), cc.xyw(1, 9, 3));
return builder.getPanel();
}
private JComponent buildButtonBar() {
return ButtonBarFactory.buildRightAlignedBar(
closeButton);
}
// Presentation Model *****************************************************
/**
* An Action that prints the current bean to the System console
* before it exists the System.
*
* Actions belong to the presentation model. However, to keep
* this tutorial small I"ve chosen to reuse a single presentation model
* for all album examples and so, couldn"t put in different close actions.
*/
private final class CloseAction extends AbstractAction {
private CloseAction() {
super("Close");
}
public void actionPerformed(ActionEvent e) {
System.out.println(presentationModel.getBean());
System.exit(0);
}
}
}
Demonstrates three different styles when to commit changes
/*
* Copyright (c) 2002-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.binding.tutorial.basics;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.text.JTextComponent;
import com.jgoodies.binding.PresentationModel;
import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.beans.Model;
import com.jgoodies.binding.tutorial.TutorialUtils;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.factories.ButtonBarFactory;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
/**
* Demonstrates three different styles when to commit changes:
* on key typed, on focus lost, on OK/Apply pressed.
* Therefore we bind 3 JTextFields to 3 String typed ValueModels
* that honor the commit style. And we bind 3 JLabels directly
* to these ValueModels that display the current value.<p>
*
* The ValueModels used in this example are requested from a
* PresentationModel that adapts text properties of a TextBean.
* This is just to demonstrate a consistent binding style.
* The same techniques work with any ValueModel.
*
* @author Karsten Lentzsch
* @version $Revision: 1.4 $
*
* @see com.jgoodies.binding.PresentationModel
*/
public class CommitStylesExample {
/**
* Holds a TextBean and vends ValueModels that adapt TextBean properties.
* As an alternative to this PresentationModel we could use 3 ValueModels,
* for example 3 ValueHolders, or any other ValueModel implementation.
*/
private final PresentationModel presentationModel;
private JTextComponent onKeyTypedField;
private JTextComponent onFocusLostField;
private JTextComponent onApplyField;
private JLabel onKeyTypedLabel;
private JLabel onFocusLostLabel;
private JLabel onApplyLabel;
private JButton applyButton;
// Launching **************************************************************
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
} catch (Exception e) {
// Likely PlasticXP is not in the class path; ignore.
}
JFrame frame = new JFrame();
frame.setTitle("Binding Tutorial :: Commit Styles");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
CommitStylesExample example = new CommitStylesExample();
JComponent panel = example.build();
frame.getContentPane().add(panel);
frame.pack();
TutorialUtils.locateOnScreenCenter(frame);
frame.setVisible(true);
}
// Instance Creation ******************************************************
/**
* Constructs the example with a PresentationModel on the a TextBean.
*/
public CommitStylesExample() {
this.presentationModel = new PresentationModel(new TextBean());
}
// Component Creation and Initialization **********************************
/**
* Creates,binds and configures the UI components.<p>
*/
private void initComponents() {
onKeyTypedField = BasicComponentFactory.createTextField(
presentationModel.getModel(TextBean.PROPERTYNAME_TEXT1), false);
onKeyTypedLabel = BasicComponentFactory.createLabel(
presentationModel.getModel(TextBean.PROPERTYNAME_TEXT1));
onFocusLostField = BasicComponentFactory.createTextField(
presentationModel.getModel(TextBean.PROPERTYNAME_TEXT2));
onFocusLostLabel = BasicComponentFactory.createLabel(
presentationModel.getModel(TextBean.PROPERTYNAME_TEXT2));
onApplyField = BasicComponentFactory.createTextField(
presentationModel.getBufferedModel(TextBean.PROPERTYNAME_TEXT3));
onApplyLabel = BasicComponentFactory.createLabel(
presentationModel.getModel(TextBean.PROPERTYNAME_TEXT3));
applyButton = new JButton(new ApplyAction());
}
// Building ***************************************************************
/**
* Builds the pane.
*
* @return the built panel
*/
public JComponent build() {
initComponents();
FormLayout layout = new FormLayout(
"right:max(50dlu;pref), 3dlu, 50dlu, 9dlu, 50dlu",
"p, 6dlu, p, 3dlu, p, 3dlu, p, 17dlu, p");
PanelBuilder builder = new PanelBuilder(layout);
builder.setDefaultDialogBorder();
CellConstraints cc = new CellConstraints();
builder.addTitle("Commit Style", cc.xy (1, 1));
builder.addTitle("Value", cc.xy (5, 1));
builder.addLabel("Key Typed", cc.xy (1, 3));
builder.add(onKeyTypedField, cc.xy (3, 3));
builder.add(onKeyTypedLabel, cc.xy (5, 3));
builder.addLabel("Focus Lost", cc.xy (1, 5));
builder.add(onFocusLostField, cc.xy (3, 5));
builder.add(onFocusLostLabel, cc.xy (5, 5));
builder.addLabel("Apply Pressed", cc.xy (1, 7));
builder.add(onApplyField, cc.xy (3, 7));
builder.add(onApplyLabel, cc.xy (5, 7));
builder.add(buildButtonBar(), cc.xyw(1, 9, 5));
return builder.getPanel();
}
private JComponent buildButtonBar() {
return ButtonBarFactory.buildRightAlignedBar(
applyButton);
}
// Actions ****************************************************************
private final class ApplyAction extends AbstractAction {
private ApplyAction() {
super("Apply");
}
public void actionPerformed(ActionEvent e) {
presentationModel.triggerCommit();
}
}
// Helper Class ***********************************************************
/**
* A simple bean that just provides three bound read-write text properties.
*/
public static final class TextBean extends Model {
// Names for the Bound Bean Properties ---------------------
public static final String PROPERTYNAME_TEXT1 = "text1";
public static final String PROPERTYNAME_TEXT2 = "text2";
public static final String PROPERTYNAME_TEXT3 = "text3";
private String text1;
private String text2;
private String text3;
// Instance Creation ---------------------------------------
private TextBean() {
text1 = "Text1";
text2 = "Text2";
text3 = "Text3";
}
// Accessors -----------------------------------------------
public String getText1() {
return text1;
}
public void setText1(String newText1) {
String oldText1 = getText1();
text1 = newText1;
firePropertyChange(PROPERTYNAME_TEXT1, oldText1, newText1);
}
public String getText2() {
return text2;
}
public void setText2(String newText2) {
String oldText2 = getText2();
text2 = newText2;
firePropertyChange(PROPERTYNAME_TEXT2, oldText2, newText2);
}
public String getText3() {
return text3;
}
public void setText3(String newText3) {
String oldText3 = getText3();
text3 = newText3;
firePropertyChange(PROPERTYNAME_TEXT3, oldText3, newText3);
}
}
}
JGoodies Binding: Abstract Table Model Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListModel;
import com.jgoodies.binding.adapter.AbstractTableAdapter;
import com.jgoodies.binding.adapter.Bindings;
import com.jgoodies.binding.adapter.SingleListSelectionAdapter;
import com.jgoodies.binding.list.ArrayListModel;
import com.jgoodies.binding.list.SelectionInList;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class AbstractTableModelExample extends JPanel {
private ArrayListModel arrayListModel;
public AbstractTableModelExample() {
super(new BorderLayout());
DefaultFormBuilder defaultFormBuilder = new DefaultFormBuilder(new FormLayout("p, 2dlu, p:g"));
defaultFormBuilder.setDefaultDialogBorder();
this.arrayListModel = new ArrayListModel();
this.arrayListModel.add(new DisplayTechnology("Swing", "Is a Java API", "Sun"));
this.arrayListModel.add(new DisplayTechnology("Flash", "Is NOT a Java API", "Macromedia"));
this.arrayListModel.add(new DisplayTechnology("SWT", "Is a Java API", "Eclipse"));
this.arrayListModel.add(new DisplayTechnology("QT", "Is NOT a Java API", "Trolltech"));
this.arrayListModel.add(new DisplayTechnology("AWT", "Is a Java API", "Sun"));
SelectionInList selectionInList = new SelectionInList((ListModel) this.arrayListModel);
JList jlist = new JList();
Bindings.bind(jlist, selectionInList);
defaultFormBuilder.append("List Model: ", new JScrollPane(jlist));
JTable table = new JTable(new DisplayTechnologyTableAdapter(selectionInList, new String[]{"Name", "Description",
"Maker"}));
table.setSelectionModel(new SingleListSelectionAdapter(
selectionInList.getSelectionIndexHolder()));
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(table.getPreferredSize());
defaultFormBuilder.append("Table", scrollPane);
add(defaultFormBuilder.getPanel());
}
private class DisplayTechnology {
private String name;
private String description;
private String maker;
public DisplayTechnology(String name, String description, String maker) {
this.name = name;
this.description = description;
this.maker = maker;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getMaker() {
return maker;
}
public String toString() {
return name;
}
}
private class DisplayTechnologyTableAdapter extends AbstractTableAdapter {
public DisplayTechnologyTableAdapter(ListModel listModel, String[] columnNames) {
super(listModel, columnNames);
}
public Object getValueAt(int rowIndex, int columnIndex) {
DisplayTechnology displayTechnology = (DisplayTechnology) getRow(rowIndex);
if (columnIndex == 0) {
return displayTechnology.getName();
} else if (columnIndex == 1) {
return displayTechnology.getDescription();
} else {
return displayTechnology.getMaker();
}
}
}
public static void main(String[] a){
JFrame f = new JFrame("Abstract TableModel Example");
f.setDefaultCloseOperation(2);
f.add(new AbstractTableModelExample());
f.pack();
f.setVisible(true);
}
}
JGoodies Binding: Basic Component Factory Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import com.jgoodies.binding.adapter.BasicComponentFactory;
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 javax.swing.*;
public class BasicComponentFactoryExample extends JPanel {
public JPanel createPanel() {
DefaultFormBuilder defaultFormBuilder =
new DefaultFormBuilder(new FormLayout("p, 2dlu, p:g"));
defaultFormBuilder.setDefaultDialogBorder();
ValueModel longModel = new ValueHolder();
ValueModel dateModel = new ValueHolder();
ValueModel stringModel = new ValueHolder();
defaultFormBuilder.append("Integer Field:",
BasicComponentFactory.createIntegerField(longModel, 3));
defaultFormBuilder.append("Long Field:",
BasicComponentFactory.createLongField(longModel, 2));
defaultFormBuilder.append("Date Field:",
BasicComponentFactory.createDateField(dateModel));
defaultFormBuilder.nextLine();
defaultFormBuilder.append("Text Field:",
BasicComponentFactory.createTextField(stringModel, true));
defaultFormBuilder.append("Password Field:",
BasicComponentFactory.createPasswordField(stringModel, false));
defaultFormBuilder.append("Text Area:",
BasicComponentFactory.createTextArea(stringModel));
return defaultFormBuilder.getPanel();
}
public static void main(String[] a){
JFrame f = new JFrame("Basic Component Factory Example");
f.setDefaultCloseOperation(2);
f.add(new ValueHolderExample());
f.pack();
f.setVisible(true);
}
}
JGoodies Binding: Bean Adapter Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
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.beans.BeanAdapter;
import com.jgoodies.binding.beans.Model;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class BeanAdapterExample extends JPanel {
private PersonBean personBean;
public BeanAdapterExample() {
DefaultFormBuilder defaultFormBuilder = new DefaultFormBuilder(new FormLayout("p, 2dlu, p:g"));
defaultFormBuilder.setDefaultDialogBorder();
this.personBean = new PersonBean("Scott", "Delap");
BeanAdapter beanAdapter = new BeanAdapter(this.personBean, true);
ValueModel firstNameAdapter = beanAdapter.getValueModel("firstName");
ValueModel lastNameAdapter = beanAdapter.getValueModel("lastName");
JTextField firstNameTextField = BasicComponentFactory.createTextField(firstNameAdapter);
JTextField lastNameTextField = BasicComponentFactory.createTextField(lastNameAdapter);
defaultFormBuilder.append("First Name: ", firstNameTextField);
defaultFormBuilder.append("Last Name: ", lastNameTextField);
defaultFormBuilder.append(new JButton(new ConvertValueToUpperCaseAction()), 3);
defaultFormBuilder.append(new JButton(new ConvertValueToLowerCaseAction()), 3);
defaultFormBuilder.append(new JButton(new ShowValueHolderValueAction()), 3);
add(defaultFormBuilder.getPanel());
}
private class ConvertValueToUpperCaseAction extends AbstractAction {
public ConvertValueToUpperCaseAction() {
super("Convert Value To UpperCase");
}
public void actionPerformed(ActionEvent event) {
personBean.setFirstName(personBean.getFirstName().toUpperCase());
personBean.setLastName(personBean.getLastName().toUpperCase());
}
}
private class ConvertValueToLowerCaseAction extends AbstractAction {
public ConvertValueToLowerCaseAction() {
super("Convert Value To LowerCase");
}
public void actionPerformed(ActionEvent event) {
personBean.setFirstName(personBean.getFirstName().toLowerCase());
personBean.setLastName(personBean.getLastName().toLowerCase());
}
}
private class ShowValueHolderValueAction extends AbstractAction {
public ShowValueHolderValueAction() {
super("Show Value");
}
public void actionPerformed(ActionEvent event) {
StringBuffer message = new StringBuffer();
message.append("<html>");
message.append("<b>First Name:</b> ");
message.append(personBean.getFirstName());
message.append("<br><b>Last Name:</b> ");
message.append(personBean.getLastName());
message.append("</html>");
JOptionPane.showMessageDialog(null, message.toString());
}
}
public class PersonBean extends Model {
private String firstName;
private String lastName;
public static final String FIRST_NAME_PROPERTY = "firstName";
public static final String LAST_NAME_PROPERTY = "lastName";
public PersonBean(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
String oldValue = this.firstName;
this.firstName = firstName;
firePropertyChange(FIRST_NAME_PROPERTY, oldValue, this.firstName);
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
String oldValue = this.lastName;
this.lastName = lastName;
firePropertyChange(LAST_NAME_PROPERTY, oldValue, this.lastName);
}
}
public static void main(String[] a){
JFrame f = new JFrame("Bean Adapter Example");
f.setDefaultCloseOperation(2);
f.add(new BeanAdapterExample());
f.pack();
f.setVisible(true);
}
}
JGoodies Binding: Bounded Range Adapter Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.text.DecimalFormat;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import com.jgoodies.binding.adapter.BoundedRangeAdapter;
import com.jgoodies.binding.beans.PropertyConnector;
import com.jgoodies.binding.value.ConverterFactory;
import com.jgoodies.binding.value.ValueHolder;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class BoundedRangeAdapterExample extends JPanel {
public BoundedRangeAdapterExample() {
DefaultFormBuilder defaultFormBuilder = new DefaultFormBuilder(new FormLayout("p, 2dlu, p"));
defaultFormBuilder.setDefaultDialogBorder();
ValueModel percentageModel = new ValueHolder();
percentageModel.setValue(new Integer("1"));
JSlider slider = new JSlider();
BoundedRangeAdapter boundedRangeAdapter = new BoundedRangeAdapter(percentageModel, 0, 0, 100);
slider.setModel(boundedRangeAdapter);
defaultFormBuilder.append("Slider:", slider);
JLabel sliderLabel = new JLabel();
PropertyConnector propertyConnector2 = new PropertyConnector(ConverterFactory.createStringConverter(percentageModel, new DecimalFormat("#")), "value", sliderLabel, "text");
propertyConnector2.updateProperty2();
defaultFormBuilder.append("Label:", sliderLabel);
add(defaultFormBuilder.getPanel());
}
public static void main(String[] a){
JFrame f = new JFrame("Bounded Range Adapter Example");
f.setDefaultCloseOperation(2);
f.add(new BoundedRangeAdapterExample());
f.pack();
f.setVisible(true);
}
}
JGoodies Binding: Buffering Presentation Model Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
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.beans.Model;
import com.jgoodies.binding.value.Trigger;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class BufferingPresentationModelExample extends JPanel {
private PersonBean personBean;
private Trigger trigger;
private PresentationModel presentationModel;
public BufferingPresentationModelExample() {
DefaultFormBuilder defaultFormBuilder = new DefaultFormBuilder(new FormLayout("p, 2dlu, p:g"));
defaultFormBuilder.setDefaultDialogBorder();
this.personBean = new PersonBean("Scott", "Delap");
this.trigger = new Trigger();
this.presentationModel = new PresentationModel(this.personBean, this.trigger);
ValueModel firstNameAdapter = presentationModel.getBufferedModel("firstName");
ValueModel lastNameAdapter = presentationModel.getBufferedModel("lastName");
JTextField firstNameTextField = BasicComponentFactory.createTextField(firstNameAdapter);
JTextField lastNameTextField = BasicComponentFactory.createTextField(lastNameAdapter);
defaultFormBuilder.append("First Name: ", firstNameTextField);
defaultFormBuilder.append("Last Name: ", lastNameTextField);
defaultFormBuilder.append(new JButton(new FlushBufferAction()), 3);
defaultFormBuilder.append(new JButton(new CommitBufferAction()), 3);
defaultFormBuilder.append(new JButton(new ShowValueHolderValueAction()), 3);
add(defaultFormBuilder.getPanel());
}
private class CommitBufferAction extends AbstractAction {
public CommitBufferAction() {
super("Commit Buffer");
}
public void actionPerformed(ActionEvent event) {
trigger.triggerCommit();
}
}
private class FlushBufferAction extends AbstractAction {
public FlushBufferAction() {
super("Flush Buffer");
}
public void actionPerformed(ActionEvent event) {
trigger.triggerFlush();
}
}
private class ShowValueHolderValueAction extends AbstractAction {
public ShowValueHolderValueAction() {
super("Show Value");
}
public void actionPerformed(ActionEvent event) {
StringBuffer message = new StringBuffer();
message.append("<html>");
message.append("<b>First Name:</b> ");
message.append(personBean.getFirstName());
message.append("<br><b>Last Name:</b> ");
message.append(personBean.getLastName());
message.append("<br><b>Is Buffering:</b> ");
message.append(presentationModel.isBuffering());
message.append("</html>");
JOptionPane.showMessageDialog(null, message.toString());
}
}
public class PersonBean extends Model {
private String firstName;
private String lastName;
public static final String FIRST_NAME_PROPERTY = "firstName";
public static final String LAST_NAME_PROPERTY = "lastName";
public PersonBean(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
String oldValue = this.firstName;
this.firstName = firstName;
firePropertyChange(FIRST_NAME_PROPERTY, oldValue, this.firstName);
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
String oldValue = this.lastName;
this.lastName = lastName;
firePropertyChange(LAST_NAME_PROPERTY, oldValue, this.lastName);
}
}
public static void main(String[] a){
JFrame f = new JFrame("Buffering Presentation Model Example");
f.setDefaultCloseOperation(2);
f.add(new BufferingPresentationModelExample());
f.pack();
f.setVisible(true);
}
}
JGoodies Binding: ComboBox Adapter Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.adapter.ruboBoxAdapter;
import com.jgoodies.binding.value.ValueHolder;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
public class ComboBoxAdapterExample extends JPanel {
public ComboBoxAdapterExample() {
JPanel panel = new JPanel(new FormLayout("p, 2dlu, p:g", "t:p, b:d:g"));
panel.setBorder(new EmptyBorder(6, 6, 6, 6));
ArrayList strings = new ArrayList();
strings.add("Swing");
strings.add("SWT");
strings.add("HTML");
strings.add("Flash");
strings.add("QT");
CellConstraints cc = new CellConstraints();
ValueModel selectionHolder = new ValueHolder("Select A Display Technology");
ComboBoxAdapter comboBoxAdapter = new ComboBoxAdapter(strings, selectionHolder);
JComboBox comboBox = new JComboBox();
comboBox.setModel(comboBoxAdapter);
panel.add(new JLabel("Combo Box:"), cc.xy(1, 1));
panel.add(comboBox, cc.xy(3, 1));
panel.add(new JLabel("Selection:"), cc.xy(1, 2));
panel.add(BasicComponentFactory.createTextField(selectionHolder), cc.xy(3, 2));
add(panel);
}
public static void main(String[] a){
JFrame f = new JFrame("ComboBox Adapter Example");
f.setDefaultCloseOperation(2);
f.add(new ComboBoxAdapterExample());
f.pack();
f.setVisible(true);
}
}
JGoodies Binding: Converter Factory Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import javax.swing.JFrame;
import javax.swing.JPanel;
import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.value.ConverterFactory;
import com.jgoodies.binding.value.ValueHolder;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class ConverterFactoryExample extends JPanel {
public ConverterFactoryExample() {
DefaultFormBuilder defaultFormBuilder = new DefaultFormBuilder(new FormLayout("p, 2dlu, p:g"));
defaultFormBuilder.setDefaultDialogBorder();
ValueModel booleanModel = new ValueHolder(true);
ValueModel negativeBooleanModel = ConverterFactory.createBooleanNegator(booleanModel);
ValueModel stringModel = ConverterFactory.createBooleanToStringConverter(booleanModel, "Is True", "Is Not True");
defaultFormBuilder.append("CheckBox1:", BasicComponentFactory.createCheckBox(booleanModel, "True Is Checked"));
defaultFormBuilder.append("CheckBox2:", BasicComponentFactory.createCheckBox(negativeBooleanModel, "True Is NOT Checked"));
defaultFormBuilder.append("Text Field:", BasicComponentFactory.createTextField(stringModel));
add(defaultFormBuilder.getPanel());
}
public static void main(String[] a){
JFrame f = new JFrame("Converter Factory Example");
f.setDefaultCloseOperation(2);
f.add(new ConverterFactoryExample());
f.pack();
f.setVisible(true);
}
}
JGoodies Binding: Feed Bean Example 1
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.event.ActionEvent;
import java.util.Arrays;
import java.util.List;
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 FeedBeanExample1 extends JPanel {
JTextField nameField;
JTextField siteField;
JTextField feedField;
Feed feed;
public FeedBeanExample1() {
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 Feed getFeed() {
return this.feed;
}
private class ShowFeedInformationAction extends AbstractAction {
public ShowFeedInformationAction() {
super("Show Feed Information");
}
public void actionPerformed(ActionEvent event) {
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("Feed Bean Example 1");
f.setDefaultCloseOperation(2);
f.add(new FeedBeanExample1());
f.pack();
f.setVisible(true);
}
class Feed {
private long id = 0;
private String name;
private String siteUrl;
private String feedUrl;
private FeedType feedType;
private boolean customCheckIntervalEnabled = false;
private Integer checkInterval;
public Feed() {
}
public Feed(String name, String siteUrl, String feedUrl, FeedType feedType) {
this.name = name;
this.siteUrl = siteUrl;
this.feedUrl = feedUrl;
this.feedType = feedType;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String newName) {
this.name = newName;
}
public String getSiteUrl() {
return siteUrl;
}
public void setSiteUrl(String newSiteUrl) {
this.siteUrl = newSiteUrl;
}
public String getFeedUrl() {
return feedUrl;
}
public void setFeedUrl(String newFeedUrl) {
this.feedUrl = newFeedUrl;
}
public FeedType getFeedType() {
return feedType;
}
public void setFeedType(FeedType newFeedType) {
this.feedType = newFeedType;
}
public boolean isCustomCheckIntervalEnabled() {
return customCheckIntervalEnabled;
}
public void setCustomCheckIntervalEnabled(boolean newCustomCheckIntervalEnabled) {
this.customCheckIntervalEnabled = newCustomCheckIntervalEnabled;
}
public Integer getCheckInterval() {
return checkInterval;
}
public void setCheckInterval(Integer newCheckInterval) {
this.checkInterval = newCheckInterval;
}
public String toString() {
return this.name;
}
}
class FeedType {
private String type;
private FeedType(String type) {
this.type = type;
}
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof FeedType)) return false;
final FeedType feedType = (FeedType) o;
if (type != null ? !type.equals(feedType.type) : feedType.type != null) return false;
return true;
}
public int hashCode() {
return (type != null ? type.hashCode() : 0);
}
public String toString() {
return this.type;
}
public FeedType RSS_09 = new FeedType("RSS_09");
public FeedType RSS_093 = new FeedType("RSS_093");
public FeedType RSS_20 = new FeedType("RSS_20");
public FeedType ATOM_03 = new FeedType("ATOM_03");
public final List TYPES = Arrays.asList(new FeedType[]{
RSS_09, RSS_093, RSS_20, ATOM_03});
}
}
JGoodies Binding: Feed Bean Example 2
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.event.ActionEvent;
import java.util.Arrays;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
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 FeedBeanExample2 extends JPanel {
JTextField nameField;
JTextField siteField;
JTextField feedField;
JComboBox feedTypesComboBox;
JCheckBox customCheckIntervalCheckbox;
JTextField intervalField;
Feed feed;
public FeedBeanExample2() {
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.feedTypesComboBox = new JComboBox(Arrays.asList(new FeedType[]{
new FeedType("RSS_09"), new FeedType("RSS_093"), new FeedType("RSS_20"),
new FeedType("ATOM_03")}).toArray());
formBuilder.append("Feed Type:", this.feedTypesComboBox);
this.customCheckIntervalCheckbox = new JCheckBox();
formBuilder.append("Custom Check Interval:", this.customCheckIntervalCheckbox);
this.intervalField = new JTextField();
formBuilder.append("Interval:", this.intervalField);
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");
this.feed.setFeedType(new FeedType("RSS_20"));
this.feed.setCustomCheckIntervalEnabled(true);
this.feed.setCheckInterval(new Integer(4));
}
private void initializeFormElements() {
this.nameField.setText(this.feed.getName());
this.siteField.setText(this.feed.getSiteUrl());
this.feedField.setText(this.feed.getFeedUrl());
this.feedTypesComboBox.setSelectedItem(this.feed.getFeedType());
this.customCheckIntervalCheckbox.setSelected(this.feed.isCustomCheckIntervalEnabled());
if (this.feed.getCheckInterval() != null) {
this.intervalField.setText(this.feed.getCheckInterval().toString());
}
}
private void synchFormAndFeed() {
this.feed.setName(this.nameField.getText());
this.feed.setSiteUrl(this.siteField.getText());
this.feed.setFeedUrl(this.feedField.getText());
this.feed.setFeedType((FeedType) this.feedTypesComboBox.getSelectedItem());
this.feed.setCustomCheckIntervalEnabled(this.customCheckIntervalCheckbox.isSelected());
if (this.feed.isCustomCheckIntervalEnabled()) {
this.feed.setCheckInterval(new Integer(this.intervalField.getText()));
} else {
this.feed.setCheckInterval(null);
}
}
private Feed getFeed() {
return this.feed;
}
private class ShowFeedInformationAction extends AbstractAction {
public ShowFeedInformationAction() {
super("Show Feed Information");
}
public void actionPerformed(ActionEvent event) {
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("<br>");
message.append("<b>Feed Type:</b> ");
message.append(getFeed().getFeedType());
message.append("<br>");
message.append("<b>Custom Check:</b> ");
message.append(getFeed().isCustomCheckIntervalEnabled());
message.append("<br>");
message.append("<b>Check Interval:</b> ");
message.append(getFeed().getCheckInterval());
message.append("</html>");
JOptionPane.showMessageDialog(null, message.toString());
}
}
public static void main(String[] a){
JFrame f = new JFrame("Feed Bean Example 2");
f.setDefaultCloseOperation(2);
f.add(new FeedBeanExample2());
f.pack();
f.setVisible(true);
}
class Feed {
private long id = 0;
private String name;
private String siteUrl;
private String feedUrl;
private FeedType feedType;
private boolean customCheckIntervalEnabled = false;
private Integer checkInterval;
public Feed() {
}
public Feed(String name, String siteUrl, String feedUrl, FeedType feedType) {
this.name = name;
this.siteUrl = siteUrl;
this.feedUrl = feedUrl;
this.feedType = feedType;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String newName) {
this.name = newName;
}
public String getSiteUrl() {
return siteUrl;
}
public void setSiteUrl(String newSiteUrl) {
this.siteUrl = newSiteUrl;
}
public String getFeedUrl() {
return feedUrl;
}
public void setFeedUrl(String newFeedUrl) {
this.feedUrl = newFeedUrl;
}
public FeedType getFeedType() {
return feedType;
}
public void setFeedType(FeedType newFeedType) {
this.feedType = newFeedType;
}
public boolean isCustomCheckIntervalEnabled() {
return customCheckIntervalEnabled;
}
public void setCustomCheckIntervalEnabled(boolean newCustomCheckIntervalEnabled) {
this.customCheckIntervalEnabled = newCustomCheckIntervalEnabled;
}
public Integer getCheckInterval() {
return checkInterval;
}
public void setCheckInterval(Integer newCheckInterval) {
this.checkInterval = newCheckInterval;
}
public String toString() {
return this.name;
}
}
class FeedType {
private String type;
private FeedType(String type) {
this.type = type;
}
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof FeedType)) return false;
final FeedType feedType = (FeedType) o;
if (type != null ? !type.equals(feedType.type) : feedType.type != null) return false;
return true;
}
public int hashCode() {
return (type != null ? type.hashCode() : 0);
}
public String toString() {
return this.type;
}
}
}
JGoodies Binding: Feed Bean Example 3
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.event.ActionEvent;
import java.util.Arrays;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class FeedBeanExample3 extends JPanel {
JTextField nameField;
JTextField siteField;
JTextField feedField;
JComboBox feedTypesComboBox;
JCheckBox customCheckIntervalCheckbox;
JTextField intervalField;
Feed feed;
public FeedBeanExample3() {
createFeed();
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.feedTypesComboBox = new JComboBox(Arrays.asList(new FeedType[]{
new FeedType("RSS_09"), new FeedType("RSS_093"), new FeedType("RSS_20"),
new FeedType("ATOM_03")}).toArray());
formBuilder.append("Feed Type:", this.feedTypesComboBox);
CustomCheckIntervalModel customCheckIntervalModel = new CustomCheckIntervalModel(getFeed());
this.customCheckIntervalCheckbox = new JCheckBox();
this.customCheckIntervalCheckbox.setModel(customCheckIntervalModel);
formBuilder.append("Custom Check Interval:", this.customCheckIntervalCheckbox);
this.intervalField = new JTextField();
formBuilder.append("Interval:", this.intervalField);
formBuilder.append(new JButton(new ShowFeedInformationAction()), 3);
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");
this.feed.setFeedType(new FeedType("RSS_20"));
this.feed.setCustomCheckIntervalEnabled(true);
this.feed.setCheckInterval(new Integer(4));
}
private void initializeFormElements() {
this.nameField.setText(this.feed.getName());
this.siteField.setText(this.feed.getSiteUrl());
this.feedField.setText(this.feed.getFeedUrl());
this.feedTypesComboBox.setSelectedItem(this.feed.getFeedType());
if (this.feed.getCheckInterval() != null) {
this.intervalField.setText(this.feed.getCheckInterval().toString());
}
}
private void synchFormAndFeed() {
this.feed.setName(this.nameField.getText());
this.feed.setSiteUrl(this.siteField.getText());
this.feed.setFeedUrl(this.feedField.getText());
this.feed.setFeedType((FeedType) this.feedTypesComboBox.getSelectedItem());
if (this.feed.isCustomCheckIntervalEnabled()) {
this.feed.setCheckInterval(new Integer(this.intervalField.getText()));
} else {
this.feed.setCheckInterval(null);
}
}
private Feed getFeed() {
return this.feed;
}
private class ShowFeedInformationAction extends AbstractAction {
public ShowFeedInformationAction() {
super("Show Feed Information");
}
public void actionPerformed(ActionEvent event) {
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("<br>");
message.append("<b>Feed Type:</b> ");
message.append(getFeed().getFeedType());
message.append("<br>");
message.append("<b>Custom Check:</b> ");
message.append(getFeed().isCustomCheckIntervalEnabled());
message.append("<br>");
message.append("<b>Check Interval:</b> ");
message.append(getFeed().getCheckInterval());
message.append("</html>");
JOptionPane.showMessageDialog(null, message.toString());
}
}
private class CustomCheckIntervalModel extends JToggleButton.ToggleButtonModel {
private Feed feed;
public CustomCheckIntervalModel(Feed feed) {
super();
this.feed = feed;
}
public boolean isSelected() {
return feed.isCustomCheckIntervalEnabled();
}
public void setSelected(boolean b) {
feed.setCustomCheckIntervalEnabled(b);
}
}
public static void main(String[] a){
JFrame f = new JFrame("Feed Bean Example 3");
f.setDefaultCloseOperation(2);
f.add(new FeedBeanExample3());
f.pack();
f.setVisible(true);
}
class Feed {
private long id = 0;
private String name;
private String siteUrl;
private String feedUrl;
private FeedType feedType;
private boolean customCheckIntervalEnabled = false;
private Integer checkInterval;
public Feed() {
}
public Feed(String name, String siteUrl, String feedUrl, FeedType feedType) {
this.name = name;
this.siteUrl = siteUrl;
this.feedUrl = feedUrl;
this.feedType = feedType;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String newName) {
this.name = newName;
}
public String getSiteUrl() {
return siteUrl;
}
public void setSiteUrl(String newSiteUrl) {
this.siteUrl = newSiteUrl;
}
public String getFeedUrl() {
return feedUrl;
}
public void setFeedUrl(String newFeedUrl) {
this.feedUrl = newFeedUrl;
}
public FeedType getFeedType() {
return feedType;
}
public void setFeedType(FeedType newFeedType) {
this.feedType = newFeedType;
}
public boolean isCustomCheckIntervalEnabled() {
return customCheckIntervalEnabled;
}
public void setCustomCheckIntervalEnabled(boolean newCustomCheckIntervalEnabled) {
this.customCheckIntervalEnabled = newCustomCheckIntervalEnabled;
}
public Integer getCheckInterval() {
return checkInterval;
}
public void setCheckInterval(Integer newCheckInterval) {
this.checkInterval = newCheckInterval;
}
public String toString() {
return this.name;
}
}
class FeedType {
private String type;
private FeedType(String type) {
this.type = type;
}
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof FeedType)) return false;
final FeedType feedType = (FeedType) o;
if (type != null ? !type.equals(feedType.type) : feedType.type != null) return false;
return true;
}
public int hashCode() {
return (type != null ? type.hashCode() : 0);
}
public String toString() {
return this.type;
}
}
}
JGoodies Binding: Presentation Bean Channel Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
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.beans.Model;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class PresentationBeanChannelExample extends JPanel {
private PersonBean personBean1;
private PersonBean personBean2;
private PresentationModel presentationModel;
public PresentationBeanChannelExample() {
DefaultFormBuilder defaultFormBuilder = new DefaultFormBuilder(new FormLayout("p, 2dlu, p:g"));
defaultFormBuilder.setDefaultDialogBorder();
this.personBean1 = new PersonBean("Scott", "Delap");
this.personBean2 = new PersonBean("Matt", "Raible");
this.presentationModel = new PresentationModel(this.personBean1);
ValueModel firstNameAdapter = presentationModel.getModel("firstName");
ValueModel lastNameAdapter = presentationModel.getModel("lastName");
JTextField firstNameTextField = BasicComponentFactory.createTextField(firstNameAdapter);
JTextField lastNameTextField = BasicComponentFactory.createTextField(lastNameAdapter);
defaultFormBuilder.append("First Name: ", firstNameTextField);
defaultFormBuilder.append("Last Name: ", lastNameTextField);
defaultFormBuilder.append(new JButton(new ChangeBeanAction()), 3);
defaultFormBuilder.append(new JButton(new ConvertValueToUpperCaseAction()), 3);
defaultFormBuilder.append(new JButton(new ConvertValueToLowerCaseAction()), 3);
defaultFormBuilder.append(new JButton(new ShowValueHolderValueAction()), 3);
add(defaultFormBuilder.getPanel());
}
private class ChangeBeanAction extends AbstractAction {
public ChangeBeanAction() {
super("Change PersonBean");
}
public void actionPerformed(ActionEvent event) {
if (presentationModel.getBean() == personBean1) {
presentationModel.setBean(personBean2);
} else {
presentationModel.setBean(personBean1);
}
}
}
private class ConvertValueToUpperCaseAction extends AbstractAction {
public ConvertValueToUpperCaseAction() {
super("Convert Value To UpperCase");
}
public void actionPerformed(ActionEvent event) {
PersonBean personBean = (PersonBean) presentationModel.getBean();
personBean.setFirstName(personBean.getFirstName().toUpperCase());
personBean.setLastName(personBean.getLastName().toUpperCase());
}
}
private class ConvertValueToLowerCaseAction extends AbstractAction {
public ConvertValueToLowerCaseAction() {
super("Convert Value To LowerCase");
}
public void actionPerformed(ActionEvent event) {
PersonBean personBean = (PersonBean) presentationModel.getBean();
personBean.setFirstName(personBean.getFirstName().toLowerCase());
personBean.setLastName(personBean.getLastName().toLowerCase());
}
}
private class ShowValueHolderValueAction extends AbstractAction {
public ShowValueHolderValueAction() {
super("Show Value");
}
public void actionPerformed(ActionEvent event) {
PersonBean personBean = (PersonBean) presentationModel.getBean();
StringBuffer message = new StringBuffer();
message.append("<html>");
message.append("<b>First Name:</b> ");
message.append(personBean.getFirstName());
message.append("<br><b>Last Name:</b> ");
message.append(personBean.getLastName());
message.append("</html>");
JOptionPane.showMessageDialog(null, message.toString());
}
}
public class PersonBean extends Model {
private String firstName;
private String lastName;
public static final String FIRST_NAME_PROPERTY = "firstName";
public static final String LAST_NAME_PROPERTY = "lastName";
public PersonBean(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
String oldValue = this.firstName;
this.firstName = firstName;
firePropertyChange(FIRST_NAME_PROPERTY, oldValue, this.firstName);
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
String oldValue = this.lastName;
this.lastName = lastName;
firePropertyChange(LAST_NAME_PROPERTY, oldValue, this.lastName);
}
}
public static void main(String[] a){
JFrame f = new JFrame("Presentation Bean Channel Example");
f.setDefaultCloseOperation(2);
f.add(new PresentationBeanChannelExample());
f.pack();
f.setVisible(true);
}
}
JGoodies Binding: Presentation Bean Property Change Listener 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.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.beans.Model;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class PresentationBeanPropertyChangeListenerExample extends JPanel {
private PersonBean personBean;
public PresentationBeanPropertyChangeListenerExample() {
DefaultFormBuilder defaultFormBuilder = new DefaultFormBuilder(new FormLayout("p, 2dlu, p:g"));
defaultFormBuilder.setDefaultDialogBorder();
this.personBean = new PersonBean("Scott", "Delap");
PresentationModel presentationModel = new PresentationModel(this.personBean);
presentationModel.addBeanPropertyChangeListener(new NotifyingPropertyChangeListener());
ValueModel firstNameAdapter = presentationModel.getModel("firstName");
ValueModel lastNameAdapter = presentationModel.getModel("lastName");
JTextField firstNameTextField = BasicComponentFactory.createTextField(firstNameAdapter);
JTextField lastNameTextField = BasicComponentFactory.createTextField(lastNameAdapter);
defaultFormBuilder.append("First Name: ", firstNameTextField);
defaultFormBuilder.append("Last Name: ", lastNameTextField);
defaultFormBuilder.append(new JButton(new ConvertValueToUpperCaseAction()), 3);
defaultFormBuilder.append(new JButton(new ConvertValueToLowerCaseAction()), 3);
defaultFormBuilder.append(new JButton(new ShowValueHolderValueAction()), 3);
add(defaultFormBuilder.getPanel());
}
private class ConvertValueToUpperCaseAction extends AbstractAction {
public ConvertValueToUpperCaseAction() {
super("Convert Value To UpperCase");
}
public void actionPerformed(ActionEvent event) {
personBean.setFirstName(personBean.getFirstName().toUpperCase());
personBean.setLastName(personBean.getLastName().toUpperCase());
}
}
private class ConvertValueToLowerCaseAction extends AbstractAction {
public ConvertValueToLowerCaseAction() {
super("Convert Value To LowerCase");
}
public void actionPerformed(ActionEvent event) {
personBean.setFirstName(personBean.getFirstName().toLowerCase());
personBean.setLastName(personBean.getLastName().toLowerCase());
}
}
private class ShowValueHolderValueAction extends AbstractAction {
public ShowValueHolderValueAction() {
super("Show Value");
}
public void actionPerformed(ActionEvent event) {
StringBuffer message = new StringBuffer();
message.append("<html>");
message.append("<b>First Name:</b> ");
message.append(personBean.getFirstName());
message.append("<br><b>Last Name:</b> ");
message.append(personBean.getLastName());
message.append("</html>");
JOptionPane.showMessageDialog(null, message.toString());
}
}
private class NotifyingPropertyChangeListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
JOptionPane.showMessageDialog(null, "Property " + evt.getPropertyName() + " was changed to " + evt.getNewValue());
}
}
public class PersonBean extends Model {
private String firstName;
private String lastName;
public static final String FIRST_NAME_PROPERTY = "firstName";
public static final String LAST_NAME_PROPERTY = "lastName";
public PersonBean(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
String oldValue = this.firstName;
this.firstName = firstName;
firePropertyChange(FIRST_NAME_PROPERTY, oldValue, this.firstName);
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
String oldValue = this.lastName;
this.lastName = lastName;
firePropertyChange(LAST_NAME_PROPERTY, oldValue, this.lastName);
}
}
public static void main(String[] a){
JFrame f = new JFrame("Presentation Bean Property Change Listener Example");
f.setDefaultCloseOperation(2);
f.add(new PresentationBeanPropertyChangeListenerExample());
f.pack();
f.setVisible(true);
}
}
JGoodies Binding: Presentation Model Property Change 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.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.beans.Model;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class PresentationModelPropertyChangeExample extends JPanel {
private PersonBean personBean1;
private PersonBean personBean2;
private PresentationModel presentationModel;
public PresentationModelPropertyChangeExample() {
DefaultFormBuilder defaultFormBuilder = new DefaultFormBuilder(new FormLayout("p, 2dlu, p:g"));
defaultFormBuilder.setDefaultDialogBorder();
this.personBean1 = new PersonBean("Scott", "Delap");
this.personBean2 = new PersonBean("Matt", "Raible");
this.presentationModel = new PresentationModel(this.personBean1);
this.presentationModel.addPropertyChangeListener(new BeanChannelChangeListener());
ValueModel firstNameAdapter = presentationModel.getModel("firstName");
ValueModel lastNameAdapter = presentationModel.getModel("lastName");
JTextField firstNameTextField = BasicComponentFactory.createTextField(firstNameAdapter);
JTextField lastNameTextField = BasicComponentFactory.createTextField(lastNameAdapter);
defaultFormBuilder.append("First Name: ", firstNameTextField);
defaultFormBuilder.append("Last Name: ", lastNameTextField);
defaultFormBuilder.append(new JButton(new ChangeBeanAction()), 3);
add(defaultFormBuilder.getPanel());
}
private class ChangeBeanAction extends AbstractAction {
public ChangeBeanAction() {
super("Change PersonBean");
}
public void actionPerformed(ActionEvent event) {
if (presentationModel.getBean() == personBean1) {
presentationModel.setBean(personBean2);
} else {
presentationModel.setBean(personBean1);
}
}
}
private class BeanChannelChangeListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
JOptionPane.showMessageDialog(null, "Property " + evt.getPropertyName() + " Old Value = " + evt.getOldValue() + ", New Value = " + evt.getNewValue());
}
}
public class PersonBean extends Model {
private String firstName;
private String lastName;
public static final String FIRST_NAME_PROPERTY = "firstName";
public static final String LAST_NAME_PROPERTY = "lastName";
public PersonBean(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
String oldValue = this.firstName;
this.firstName = firstName;
firePropertyChange(FIRST_NAME_PROPERTY, oldValue, this.firstName);
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
String oldValue = this.lastName;
this.lastName = lastName;
firePropertyChange(LAST_NAME_PROPERTY, oldValue, this.lastName);
}
public String toString() {
return getFirstName() + " " + getLastName();
}
}
public static void main(String[] a){
JFrame f = new JFrame("Presentation PropertyChange Example");
f.setDefaultCloseOperation(2);
f.add(new PresentationModelPropertyChangeExample());
f.pack();
f.setVisible(true);
}
}
JGoodies Binding: Property Adapter Example 1
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
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.beans.PropertyAdapter;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class PropertyAdapterExample1 extends JPanel {
private PersonBean personBean;
public PropertyAdapterExample1() {
DefaultFormBuilder defaultFormBuilder = new DefaultFormBuilder(new FormLayout("p, 2dlu, p:g"));
defaultFormBuilder.setDefaultDialogBorder();
this.personBean = new PersonBean("Scott", "Delap");
PropertyAdapter firstNameAdapter = new PropertyAdapter(this.personBean, "firstName");
PropertyAdapter lastNameAdapter = new PropertyAdapter(this.personBean, "lastName");
JTextField firstNameTextField = BasicComponentFactory.createTextField(firstNameAdapter);
JTextField lastNameTextField = BasicComponentFactory.createTextField(lastNameAdapter);
defaultFormBuilder.append("First Name: ", firstNameTextField);
defaultFormBuilder.append("Last Name: ", lastNameTextField);
defaultFormBuilder.append(new JButton(new ShowValueHolderValueAction()), 3);
add(defaultFormBuilder.getPanel());
}
public class PersonBean {
private String firstName;
private String lastName;
public PersonBean(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
private class ShowValueHolderValueAction extends AbstractAction {
public ShowValueHolderValueAction() {
super("Show Value");
}
public void actionPerformed(ActionEvent event) {
StringBuffer message = new StringBuffer();
message.append("<html>");
message.append("<b>First Name:</b> ");
message.append(personBean.getFirstName());
message.append("<br><b>Last Name:</b> ");
message.append(personBean.getLastName());
message.append("</html>");
JOptionPane.showMessageDialog(null, message.toString());
}
}
public static void main(String[] a){
JFrame f = new JFrame("Property Adapter Example 1");
f.setDefaultCloseOperation(2);
f.add(new PropertyAdapterExample1());
f.pack();
f.setVisible(true);
}
}
JGoodies Binding: Property Adapter Example 2
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
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.beans.PropertyAdapter;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class PropertyAdapterExample2 extends JPanel {
private PersonBean personBean;
public PropertyAdapterExample2() {
DefaultFormBuilder defaultFormBuilder = new DefaultFormBuilder(new FormLayout("p, 2dlu, p:g"));
defaultFormBuilder.setDefaultDialogBorder();
this.personBean = new PersonBean("Scott", "Delap");
PropertyAdapter firstNameAdapter = new PropertyAdapter(this.personBean, "firstName", "getFirst", "setFirstNameValue");
PropertyAdapter lastNameAdapter = new PropertyAdapter(this.personBean, "lastName");
JTextField firstNameTextField = BasicComponentFactory.createTextField(firstNameAdapter);
JTextField lastNameTextField = BasicComponentFactory.createTextField(lastNameAdapter);
defaultFormBuilder.append("First Name: ", firstNameTextField);
defaultFormBuilder.append("Last Name: ", lastNameTextField);
defaultFormBuilder.append(new JButton(new ShowValueHolderValueAction()), 3);
add(defaultFormBuilder.getPanel());
}
public class PersonBean {
private String firstName;
private String lastName;
public PersonBean(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirst() {
return firstName;
}
public void setFirstNameValue(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
private class ShowValueHolderValueAction extends AbstractAction {
public ShowValueHolderValueAction() {
super("Show Value");
}
public void actionPerformed(ActionEvent event) {
StringBuffer message = new StringBuffer();
message.append("<html>");
message.append("<b>First Name:</b> ");
message.append(personBean.getFirst());
message.append("<br><b>Last Name:</b> ");
message.append(personBean.getLastName());
message.append("</html>");
JOptionPane.showMessageDialog(null, message.toString());
}
}
public static void main(String[] a){
JFrame f = new JFrame("Property Adapter Example 2");
f.setDefaultCloseOperation(2);
f.add(new PropertyAdapterExample2());
f.pack();
f.setVisible(true);
}
}
JGoodies Binding: Property Adapter Example 3
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
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.beans.Model;
import com.jgoodies.binding.beans.PropertyAdapter;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class PropertyAdapterExample3 extends JPanel {
private PersonBean personBean;
public PropertyAdapterExample3() {
DefaultFormBuilder defaultFormBuilder = new DefaultFormBuilder(new FormLayout("p, 2dlu, p:g"));
defaultFormBuilder.setDefaultDialogBorder();
this.personBean = new PersonBean("Scott", "Delap");
PropertyAdapter firstNameAdapter = new PropertyAdapter(this.personBean, "firstName", true);
PropertyAdapter lastNameAdapter = new PropertyAdapter(this.personBean, "lastName", true);
JTextField firstNameTextField = BasicComponentFactory.createTextField(firstNameAdapter);
JTextField lastNameTextField = BasicComponentFactory.createTextField(lastNameAdapter);
defaultFormBuilder.append("First Name: ", firstNameTextField);
defaultFormBuilder.append("Last Name: ", lastNameTextField);
defaultFormBuilder.append(new JButton(new ConvertValueToUpperCaseAction()), 3);
defaultFormBuilder.append(new JButton(new ConvertValueToLowerCaseAction()), 3);
defaultFormBuilder.append(new JButton(new ShowValueHolderValueAction()), 3);
add(defaultFormBuilder.getPanel());
}
private class ConvertValueToUpperCaseAction extends AbstractAction {
public ConvertValueToUpperCaseAction() {
super("Convert Value To UpperCase");
}
public void actionPerformed(ActionEvent event) {
personBean.setFirstName(personBean.getFirstName().toUpperCase());
personBean.setLastName(personBean.getLastName().toUpperCase());
}
}
private class ConvertValueToLowerCaseAction extends AbstractAction {
public ConvertValueToLowerCaseAction() {
super("Convert Value To LowerCase");
}
public void actionPerformed(ActionEvent event) {
personBean.setFirstName(personBean.getFirstName().toLowerCase());
personBean.setLastName(personBean.getLastName().toLowerCase());
}
}
private class ShowValueHolderValueAction extends AbstractAction {
public ShowValueHolderValueAction() {
super("Show Value");
}
public void actionPerformed(ActionEvent event) {
StringBuffer message = new StringBuffer();
message.append("<html>");
message.append("<b>First Name:</b> ");
message.append(personBean.getFirstName());
message.append("<br><b>Last Name:</b> ");
message.append(personBean.getLastName());
message.append("</html>");
JOptionPane.showMessageDialog(null, message.toString());
}
}
public class PersonBean extends Model {
private String firstName;
private String lastName;
public static final String FIRST_NAME_PROPERTY = "firstName";
public static final String LAST_NAME_PROPERTY = "lastName";
public PersonBean(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
String oldValue = this.firstName;
this.firstName = firstName;
firePropertyChange(FIRST_NAME_PROPERTY, oldValue, this.firstName);
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
String oldValue = this.lastName;
this.lastName = lastName;
firePropertyChange(LAST_NAME_PROPERTY, oldValue, this.lastName);
}
}
public static void main(String[] a){
JFrame f = new JFrame("Property Adapter Example 3");
f.setDefaultCloseOperation(2);
f.add(new PropertyAdapterExample3());
f.pack();
f.setVisible(true);
}
}
JGoodies Binding: Property Connector Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.text.ParseException;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.text.MaskFormatter;
import com.jgoodies.binding.beans.PropertyConnector;
import com.jgoodies.binding.value.ValueHolder;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class PropertyConnectorExample extends JPanel {
public PropertyConnectorExample() {
DefaultFormBuilder defaultFormBuilder = new DefaultFormBuilder(new FormLayout("p, 2dlu, p"));
defaultFormBuilder.setDefaultDialogBorder();
ValueModel socialSecurityNumberModel = new ValueHolder();
socialSecurityNumberModel.setValue("123-45-6789");
MaskFormatter maskFormatter = null;
try {
maskFormatter = new MaskFormatter("###-##-####");
} catch (ParseException e) {
//Shouldn"t Happen
}
JFormattedTextField socialSecurityTextField = new JFormattedTextField(maskFormatter);
PropertyConnector propertyConnector1 = new PropertyConnector(socialSecurityNumberModel, "value", socialSecurityTextField, "value");
propertyConnector1.updateProperty2();
defaultFormBuilder.append("Formatted Text Field:", socialSecurityTextField);
JLabel socialSecurityLabel = new JLabel();
PropertyConnector propertyConnector2 = new PropertyConnector(socialSecurityNumberModel, "value", socialSecurityLabel, "text");
propertyConnector2.updateProperty2();
defaultFormBuilder.append("Label:", socialSecurityLabel);
defaultFormBuilder.append(new JButton("Focus Button"), 3);
add(defaultFormBuilder.getPanel());
}
public static void main(String[] a){
JFrame f = new JFrame("Property Connector Example");
f.setDefaultCloseOperation(2);
f.add(new PropertyConnectorExample());
f.pack();
f.setVisible(true);
}
}
JGoodies Binding: Radio Button Adapter Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.Color;
import java.awt.Font;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import com.jgoodies.binding.adapter.RadioButtonAdapter;
import com.jgoodies.binding.value.ValueHolder;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
public class RadioButtonAdapterExample extends JPanel {
private JLabel radioLabel;
public RadioButtonAdapterExample() {
PanelBuilder panelBuilder = new PanelBuilder(new FormLayout("p, 2dlu, p, 2dlu, p, 2dlu, p", "p"));
panelBuilder.setDefaultDialogBorder();
CellConstraints cc = new CellConstraints();
ValueHolder selectionModel = new ValueHolder();
JRadioButton radioButton1 = new JRadioButton("Red");
RadioButtonAdapter radioButtonAdapter1 = new RadioButtonAdapter(selectionModel, Color.red);
radioButton1.setModel(radioButtonAdapter1);
JRadioButton radioButton2 = new JRadioButton("Blue");
RadioButtonAdapter radioButtonAdapter2 = new RadioButtonAdapter(selectionModel, Color.blue);
radioButton2.setModel(radioButtonAdapter2);
JRadioButton radioButton3 = new JRadioButton("Green");
RadioButtonAdapter radioButtonAdapter3 = new RadioButtonAdapter(selectionModel, Color.green);
radioButton3.setModel(radioButtonAdapter3);
this.radioLabel = panelBuilder.addLabel("Radio Buttons:", cc.xy(1, 1));
this.radioLabel.setFont(this.radioLabel.getFont().deriveFont(Font.BOLD));
panelBuilder.add(radioButton1, cc.xy(3, 1));
panelBuilder.add(radioButton2, cc.xy(5, 1));
panelBuilder.add(radioButton3, cc.xy(7, 1));
selectionModel.setValue("blue");
selectionModel.addPropertyChangeListener(new RadioChangeListener());
add(panelBuilder.getPanel());
}
private class RadioChangeListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
radioLabel.setForeground((Color) evt.getNewValue());
}
}
public static void main(String[] a){
JFrame f = new JFrame("Radio Button Adapter Example");
f.setDefaultCloseOperation(2);
f.add(new RadioButtonAdapterExample());
f.pack();
f.setVisible(true);
}
}
JGoodies Binding: Selection In List Bean Channel Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListModel;
import com.jgoodies.binding.adapter.AbstractTableAdapter;
import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.adapter.Bindings;
import com.jgoodies.binding.beans.BeanAdapter;
import com.jgoodies.binding.list.ArrayListModel;
import com.jgoodies.binding.list.SelectionInList;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class SelectionInListBeanChannelExample extends JPanel {
private ArrayListModel arrayListModel;
public SelectionInListBeanChannelExample() {
DefaultFormBuilder defaultFormBuilder = new DefaultFormBuilder(new FormLayout("p, 2dlu, p:g"));
defaultFormBuilder.setDefaultDialogBorder();
this.arrayListModel = new ArrayListModel();
this.arrayListModel.add(new DisplayTechnology("Swing", "Is a Java API", "Sun"));
this.arrayListModel.add(new DisplayTechnology("Flash", "Is NOT a Java API", "Macromedia"));
this.arrayListModel.add(new DisplayTechnology("SWT", "Is a Java API", "Eclipse"));
this.arrayListModel.add(new DisplayTechnology("QT", "Is NOT a Java API", "Trolltech"));
this.arrayListModel.add(new DisplayTechnology("AWT", "Is a Java API", "Sun"));
SelectionInList selectionInList = new SelectionInList((ListModel) this.arrayListModel);
JList jlist = new JList();
Bindings.bind(jlist, selectionInList);
defaultFormBuilder.append("List Model: ", new JScrollPane(jlist));
BeanAdapter beanAdapter = new BeanAdapter(selectionInList);
ValueModel nameModel = beanAdapter.getValueModel("name");
ValueModel descriptionModel = beanAdapter.getValueModel("description");
ValueModel makerModel = beanAdapter.getValueModel("maker");
defaultFormBuilder.append("Name:", BasicComponentFactory.createTextField(nameModel));
defaultFormBuilder.append("Description:", BasicComponentFactory.createTextField(descriptionModel));
defaultFormBuilder.append("Maker:", BasicComponentFactory.createTextField(makerModel));
add(defaultFormBuilder.getPanel());
}
public class DisplayTechnology {
private String name;
private String description;
private String maker;
public DisplayTechnology(String name, String description, String maker) {
this.name = name;
this.description = description;
this.maker = maker;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getMaker() {
return maker;
}
public String toString() {
return name;
}
}
private class DisplayTechnologyTableAdapter extends AbstractTableAdapter {
public DisplayTechnologyTableAdapter(ListModel listModel, String[] columnNames) {
super(listModel, columnNames);
}
public Object getValueAt(int rowIndex, int columnIndex) {
DisplayTechnology displayTechnology = (DisplayTechnology) getRow(rowIndex);
if (columnIndex == 0) {
return displayTechnology.getName();
} else if (columnIndex == 1) {
return displayTechnology.getDescription();
} else {
return displayTechnology.getMaker();
}
}
}
public static void main(String[] a){
JFrame f = new JFrame("Selection In List Bean Channel Example");
f.setDefaultCloseOperation(2);
f.add(new SelectionInListBeanChannelExample());
f.pack();
f.setVisible(true);
}
}
JGoodies Binding: Selection In List Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.adapter.Bindings;
import com.jgoodies.binding.list.SelectionInList;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class SelectionInListExample extends JPanel {
public SelectionInListExample() {
ArrayList strings = new ArrayList();
strings.add("Swing");
strings.add("SWT");
strings.add("HTML");
strings.add("Flash");
strings.add("QT");
SelectionInList selectionInList = new SelectionInList(strings);
DefaultFormBuilder defaultFormBuilder = new DefaultFormBuilder(new FormLayout("p, 2dlu, p:g"));
defaultFormBuilder.setDefaultDialogBorder();
JList jlist = new JList();
Bindings.bind(jlist, selectionInList);
defaultFormBuilder.append("JList: ", new JScrollPane(jlist));
defaultFormBuilder.append("Selected String: ", BasicComponentFactory.createTextField(selectionInList.getSelectionHolder()));
add(defaultFormBuilder.getPanel());
}
public static void main(String[] a){
JFrame f = new JFrame("Selection In List Example");
f.setDefaultCloseOperation(2);
f.add(new SelectionInListExample());
f.pack();
f.setVisible(true);
}
}
JGoodies Binding: Selection In List 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 java.util.List;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import com.jgoodies.binding.adapter.Bindings;
import com.jgoodies.binding.list.ArrayListModel;
import com.jgoodies.binding.list.SelectionInList;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class SelectionInListModelExample extends JPanel {
private ArrayListModel arrayListModel;
private int counter = 1;
public SelectionInListModelExample() {
DefaultFormBuilder defaultFormBuilder = new DefaultFormBuilder(new FormLayout("p, 2dlu, p:g"));
defaultFormBuilder.setDefaultDialogBorder();
this.arrayListModel = new ArrayListModel();
this.arrayListModel.add("Swing");
this.arrayListModel.add("SWT");
this.arrayListModel.add("HTML");
this.arrayListModel.add("Flash");
this.arrayListModel.add("QT");
SelectionInList selectionInList = new SelectionInList((ListModel) this.arrayListModel);
ExamplePropertyChangeListener propertyChangeListener = new ExamplePropertyChangeListener();
selectionInList.addPropertyChangeListener(propertyChangeListener);
ExampleListDataChangeListener listDataChangeListener = new ExampleListDataChangeListener();
selectionInList.addListDataListener(listDataChangeListener);
JList jlist = new JList();
Bindings.bind(jlist, selectionInList);
defaultFormBuilder.append("List Model: ", new JScrollPane(jlist));
defaultFormBuilder.append("", new JButton(new AddElementAction(this.arrayListModel)));
defaultFormBuilder.append("", new JButton(new RemoveFirstElementAction(this.arrayListModel)));
add(defaultFormBuilder.getPanel());
}
private class RemoveFirstElementAction extends AbstractAction {
private List targetList;
public RemoveFirstElementAction(List targetList) {
super("Remove First Element");
this.targetList = targetList;
}
public void actionPerformed(ActionEvent e) {
if (this.targetList.size() > 0) {
this.targetList.remove(0);
}
}
}
private class AddElementAction extends AbstractAction {
private List targetList;
public AddElementAction(List targetList) {
super("Add Element");
this.targetList = targetList;
}
public void actionPerformed(ActionEvent e) {
this.targetList.add("New Element " + counter);
counter++;
}
}
private class ExamplePropertyChangeListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
JOptionPane.showMessageDialog(null, "<html>Property <b>" + evt.getPropertyName() + "</b> changed Old Value = " + evt.getOldValue() + ", New Value = " + evt.getNewValue() + "</html>");
}
}
private class ExampleListDataChangeListener implements ListDataListener {
public void intervalAdded(ListDataEvent e) {
JOptionPane.showMessageDialog(null, "<html>Interval " + e.getIndex0() + " to " + e.getIndex1() + " added.</html>");
}
public void intervalRemoved(ListDataEvent e) {
JOptionPane.showMessageDialog(null, "<html>Interval " + e.getIndex0() + " to " + e.getIndex1() + " removed.</html>");
}
public void contentsChanged(ListDataEvent e) {
JOptionPane.showMessageDialog(null, "<html>Contents changed.</html>");
}
}
public static void main(String[] a){
JFrame f = new JFrame("List / ListModel Example (Selection List Model)");
f.setDefaultCloseOperation(2);
f.add(new SelectionInListModelExample());
f.pack();
f.setVisible(true);
}
}
JGoodies Binding: Toggle Button Adapter Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.Dimension;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.adapter.ToggleButtonAdapter;
import com.jgoodies.binding.beans.BeanAdapter;
import com.jgoodies.binding.beans.Model;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class ToggleButtonAdapterExample extends JPanel {
public ToggleButtonAdapterExample() {
DefaultFormBuilder defaultFormBuilder = new DefaultFormBuilder(new FormLayout("p, 2dlu, p"));
defaultFormBuilder.setDefaultDialogBorder();
ToggleChangeListener toggleChangeListener = new ToggleChangeListener();
BooleanBean booleanBean = new BooleanBean();
BeanAdapter booleanBeanAdapter = new BeanAdapter(booleanBean, true);
booleanBeanAdapter.addBeanPropertyChangeListener(toggleChangeListener);
ValueModel booleanValueModel = booleanBeanAdapter.getValueModel("enabled");
JCheckBox checkBox = BasicComponentFactory.createCheckBox(booleanValueModel, "Enabled");
JToggleButton booleanToggleButton = new JToggleButton();
booleanToggleButton.setPreferredSize(new Dimension(20, 20));
booleanToggleButton.setModel(new ToggleButtonAdapter(booleanValueModel));
defaultFormBuilder.append("Check Box:", checkBox);
defaultFormBuilder.append("Toggle Button:", booleanToggleButton);
StopAndGoBean stopAndGoBean = new StopAndGoBean();
BeanAdapter stopAndGoBeanAdapter = new BeanAdapter(stopAndGoBean);
stopAndGoBeanAdapter.addBeanPropertyChangeListener(toggleChangeListener);
ValueModel stopAndGoModel = stopAndGoBeanAdapter.getValueModel("state");
JToggleButton stopAndGoToggleButton = new JToggleButton();
stopAndGoToggleButton.setPreferredSize(new Dimension(20, 20));
stopAndGoToggleButton.setModel(new ToggleButtonAdapter(stopAndGoModel, "stop", "go"));
defaultFormBuilder.append("Stop/Go Button:", stopAndGoToggleButton);
add(defaultFormBuilder.getPanel());
}
private class ToggleChangeListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
JOptionPane.showMessageDialog(null, "Property " + evt.getPropertyName() + " was changed to " + evt.getNewValue());
}
}
public class BooleanBean extends Model {
public final static String ENABLED_PROPERTY = "enabled";
private Boolean enabled = Boolean.TRUE;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
Boolean oldValue = this.enabled;
this.enabled = enabled;
firePropertyChange(ENABLED_PROPERTY, oldValue, this.enabled);
}
}
public class StopAndGoBean extends Model {
public final static String STATE_PROPERTY = "state";
private String state = "stop";
public String getState() {
return state;
}
public void setState(String state) {
String oldState = this.state;
this.state = state;
firePropertyChange(STATE_PROPERTY, oldState, this.state);
}
}
public static void main(String[] a){
JFrame f = new JFrame("ToggleButtonAdapter Example");
f.setDefaultCloseOperation(2);
f.add(new ToggleButtonAdapterExample());
f.pack();
f.setVisible(true);
}
}
JGoodies Binding: Value Holder Example
/*
Code revised from Desktop Java Live:
http://www.sourcebeat.ru/downloads/
*/
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
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.ValueHolder;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class ValueHolderExample extends JPanel {
private ValueHolder valueHolder;
public ValueHolderExample() {
DefaultFormBuilder defaultFormBuilder = new DefaultFormBuilder(new FormLayout("p, 2dlu, p:g"));
defaultFormBuilder.setDefaultDialogBorder();
this.valueHolder = new ValueHolder("Text Value");
JTextField textField = BasicComponentFactory.createTextField(valueHolder);
defaultFormBuilder.append("TextField: ", textField);
defaultFormBuilder.append(new JButton(new ShowValueHolderValueAction()), 3);
add(defaultFormBuilder.getPanel());
}
private class ShowValueHolderValueAction extends AbstractAction {
public ShowValueHolderValueAction() {
super("Show Value");
}
public void actionPerformed(ActionEvent event) {
StringBuffer message = new StringBuffer();
message.append("<html>");
message.append("<b>Value:</b> ");
message.append(valueHolder.getValue());
message.append("</html>");
JOptionPane.showMessageDialog(null, message.toString());
}
}
public static void main(String[] a){
JFrame f = new JFrame("ValueHolder Example");
f.setDefaultCloseOperation(2);
f.add(new ValueHolderExample());
f.pack();
f.setVisible(true);
}
}
Swingx: Swing Data Binding
Using buffered adapting ValueModels created by a PresentationModel
<source lang="java">
/*
* Copyright (c) 2002-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.binding.tutorial.basics; import java.awt.event.ActionEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.*; import javax.swing.text.JTextComponent; import com.jgoodies.binding.PresentationModel; import com.jgoodies.binding.adapter.BasicComponentFactory; import com.jgoodies.binding.tutorial.Album; import com.jgoodies.binding.tutorial.TutorialUtils; import com.jgoodies.binding.value.AbstractValueModel; import com.jgoodies.binding.value.ValueModel; import com.jgoodies.forms.builder.PanelBuilder; import com.jgoodies.forms.factories.ButtonBarFactory; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; /**
* Builds an editor with components bound to the domain object properties * using buffered adapting ValueModels created by a PresentationModel. * These buffers can be committed on "Apply" and flushed on "Reset". * A second set of components displays the domain object properties. * * @author Karsten Lentzsch * @version $Revision: 1.5 $ * * @see com.jgoodies.binding.PresentationModel * @see com.jgoodies.binding.value.BufferedValueModel * @see com.jgoodies.binding.value.Trigger */
public class EditorBufferedExample {
/** * Holds the edited Album and vends ValueModels that adapt Album properties. * In this example we will request BufferedValueModels for the editor. */ private final PresentationModel presentationModel; private JTextComponent titleField; private JTextComponent artistField; private JCheckBox classicalBox; private JTextComponent composerField; private JTextComponent unbufferedTitleField; private JTextComponent unbufferedArtistField; private JCheckBox unbufferedClassicalBox; private JTextComponent unbufferedComposerField; private JButton applyButton; private JButton resetButton; // Launching ************************************************************** public static void main(String[] args) { try { UIManager.setLookAndFeel("com.jgoodies.looks.plastic.PlasticXPLookAndFeel"); } catch (Exception e) { // Likely PlasticXP is not in the class path; ignore. } JFrame frame = new JFrame(); frame.setTitle("Binding Tutorial :: Editor (Bound, Buffered)"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); EditorBufferedExample example = new EditorBufferedExample(); JComponent panel = example.build(); frame.getContentPane().add(panel); frame.pack(); TutorialUtils.locateOnScreenCenter(frame); frame.setVisible(true); } // Instance Creation ****************************************************** /** * Constructs a buffered editor on an example Album. */ public EditorBufferedExample() { this(Album.ALBUM1); } /** * Constructs a buffered editor for an Album to be edited. * * @param album the Album to be edited */ public EditorBufferedExample(Album album) { this.presentationModel = new PresentationModel(album); } // Initialization ********************************************************* /** * Creates, binds and configures the UI components. * Changes are committed to the value models on apply and are * flushed on reset. */ private void initComponents() { titleField = BasicComponentFactory.createTextField( presentationModel.getBufferedModel(Album.PROPERTYNAME_TITLE)); artistField = BasicComponentFactory.createTextField( presentationModel.getBufferedModel(Album.PROPERTYNAME_ARTIST)); classicalBox = BasicComponentFactory.createCheckBox ( presentationModel.getBufferedModel(Album.PROPERTYNAME_CLASSICAL), "Classical"); composerField = BasicComponentFactory.createTextField( presentationModel.getBufferedModel(Album.PROPERTYNAME_COMPOSER)); unbufferedTitleField = BasicComponentFactory.createTextField( presentationModel.getModel(Album.PROPERTYNAME_TITLE)); unbufferedTitleField.setEditable(false); unbufferedArtistField = BasicComponentFactory.createTextField( presentationModel.getModel(Album.PROPERTYNAME_ARTIST)); unbufferedArtistField.setEditable(false); unbufferedClassicalBox = BasicComponentFactory.createCheckBox ( presentationModel.getModel(Album.PROPERTYNAME_CLASSICAL), "Classical"); unbufferedClassicalBox.setEnabled(false); unbufferedComposerField = BasicComponentFactory.createTextField( presentationModel.getModel(Album.PROPERTYNAME_COMPOSER)); unbufferedComposerField.setEditable(false); applyButton = new JButton(new ApplyAction()); resetButton = new JButton(new ResetAction()); updateComposerField(); } /** * Observes the buffered classical property* to update the composer field"s enablement and contents.
* * If the AlbumPresentationModel would provide a property * bufferedComposerEnabled we could use that instead. * I"ve not added the latter property to the AlbumPresentationModel * so it remains close to the example used in Martin Fowler"s * description of the *