001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common
008: * Development and Distribution License("CDDL") (collectively, the
009: * "License"). You may not use this file except in compliance with the
010: * License. You can obtain a copy of the License at
011: * http://www.netbeans.org/cddl-gplv2.html
012: * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
013: * specific language governing permissions and limitations under the
014: * License. When distributing the software, include this License Header
015: * Notice in each file and include the License file at
016: * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
017: * particular file as subject to the "Classpath" exception as provided
018: * by Sun in the GPL Version 2 section of the License file that
019: * accompanied this code. If applicable, add the following below the
020: * License Header, with the fields enclosed by brackets [] replaced by
021: * your own identifying information:
022: * "Portions Copyrighted [year] [name of copyright owner]"
023: *
024: * Contributor(s):
025: *
026: * The Original Software is NetBeans. The Initial Developer of the Original
027: * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
028: * Microsystems, Inc. All Rights Reserved.
029: *
030: * If you wish your version of this file to be governed by only the CDDL
031: * or only the GPL Version 2, indicate your decision by adding
032: * "[Contributor] elects to include this software in this distribution
033: * under the [CDDL or GPL Version 2] license." If you do not indicate a
034: * single choice of license, a recipient has the option to distribute
035: * your version of this file under either the CDDL, the GPL Version 2 or
036: * to extend the choice of license to its licensees as provided above.
037: * However, if you add GPL Version 2 code and therefore, elected the GPL
038: * Version 2 license, then the option applies only if the new code is
039: * made subject to such option by the copyright holder.
040: */
041: /*
042: * AutoCompleteComboBox.java
043: *
044: * Created on March 27, 2005, 9:24 AM
045: */
046:
047: package org.netbeans.modules.visualweb.ejb.ui;
048:
049: import org.netbeans.modules.visualweb.ejb.datamodel.EjbGroup;
050: import org.netbeans.modules.visualweb.ejb.datamodel.MethodInfo;
051: import org.netbeans.modules.visualweb.ejb.load.EjbLoaderHelper;
052: import java.awt.event.ActionEvent;
053: import java.awt.event.ActionListener;
054: import java.awt.event.FocusAdapter;
055: import java.awt.event.FocusEvent;
056: import java.awt.event.KeyAdapter;
057: import java.awt.event.KeyEvent;
058: import java.net.URLClassLoader;
059: import javax.swing.ComboBoxModel;
060: import javax.swing.JComboBox;
061: import javax.swing.JFrame;
062: import javax.swing.text.AttributeSet;
063: import javax.swing.text.BadLocationException;
064: import javax.swing.text.JTextComponent;
065: import javax.swing.text.PlainDocument;
066: import org.openide.DialogDisplayer;
067: import org.openide.NotifyDescriptor;
068:
069: /**
070: * Provides auto-completion of the given combo box
071: *
072: * @author cao
073: */
074: public class ComboBoxAutoCompletion extends PlainDocument {
075: private JComboBox comboBox;
076: private ComboBoxModel model;
077: private JTextComponent editor;
078:
079: // flag to indicate if setSelectedItem has been called
080: // subsequent calls to remove/insertString should be ignored
081: private boolean selecting = false;
082: private boolean hidePopupOnFocusLoss;
083: private boolean hitBackspace = false;
084: private boolean hitBackspaceOnSelection;
085: private boolean listContainsSelectedItem;
086:
087: // Flag to indicate if the enter key just pressed
088: private boolean enterKeyPressed = false;
089:
090: private EjbGroup ejbGroup;
091: private MethodInfo methodInfo;
092: private URLClassLoader classloader;
093:
094: public ComboBoxAutoCompletion(JComboBox combobox) {
095: this .comboBox = combobox;
096:
097: model = comboBox.getModel();
098: editor = (JTextComponent) comboBox.getEditor()
099: .getEditorComponent();
100: editor.setDocument(this );
101: comboBox.addActionListener(new ActionListener() {
102: public void actionPerformed(ActionEvent e) {
103: if (!selecting)
104: highlightCompletedText(0);
105:
106: if (methodInfo != null) {
107: // Only validate if the enter key is pressed
108: if (enterKeyPressed) {
109: validateColElemClassName((String) comboBox
110: .getSelectedItem());
111: }
112: }
113: }
114: });
115: editor.addKeyListener(new KeyAdapter() {
116: public void keyPressed(KeyEvent e) {
117: if (comboBox.isDisplayable())
118: comboBox.setPopupVisible(true);
119: hitBackspace = false;
120: enterKeyPressed = false;
121:
122: switch (e.getKeyCode()) {
123: // determine if the pressed key is backspace (needed by the remove method)
124: case KeyEvent.VK_BACK_SPACE:
125: hitBackspace = true;
126: hitBackspaceOnSelection = editor
127: .getSelectionStart() != editor
128: .getSelectionEnd();
129: break;
130:
131: case KeyEvent.VK_ENTER:
132: enterKeyPressed = true;
133: break;
134: }
135: }
136: });
137: // Bug 5100422 on Java 1.5: Editable JComboBox won't hide popup when tabbing out
138: hidePopupOnFocusLoss = System.getProperty("java.version")
139: .startsWith("1.5");
140: // Highlight whole text when gaining focus
141: editor.addFocusListener(new FocusAdapter() {
142: public void focusGained(FocusEvent e) {
143: highlightCompletedText(0);
144: }
145:
146: public void focusLost(FocusEvent e) {
147: // Workaround for Bug 5100422 - Hide Popup on focus loss
148: if (hidePopupOnFocusLoss)
149: comboBox.setPopupVisible(false);
150: }
151: });
152: // Handle initially selected object
153: Object selected = comboBox.getSelectedItem();
154: if (selected != null)
155: setText(selected.toString());
156: highlightCompletedText(0);
157: }
158:
159: public void setEjbGroup(EjbGroup ejbGroup) {
160: this .ejbGroup = ejbGroup;
161: }
162:
163: public void setMethodInfo(MethodInfo methodInfo) {
164: this .methodInfo = methodInfo;
165: }
166:
167: public void validateColElemClassName(String className) {
168:
169: // Only if the method has return type of Collection
170: if (!methodInfo.getReturnType().isCollection())
171: return;
172:
173: // TODO ignore null or empty for now
174: if (className == null || className.trim().length() == 0)
175: return;
176:
177: if (classloader == null)
178: classloader = EjbLoaderHelper
179: .getEjbGroupClassLoader(ejbGroup);
180:
181: // Make sure that the element class specified by the user is a valid one
182: try {
183: Class c = Class.forName(className, true, classloader);
184: } catch (java.lang.ClassNotFoundException ce) {
185: NotifyDescriptor d = new NotifyDescriptor.Message("Class "
186: + className + " not found", /*NbBundle.getMessage(MethodNode.class, "PARAMETER_NAME_NOT_UNIQUE", name ),*/
187: NotifyDescriptor.ERROR_MESSAGE);
188: DialogDisplayer.getDefault().notify(d);
189: return;
190: }
191: }
192:
193: public void remove(int offs, int len) throws BadLocationException {
194: // return immediately when selecting an item
195: if (selecting)
196: return;
197: if (hitBackspace) {
198: if (listContainsSelectedItem) {
199: // move the selection backwards
200: // old item keeps being selected
201: if (offs > 0) {
202: if (hitBackspaceOnSelection)
203: offs--;
204: } else {
205: // User hit backspace with the cursor positioned on the start => beep
206: comboBox.getToolkit().beep(); // when available use: UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
207: }
208: highlightCompletedText(offs);
209: return;
210: } else {
211: super .remove(offs, len);
212: String currentText = getText(0, getLength());
213: // lookup if a matching item exists
214: Object item = lookupItem(currentText);
215: if (item != null) {
216: //System.out.println("'" + item + "' matches.");
217: setSelectedItem(item);
218: listContainsSelectedItem = true;
219: } else {
220: //System.out.println("No match. Selecting '" + currentText + "'.");
221: // no item matches => use the current input as selected item
222: item = currentText;
223: setSelectedItem(item);
224: listContainsSelectedItem = false;
225: }
226: // display the completed string
227: String itemString = item.toString();
228: setText(itemString);
229: if (listContainsSelectedItem)
230: highlightCompletedText(offs);
231: }
232: } else {
233: super .remove(offs, len);
234: setSelectedItem(getText(0, getLength()));
235: listContainsSelectedItem = false;
236: }
237: }
238:
239: public void insertString(int offs, String str, AttributeSet a)
240: throws BadLocationException {
241: // return immediately when selecting an item
242: if (selecting)
243: return;
244: // insert the string into the document
245: super .insertString(offs, str, a);
246: // lookup and select a matching item
247: Object item = lookupItem(getText(0, getLength()));
248:
249: listContainsSelectedItem = true;
250: if (item == null) {
251: // no item matches => use the current input as selected item
252: item = getText(0, getLength());
253: listContainsSelectedItem = false;
254: }
255: setSelectedItem(item);
256: setText(item.toString());
257: // select the completed part
258: if (listContainsSelectedItem)
259: highlightCompletedText(offs + str.length());
260: }
261:
262: private void setText(String text) {
263: try {
264: // remove all text and insert the completed string
265: super .remove(0, getLength());
266: super .insertString(0, text, null);
267: } catch (BadLocationException e) {
268: throw new RuntimeException(e.toString());
269: }
270: }
271:
272: private void highlightCompletedText(int start) {
273: editor.setCaretPosition(getLength());
274: editor.moveCaretPosition(start);
275: }
276:
277: private void setSelectedItem(Object item) {
278: selecting = true;
279: model.setSelectedItem(item);
280: selecting = false;
281: }
282:
283: private Object lookupItem(String pattern) {
284: Object selectedItem = model.getSelectedItem();
285: // only search for a different item if the currently selected does not match
286: if (selectedItem != null
287: && startsWithIgnoreCase(selectedItem.toString(),
288: pattern) && listContainsSelectedItem) {
289: return selectedItem;
290: } else {
291: // iterate over all items
292: for (int i = 0, n = model.getSize(); i < n; i++) {
293: Object currentItem = model.getElementAt(i);
294: // current item starts with the pattern?
295: //if (startsWithIgnoreCase(currentItem.toString(), pattern)) {
296: if (currentItem.toString().startsWith(pattern)) { // Case sensitive
297: return currentItem;
298: }
299: }
300: }
301: // no item starts with the pattern => return null
302: return null;
303: }
304:
305: // checks if str1 starts with str2 - ignores case
306: private boolean startsWithIgnoreCase(String str1, String str2) {
307: return str1.toUpperCase().startsWith(str2.toUpperCase());
308: }
309:
310: private static void createAndShowGUI() {
311: // the combo box (add/modify items if you like to)
312: JComboBox comboBox = new JComboBox(new Object[] { "Ester",
313: "Jordi", "Jordina", "Jorge", "Sergi" });
314: // has to be editable
315: comboBox.setEditable(true);
316: // change the editor's document
317: new ComboBoxAutoCompletion(comboBox);
318:
319: // create and show a window containing the combo box
320: JFrame frame = new JFrame();
321: frame.setDefaultCloseOperation(3);
322: frame.getContentPane().add(comboBox);
323: frame.pack();
324: frame.setVisible(true);
325: }
326:
327: public static void main(String[] args) {
328: javax.swing.SwingUtilities.invokeLater(new Runnable() {
329: public void run() {
330: createAndShowGUI();
331: }
332: });
333: }
334: }
|