1 package org.objectstyle.cayenne.swing; 56 57 import java.awt.Color ; 58 import java.awt.Component ; 59 import java.awt.event.ActionEvent ; 60 import java.awt.event.ActionListener ; 61 62 import javax.swing.InputVerifier ; 63 import javax.swing.JComponent ; 64 import javax.swing.JTextArea ; 65 import javax.swing.JTextField ; 66 import javax.swing.event.DocumentEvent ; 67 import javax.swing.event.DocumentListener ; 68 import javax.swing.text.JTextComponent ; 69 70 import org.objectstyle.cayenne.modeler.dialog.validator.ValidatorDialog; 71 import org.objectstyle.cayenne.validation.ValidationException; 72 73 78 public class TextBinding extends BindingBase { 79 80 protected JTextComponent textComponent; 81 82 protected Color defaultBGColor; 83 protected Color errorColor; 84 protected String defaultToolTip; 85 86 public TextBinding(JTextField textField, String expression) { 87 super(expression); 88 this.textComponent = textField; 89 initComponentDefaults(); 90 91 textField.addActionListener(new ActionListener () { 92 93 public void actionPerformed(ActionEvent e) { 94 updateModel(); 95 } 96 }); 97 98 textComponent.setInputVerifier(new InputVerifier () { 99 100 public boolean verify(JComponent c) { 101 updateModel(); 102 return true; 104 } 105 }); 106 107 } 108 109 public TextBinding(JTextArea textArea, String property) { 110 super(property); 111 this.textComponent = textArea; 112 initComponentDefaults(); 113 114 textComponent.getDocument().addDocumentListener(new DocumentListener () { 115 116 public void insertUpdate(DocumentEvent e) { 117 verifyTextChange(e); 118 } 119 120 public void changedUpdate(DocumentEvent e) { 121 verifyTextChange(e); 122 } 123 124 public void removeUpdate(DocumentEvent e) { 125 verifyTextChange(e); 126 } 127 128 void verifyTextChange(DocumentEvent e) { 129 if (!modelUpdateDisabled) { 130 updateModel(); 131 } 132 } 133 }); 134 } 135 136 protected void initComponentDefaults() { 137 this.errorColor = ValidatorDialog.WARNING_COLOR; 138 this.defaultBGColor = textComponent.getBackground(); 139 this.defaultToolTip = textComponent.getToolTipText(); 140 } 141 142 public void updateView() { 143 Object value = getValue(); 144 String text = (value != null) ? value.toString() : null; 145 146 modelUpdateDisabled = true; 147 try { 148 clear(); 149 textComponent.setText(text); 150 } 151 finally { 152 modelUpdateDisabled = false; 153 } 154 } 155 156 159 public Component getView() { 160 return textComponent; 161 } 162 163 protected void updateModel() { 164 try { 165 setValue(textComponent.getText()); 166 clear(); 167 } 168 catch (ValidationException vex) { 169 textComponent.setBackground(errorColor); 170 textComponent.setToolTipText(vex.getUnlabeledMessage()); 171 } 172 } 173 174 protected void clear() { 175 textComponent.setBackground(defaultBGColor); 176 textComponent.setToolTipText(defaultToolTip); 177 } 178 } | Popular Tags |