KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > nqadmin > swingSet > SSDBComboBox


1 /* $Id: SSDBComboBox.java,v 1.31 2005/02/22 16:07:10 prasanth Exp $
2  *
3  * Tab Spacing = 4
4  *
5  * Copyright (c) 2003-2005, The Pangburn Company and Prasanth R. Pasala.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  * Redistributions of source code must retain the above copyright notice, this
12  * list of conditions and the following disclaimer. Redistributions in binary
13  * form must reproduce the above copyright notice, this list of conditions and
14  * the following disclaimer in the documentation and/or other materials
15  * provided with the distribution. The names of its contributors may not be
16  * used to endorse or promote products derived from this software without
17  * specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
23  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  *
31  */

32
33 package com.nqadmin.swingSet;
34
35 import java.io.*;
36 import java.util.Vector JavaDoc;
37 import java.util.Stack JavaDoc;
38 import java.text.SimpleDateFormat JavaDoc;
39 import java.sql.*;
40 import java.awt.*;
41 import java.awt.event.*;
42 import javax.swing.*;
43 import com.nqadmin.swingSet.datasources.SSRowSet;
44 import com.nqadmin.swingSet.datasources.SSConnection;
45 import javax.swing.border.*;
46 import javax.swing.text.*;
47 import javax.swing.event.*;
48
49 /**
50  * SSDBComboBox.java
51  *<p>
52  * SwingSet - Open Toolkit For Making Swing Controls Database-Aware
53  *<p><pre>
54  * Similar to the SSComboBox, but used when both the 'bound' values and the
55  * 'display' values are pulled from a database table. Generally the bound
56  * value represents a foreign key to another table, and the combobox needs to
57  * diplay a list of one (or more) columns from the other table.
58  *
59  * Note, if changing both a sSRowSet and column name consider using the bind()
60  * method rather than individual setSSRowSet() and setColumName() calls.
61  *
62  * e.g.
63  *
64  * Consider two tables:
65  * 1. part_data (part_id, part_name, ...)
66  * 2. shipment_data (shipment_id, part_id, quantity, ...)
67  *
68  * Assume you would like to develop a screen for the shipment table and you
69  * want to have a screen with a combobox where the user can choose a
70  * part and a textbox where the user can specify a quantity.
71  *
72  * In the combobox you would want to display the part name rather than
73  * part_id so that it is easier for the user to choose. At the same time you
74  * want to store the id of the part chosen by the user in the shipment
75  * table.
76  *
77  * SSConnection connection = null;
78  * SSJdbcRowSetImpl sSRowSet = null;
79  * SSDataNavigator navigator = null;
80  * SSDBComboBox combo = null;
81  *
82  * try {
83  *
84  * // CREATE A DATABASE CONNECTION OBJECT
85  * SSConnection connection = new SSConnection(........);
86  *
87  * // CREATE AN INSTANCE OF SSJDBCROWSETIMPL
88  * SSJdbcRowsetImpl sSRowSet = new SSJdbcRowsetImpl(connection);
89  * sSRowSet.setCommand("SELECT * FROM shipment_data;");
90  *
91  * // DATA NAVIGATOR CALLS THE EXECUTE AND NEXT FUNCTIONS ON THE SSROWSET.
92  * // IF YOU ARE NOT USING THE DATA NAVIGATOR YOU HAVE TO INCLUDE THOSE.
93  * // sSRowSet.execute();
94  * // sSRowSet.next();
95  * SSDataNavigator navigator = new SSDataNavigator(sSRowSet);
96  *
97  * // QUERY FOR THE COMBOBOX.
98  * String query = "SELECT * FROM part_data;";
99  *
100  * // CREATE AN INSTANCE OF THE SSDBCOMBOBOX WITH THE CONNECTION OBJECT
101  * // QUERY AND COLUMN NAMES
102  * combo = new SSDBComboBox(connection,query,"part_id","part_name");
103  *
104  * // THIS BASICALLY SPECIFIES THE COLUMN AND THE SSROWSET WHERE UPDATES HAVE
105  * // TO BE MADE.
106  * combo.bind(sSRowSet,"part_id");
107  * combo.execute();
108  *
109  * // CREATE A TEXTFIELD
110  * JTextField myText = new JTextField();
111  * myText.setDocument(new SSTextDocument(sSRowSet, "quantity");
112  *
113  * } catch(Exception e) {
114  * // EXCEPTION HANDLER HERE...
115  * }
116  *
117  *
118  * // ADD THE SSDBCOMBOBOX TO THE JFRAME
119  * getContentPane().add(combo.getComboBox());
120  *
121  * // ADD THE JTEXTFIELD TO THE JFRAME
122  * getContentPane().add(myText);
123  *</pre><p>
124  * @author $Author: prasanth $
125  * @version $Revision: 1.31 $
126  */

127 //public class SSDBComboBox extends JComponent {
128
public class SSDBComboBox extends JComboBox {
129
130     /**
131      * Text field bound to the SSRowSet.
132      */

133     protected JTextField textField = new JTextField();
134
135     /**
136      * Database connection used to execute queries for combo population.
137      */

138     protected SSConnection sSConnection = null;
139
140     /**
141      * Query used to populate combo box.
142      */

143     protected String JavaDoc query = "";
144
145     /**
146      * The column name whose value is written back to the database when the user
147      * chooses an item in the combo box. This is generally the PK of the table
148      * to which a foreign key is mapped.
149      */

150     protected String JavaDoc primaryKeyColumnName = "";
151
152     /**
153      * The database column used to populate the first visible column of the
154      * combo box.
155      */

156     protected String JavaDoc displayColumnName = "";
157
158     /**
159      * The database column used to populate the second (optional) visible column
160      * of the combo box.
161      */

162     protected String JavaDoc secondDisplayColumnName = "";
163
164     /**
165      * Vector used to store all of the primaryKeyColumnName values for the
166      * combo box.
167      */

168     protected Vector JavaDoc columnVector = new Vector JavaDoc();
169
170     /**
171      * Number of items in the combo box.
172      */

173     protected int numberOfItems = 0;
174
175     /**
176      * SSRowSet from which component will get/set values.
177      */

178     protected SSRowSet sSRowSet;
179
180     /**
181      * SSRowSet column to which the component will be bound.
182      */

183     protected String JavaDoc columnName = "";
184
185     /**
186      * Component listener.
187      */

188     private final MyComboListener cmbListener = new MyComboListener();
189
190     /**
191      * Bound text field document listener.
192      */

193     private final MyTextFieldDocumentListener textFieldDocumentListener = new MyTextFieldDocumentListener();
194
195     /**
196      * Keystroke-based item selection listener.
197      */

198     private final MyKeyListener myKeyListener = new MyKeyListener();
199
200     /**
201      * Alphanumeric separator used to separate values in multi-column combo boxes.
202      */

203     protected String JavaDoc seperator = " - ";
204
205     /**
206      * Format for any date columns displayed in combo box.
207      */

208     protected String JavaDoc dateFormat = "MM/dd/yyyy";
209
210     /**
211      * Creates an object of the SSDBComboBox.
212      */

213     public SSDBComboBox() {
214         init();
215     }
216
217     /**
218      * Constructs a SSDBComboBox with the given parameters.
219      *
220      * @param _sSConnection database connection to be used.
221      * @param _query query to be used to retrieve the values from the database.
222      * @param _primaryKeyColumnName column name whose value has to be stored.
223      * @param _displayColumnName column name whose values are displayed in the combo box.
224      */

225     public SSDBComboBox(SSConnection _sSConnection, String JavaDoc _query, String JavaDoc _primaryKeyColumnName, String JavaDoc _displayColumnName) {
226         sSConnection = _sSConnection;
227         query = _query;
228         primaryKeyColumnName = _primaryKeyColumnName;
229         displayColumnName = _displayColumnName;
230         init();
231     }
232
233     /**
234      * Sets the new SSRowSet for the combo box.
235      *
236      * @param _sSRowSet SSRowSet to which the combo has to update values.
237      */

238     public void setSSRowSet(SSRowSet _sSRowSet) {
239         SSRowSet oldValue = sSRowSet;
240         sSRowSet = _sSRowSet;
241         firePropertyChange("sSRowSet", oldValue, sSRowSet);
242         bind();
243     }
244
245     /**
246      * Returns the SSRowSet being used to get the values.
247      *
248      * @return returns the SSRowSet being used.
249      */

250     public SSRowSet getSSRowSet() {
251         return sSRowSet;
252     }
253
254     /**
255      * Sets the connection object to be used.
256      *
257      * @param _sSConnection connection object used for database.
258      */

259     public void setSSConnection(SSConnection _sSConnection) {
260         SSConnection oldValue = sSConnection;
261         sSConnection = _sSConnection;
262         firePropertyChange("sSConnection", oldValue, sSConnection);
263         bind();
264     }
265
266     /**
267      * Returns connection object used to get values from database.
268      *
269      * @return returns a SSConnection object.
270      */

271     public SSConnection getSSConnection() {
272         return sSConnection;
273     }
274
275     /**
276      * Sets the query used to display items in the combo box.
277      *
278      * @param _query query to be used to get values from database (to display combo box items)
279      */

280     public void setQuery(String JavaDoc _query) {
281         String JavaDoc oldValue = query;
282         query = _query;
283         firePropertyChange("query", oldValue, query);
284     }
285
286     /**
287      * Returns the query used to retrieve values from database for the combo box.
288      *
289      * @return returns the query used.
290      */

291     public String JavaDoc getQuery() {
292         return query;
293     }
294
295     /**
296      * Sets the column name for the combo box
297      *
298      * @param _columnName name of column
299      */

300     public void setColumnName(String JavaDoc _columnName) {
301         String JavaDoc oldValue = columnName;
302         columnName = _columnName;
303         firePropertyChange("columnName", oldValue, columnName);
304         bind();
305     }
306
307     /**
308      * Returns the column name to which the combo is bound.
309      *
310      * @return returns the column name to which to combo box is bound.
311      */

312     public String JavaDoc getColumnName() {
313         return columnName;
314     }
315
316     /**
317      * Sets the column name whose values have to be displayed in combo box.
318      *
319      * @param _displayColumnName column name whose values have to be displayed.
320      */

321     public void setDisplayColumnName(String JavaDoc _displayColumnName) {
322         String JavaDoc oldValue = displayColumnName;
323         displayColumnName = _displayColumnName;
324         firePropertyChange("displayColumnName", oldValue, displayColumnName);
325     }
326
327     /**
328      * Returns the column name whose values are displayed in the combo box.
329      *
330      * @return returns the name of the column used to get values for combo box items.
331      */

332     public String JavaDoc getDisplayColumnName() {
333         return displayColumnName;
334     }
335
336     /**
337      * When a display column is of type date you can choose the format in which it has
338      * to be displayed. For the pattern refer SimpleDateFormat in java.text package.
339      *
340      * @param _dateFormat pattern in which dates have to be displayed
341      */

342      public void setDateFormat(String JavaDoc _dateFormat) {
343         String JavaDoc oldValue = dateFormat;
344         dateFormat = _dateFormat;
345         firePropertyChange("dateFormat", oldValue, dateFormat);
346      }
347
348     /**
349      * Returns the pattern in which dates have to be displayed
350      *
351      * @return returns the pattern in which dates have to be displayed
352      */

353     public String JavaDoc getDateFormat() {
354         return dateFormat;
355     }
356
357     /**
358      * Sets the second display name.
359      * If more than one column have to displayed then use this.
360      * For the parts example given above. If you have a part description in part table.
361      * Then you can display both part name and part description.
362      *
363      * @param _secondDisplayColumnName column name whose values have to be
364      * displayed in the combo in addition to the first column name.
365      */

366     public void setSecondDisplayColumnName(String JavaDoc _secondDisplayColumnName) {
367         String JavaDoc oldValue = secondDisplayColumnName;
368         secondDisplayColumnName = _secondDisplayColumnName;
369         firePropertyChange("secondDisplayColumnName", oldValue, secondDisplayColumnName);
370     }
371
372     /**
373      * Returns the second column name whose values are also displayed in the combo box.
374      *
375      * @return returns the name of the column used to get values for combo box items.
376      * returns NULL if the second display column is not provided.
377      */

378     public String JavaDoc getSecondDisplayColumnName() {
379         return secondDisplayColumnName;
380     }
381
382     /**
383      * Set the seperator to be used when multiple columns are displayed
384      *
385      * @param _seperator seperator to be used.
386      */

387      public void setSeperator(String JavaDoc _seperator) {
388         String JavaDoc oldValue = seperator;
389         seperator = _seperator;
390         firePropertyChange("seperator", oldValue, seperator);
391      }
392
393      /**
394       * Returns the seperator used when multiple columns are displayed
395       *
396       * @return seperator used.
397       */

398      public String JavaDoc getSeperator() {
399         return seperator;
400      }
401
402     /**
403      * Returns the number of items present in the combo box.
404      *
405      * This is a read-only bean property.
406      *
407      * @return returns the number of items present in the combo box.
408      */

409     public int getNumberOfItems() {
410         return numberOfItems;
411     }
412
413     /**
414      * Sets the currently selected value
415      *
416      * Currently not a bean property since there is no associated variable.
417      *
418      * @param _value value to set as currently selected.
419      */

420     public void setSelectedValue(long _value) {
421         textField.setText(String.valueOf(_value));
422     }
423
424     /**
425      * Returns the value of the selected item.
426      *
427      * Currently not a bean property since there is no associated variable.
428      *
429      * @return value corresponding to the selected item in the combo.
430      * return -1 if no item is selected.
431      */

432     public long getSelectedValue() {
433
434         int index = getSelectedIndex();
435
436         if (index == -1) {
437             return -1;
438         }
439
440         return Long.valueOf((String JavaDoc)columnVector.get(index)).longValue();
441
442     }
443
444     /**
445      * Sets the currently selected value
446      *
447      * Currently not a bean property since there is no associated variable.
448      *
449      * @param _value value to set as currently selected.
450      */

451     public void setSelectedStringValue(String JavaDoc _value) {
452         textField.setText(_value);
453     }
454
455     /**
456      * Returns the value of the selected item.
457      *
458      * Currently not a bean property since there is no associated variable.
459      *
460      * @return value corresponding to the selected item in the combo.
461      * return null if no item is selected.
462      */

463     public String JavaDoc getSelectedStringValue() {
464
465         int index = getSelectedIndex();
466
467         if (index == -1) {
468             return null;
469         }
470
471         return (String JavaDoc)columnVector.get(index);
472
473     }
474
475     /**
476      * Executes the query and adds items to the combo box based on the values
477      * retrieved from the database.
478      */

479     public void execute() throws SQLException, Exception JavaDoc {
480
481         // TURN OFF LISTENERS
482
removeListeners();
483
484         // DATABASE SETUP
485
Statement statement = sSConnection.getConnection().createStatement();
486
487             if (query.equals("")) {
488                 throw new Exception JavaDoc("Query is empty");
489             }
490
491             ResultSet rs = statement.executeQuery(query);
492
493         // CLEAR ALL ITEMS FROM COMBO AND VECTOR STORING ITS CORRESPONDING VALUES.
494
removeAllItems();
495             columnVector.clear();
496
497         // LOOP THROUGH VALUES IN RESULTSET AND ADD TO COMBO BOX
498
int i = 0;
499             while (rs.next()) {
500                 // IF TWO COLUMNS HAVE TO BE DISPLAYED IN THE COMBO THEY SEPERATED BY SEMI-COLON
501
if ( secondDisplayColumnName != null && !secondDisplayColumnName.trim().equals("")) {
502                     addItem(getStringValue(rs,displayColumnName) + seperator + rs.getString(secondDisplayColumnName));
503                 } else {
504                     addItem(getStringValue(rs,displayColumnName));
505                 }
506                 // ADD THE PK TO A VECTOR.
507
columnVector.add(i,rs.getString(primaryKeyColumnName));
508                 i++;
509             }
510
511         // STORE THE NUMBER OF ITEMS IN THE COMBO BOX.
512
numberOfItems = i;
513
514         // DISPLAYS THE ITEM CORRESPONDING TO THE PRESENT VALUE IN THE DATABASE BASE.
515
updateDisplay();
516             addListeners();
517
518     } // end public void execute() throws SQLException, Exception {
519

520     /**
521      * Sets the SSRowSet and column name to which the component is to be bound.
522      *
523      * @param _sSRowSet datasource to be used.
524      * @param _columnName Name of the column to which this check box should be bound
525      */

526     public void bind(SSRowSet _sSRowSet, String JavaDoc _columnName) {
527         SSRowSet oldValue = sSRowSet;
528         sSRowSet = _sSRowSet;
529         firePropertyChange("sSRowSet", oldValue, sSRowSet);
530
531         String JavaDoc oldValue2 = columnName;
532         columnName = _columnName;
533         firePropertyChange("columnName", oldValue2, columnName);
534
535         bind();
536     }
537
538     /**
539      * Adds an item to the existing list of items in the combo box.
540      *
541      * @param _name name that should be displayed in the combo
542      * @param _value value corresponding the the name
543      */

544      public void addItem(String JavaDoc _name, long _value) {
545         columnVector.add(Long.toString(_value));
546         addItem(_name);
547         numberOfItems++;
548      }
549
550     /**
551      * Adds an item to the existing list of items in the combo box.
552      *
553      * @param _name name that should be displayed in the combo
554      * @param _value value corresponding the the name
555      */

556      public void addStringItem(String JavaDoc _name, String JavaDoc _value) {
557         columnVector.add(_value);
558         addItem(_name);
559         numberOfItems++;
560      }
561
562      /**
563       * Deletes the item which has value equal to _value.
564       * If more than one item is present in the combo for that value the first one is changed.
565       *
566       * @param _value value of the item to be deleted.
567       *
568       * @return returns true on successful deletion else returns false.
569       */

570      public boolean deleteItem(long _value) {
571         int index = columnVector.indexOf(Long.toString(_value));
572         if (index == -1) {
573             return false;
574         }
575         columnVector.removeElementAt(index);
576         removeItemAt(index);
577         numberOfItems--;
578         return true;
579      }
580
581      /**
582       * Deletes the item which has value equal to _value.
583       * If more than one item is present in the combo for that value the first one is changed.
584       *
585       * @param _value value of the item to be deleted.
586       *
587       * @return returns true on successful deletion else returns false.
588       */

589      public boolean deleteStringItem(String JavaDoc _value) {
590         int index = columnVector.indexOf(_value);
591         if (index == -1) {
592             return false;
593         }
594         columnVector.removeElementAt(index);
595         removeItemAt(index);
596         numberOfItems--;
597         return true;
598      }
599
600     /**
601      * Updates the string thats being displayed.
602      * If more than one item is present in the combo for that value the first one is changed.
603      *
604      * NOTE: To retain changes made to current SSRowSet call updateRow before calling the
605      * updateItem on SSDBComboBox. (Only if you are using the SSDBComboBox and SSDataNavigator
606      * for navigation in the screen. If you are not using the SSDBComboBox for navigation
607      * then no need to call updateRow on the SSRowSet. Also if you are using only SSDBComboBox
608      * for navigation you need not call the updateRow.)
609      *
610      * @param _value the value corresponding to the item in combo to be updated.
611      * @param _name the new name that replace old one.
612      *
613      * @return returns true if successful else false.
614      */

615     public boolean updateItem(long _value, String JavaDoc _name) {
616         int index = columnVector.indexOf(Long.toString(_value));
617         if (index == -1) {
618             return false;
619         }
620         removeActionListener(cmbListener);
621         insertItemAt(_name,index+1);
622         removeItemAt(index);
623         setSelectedIndex(index);
624         addActionListener(cmbListener);
625         return true;
626     }
627
628     /**
629      * Updates the string thats being displayed.
630      * If more than one item is present in the combo for that value the first one is changed.
631      *
632      * NOTE: To retain changes made to current SSRowSet call updateRow before calling the
633      * updateItem on SSDBComboBox. (Only if you are using the SSDBComboBox and SSDataNavigator
634      * for navigation in the screen. If you are not using the SSDBComboBox for navigation
635      * then no need to call updateRow on the SSRowSet. Also if you are using only SSDBComboBox
636      * for navigation you need not call the updateRow.)
637      *
638      * @param _value the value corresponding to the item in combo to be updated.
639      * @param _name the new name that replace old one.
640      *
641      * @return returns true if successful else false.
642      */

643     public boolean updateStringItem(String JavaDoc _value, String JavaDoc _name) {
644         int index = columnVector.indexOf(_value);
645         if (index == -1) {
646             return false;
647         }
648         removeActionListener(cmbListener);
649         insertItemAt(_name,index+1);
650         removeItemAt(index);
651         setSelectedIndex(index);
652         addActionListener(cmbListener);
653         return true;
654     }
655
656     /**
657      * Initialization code.
658      */

659     protected void init() {
660         // ADD KEY LISTENER TO TRANSFER FOCUS TO NEXT ELEMENT WHEN ENTER
661
// THIS IS HANDLED IN MyKeyListener
662

663         // SET PREFERRED DIMENSIONS
664
setPreferredSize(new Dimension(200,20));
665     }
666
667     /**
668      * Method for handling binding of component to a SSRowSet column.
669      */

670     protected void bind() {
671
672         // CHECK FOR NULL COLUMN/ROWSET
673
if (columnName==null || columnName.trim().equals("") || sSRowSet==null) {
674                 return;
675             }
676
677         // REMOVE LISTENERS TO PREVENT DUPLICATION
678
removeListeners();
679
680         // BIND THE TEXT FIELD TO THE SPECIFIED COLUMN
681
textField.setDocument(new SSTextDocument(sSRowSet, columnName));
682
683         // SET THE COMBO BOX ITEM DISPLAYED
684
updateDisplay();
685
686         // ADD BACK LISTENERS
687
addListeners();
688
689     }
690
691     /**
692      * Updates the value displayed in the component based on the SSRowSet column
693      * binding.
694      */

695     protected void updateDisplay() {
696
697         //try {
698
// GET THE VALUE FROM TEXT FIELD
699
String JavaDoc text = textField.getText().trim();
700             if (!text.equals("")) {
701                 //long valueInText = Long.parseLong(text);
702
// GET THE INDEX WHERE THIS VALUE IS IN THE VECTOR.
703
//int indexCorrespondingToLong = columnVector.indexOf(new Long(valueInText));
704
int columnVectorIndex = columnVector.indexOf(text);
705                 // SET THE SELECTED ITEM OF COMBO TO THE ITEM AT THE INDEX FOUND FROM
706
// ABOVE STATEMENT
707
//if (indexCorrespondingToLong != getSelectedIndex()) {
708
if (columnVectorIndex != getSelectedIndex()) {
709                     //setSelectedIndex(indexCorrespondingToLong);
710
setSelectedIndex(columnVectorIndex);
711                 }
712             }
713             else{
714                 setSelectedIndex(-1);
715             }
716         //} catch(NumberFormatException nfe) {
717
// System.out.println("Possible reason underlying column is not a number field");
718
// nfe.printStackTrace();
719
//}
720

721     }
722
723     /**
724      * Method to return string equalivent of a given resultset column.
725      *
726      * @param _rs ResultSet containing column to analyize
727      * @param _columnName column to convert to string
728      *
729      * @return string equilivent of specified resultset column
730      */

731     protected String JavaDoc getStringValue(ResultSet _rs, String JavaDoc _columnName) {
732         String JavaDoc strValue = "";
733         try {
734             int type = _rs.getMetaData().getColumnType(_rs.findColumn(_columnName));
735             switch(type){
736                 case Types.DATE:
737                     SimpleDateFormat JavaDoc myDateFormat = new SimpleDateFormat JavaDoc(dateFormat);
738                     strValue = myDateFormat.format(_rs.getDate(_columnName));
739                 break;
740                 default:
741                     strValue = _rs.getString(_columnName);
742                 break;
743             }
744         } catch(SQLException se) {
745             se.printStackTrace();
746         }
747         return strValue;
748
749     }
750
751     /**
752      * Adds listeners for component and bound text field (where applicable).
753      */

754     private void addListeners() {
755         addActionListener(cmbListener);
756         addFocusListener(cmbListener);
757         addKeyListener(myKeyListener);
758         textField.getDocument().addDocumentListener(textFieldDocumentListener);
759     }
760
761     /**
762      * Removes listeners for component and bound text field (where applicable).
763      */

764     private void removeListeners() {
765         removeActionListener(cmbListener);
766         removeFocusListener(cmbListener);
767         removeKeyListener(myKeyListener);
768         textField.getDocument().removeDocumentListener(textFieldDocumentListener);
769
770     }
771
772     /**
773      * Listener(s) for the bound text field used to propigate values back to the
774      * component's value.
775      */

776     private class MyTextFieldDocumentListener implements DocumentListener {
777
778         public void changedUpdate(DocumentEvent de) {
779             removeActionListener(cmbListener);
780             updateDisplay();
781             addActionListener(cmbListener);
782         }
783
784         public void insertUpdate(DocumentEvent de) {
785             removeActionListener(cmbListener);
786             updateDisplay();
787             addActionListener(cmbListener);
788         }
789
790         public void removeUpdate(DocumentEvent de) {
791             removeActionListener(cmbListener);
792             updateDisplay();
793             addActionListener(cmbListener);
794         }
795
796     } // end private class MyTextFieldDocumentListener implements DocumentListener {
797

798     /**
799      * Listener for keystroke-based, string matching, combo box navigation.
800      */

801     private class MyKeyListener extends KeyAdapter {
802
803         String JavaDoc searchString = null;
804         Stack JavaDoc searchStack = new Stack JavaDoc();
805         int previousIndex = 0;
806
807         public void resetSearchString() {
808             searchString = null;
809         }
810
811         public void keyReleased(KeyEvent ke) {
812             int i;
813             if (ke.getKeyCode() == KeyEvent.VK_ESCAPE ||
814                     ke.getKeyCode() == KeyEvent.VK_PAGE_UP ||
815                     ke.getKeyCode() == KeyEvent.VK_PAGE_DOWN ||
816                     ke.getKeyCode() == KeyEvent.VK_UP ||
817                     ke.getKeyCode() == KeyEvent.VK_DOWN ||
818                     ke.getKeyCode() == KeyEvent.VK_ENTER ) {
819                 searchString = null;
820                 searchStack.removeAllElements();
821                 if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
822                     ((Component)ke.getSource()).transferFocus();
823                 }
824                 return;
825
826             }
827
828             if (ke.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
829                 if (searchString == null ) {
830                     setSelectedIndex(0);
831                     searchStack.removeAllElements();
832                     previousIndex = 0;
833                     return;
834                 }
835                 if (searchString.length() > 0) {
836                     searchString = searchString.substring(0,searchString.length()-1);
837                     if (searchString.length() == 0) {
838                         searchString = null;
839                         searchStack.removeAllElements();
840                         previousIndex = 0;
841                     }
842                 }
843
844             } else if(searchString == null) {
845                 searchString = new String JavaDoc(new char[]{ke.getKeyChar()});
846             } else {
847                 searchString = searchString + new String JavaDoc(new char[]{ke.getKeyChar()});
848             }
849
850             if (searchString == null) {
851                 setSelectedIndex(0);
852                 return;
853             }
854
855             if (ke.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
856
857                 if (searchStack.empty()) {
858                     setSelectedIndex(0);
859                     return;
860                 } else {
861                     // PRESENT POSITION IN COMBO
862
searchStack.pop();
863                     // PREVIOUS POSITION IN COMBO
864
if(!searchStack.empty()) {
865                         previousIndex = ((Integer JavaDoc)searchStack.peek()).intValue();
866                         setSelectedIndex(previousIndex);
867                         return;
868                     } else {
869                         previousIndex = 0;
870                         setSelectedIndex(0);
871                         return;
872                     }
873                 }
874
875             } else {
876
877                 for (i=previousIndex;i<getItemCount();i++) {
878                     if (searchString.length() == 0) {
879                         setSelectedIndex(0);
880                     } else {
881                         if (((String JavaDoc)getItemAt(i)).length() >= searchString.length()) {
882                             if (searchString.equalsIgnoreCase( ((String JavaDoc)getItemAt(i)).substring(0,searchString.length())) ) {
883                                 setSelectedIndex(i);
884                                 searchStack.push(new Integer JavaDoc(i));
885                                 return;
886                             }
887                         }
888                     }
889
890                 }
891
892                 if (i == getItemCount()) {
893                     for (i=0;i<previousIndex;i++) {
894                         if (searchString.length() == 0) {
895                             setSelectedIndex(0);
896                         } else {
897                             if (((String JavaDoc)getItemAt(i)).length() >= searchString.length()) {
898                                 if (searchString.equalsIgnoreCase( ((String JavaDoc)getItemAt(i)).substring(0,searchString.length())) ){
899                                     setSelectedIndex(i);
900                                     searchStack.push(new Integer JavaDoc(i));
901                                     return;
902                                 }
903                             }
904                         }
905                     }
906                 }
907             }
908
909             if (searchStack.empty()) {
910                 setSelectedIndex(0);
911             } else {
912                 setSelectedIndex(((Integer JavaDoc)searchStack.peek()).intValue());
913             }
914
915         }
916     } // end private class MyKeyListener extends KeyAdapter {
917

918     /**
919      * Listener(s) for the component's value used to propigate changes back to
920      * bound text field.
921      */

922     private class MyComboListener extends FocusAdapter implements ActionListener {
923
924         public void actionPerformed(ActionEvent ae) {
925
926             textField.getDocument().removeDocumentListener(textFieldDocumentListener);
927
928             // GET THE INDEX CORRESPONDING TO THE SELECTED TEXT IN COMBO
929
int index = getSelectedIndex();
930
931             // IF THE USER WANTS TO REMOVE COMPLETELY THE VALUE IN THE FIELD HE CHOOSES
932
// THE EMPTY STRING IN COMBO THEN THE TEXT FIELD IS SET TO EMPTY STRING
933
if (index != -1) {
934                 try {
935                     // NOW LOOK UP THE VECTOR AND GET THE VALUE CORRESPONDING TO THE TEXT SELECTED IN THE COMBO
936
//long valueCorresponingToIndex = ( (Long)columnVector.get(index) ).longValue() ;
937
//GET THE TEXT IN THE TEXT FIELD
938
//String strValueinTextField = textField.getText();
939
//INITIALIZE THE LONG VALUE IN TEXT TO -1
940
//long valueInText = -1;
941
// IF THE TEXT IS NOT NULL PARSE ITS LONG VALUE
942
//if (!strValueinTextField.equals("")) {
943
// valueInText = Long.parseLong(strValueinTextField);
944
//}
945
String JavaDoc textFieldText = textField.getText();
946                     String JavaDoc columnVectorText = (String JavaDoc)columnVector.get(index);
947
948                     if (!textFieldText.equals(columnVectorText)) {
949                         textField.setText(columnVectorText);
950                     }
951
952
953                     // IF THE LONG VALUE CORRESPONDING TO THE SELECTED TEXT OF COMBO NOT EQUAL
954
// TO THAT IN THE TEXT FIELD THEN CHANGE THE TEXT IN THE TEXT FIELD TO THAT VALUE
955
// IF ITS THE SAME LEAVE IT AS IS
956
//if (valueInText != valueCorresponingToIndex) {
957
// textField.setText( String.valueOf(valueCorresponingToIndex) );
958
//}
959

960                 } catch(NullPointerException JavaDoc npe) {
961                 } catch(NumberFormatException JavaDoc nfe) {
962                 }
963             }
964             else{
965                 textField.setText("");
966             }
967
968             textField.getDocument().addDocumentListener(textFieldDocumentListener);
969
970         }
971
972         public void focusLost(FocusEvent fe){
973             myKeyListener.resetSearchString();
974         }
975
976     } // private class MyComboListener implements ActionListener {
977

978
979 // DEPRECATED STUFF....................
980

981     /**
982      * Constructs a SSDBComboBox with the given parameters.
983      *
984      * @param _sSConnection database connection to be used.
985      * @param _query query to be used to retrieve the values from the database.
986      * @param _primaryKeyColumnName column name whose value has to be stored.
987      * @param _displayColumnName column name whose values are displayed in the combo box.
988      * @param _textField a text field to which the combo box has to be synchronized
989      *
990      * @deprecated
991      */

992     public SSDBComboBox(SSConnection _sSConnection, String JavaDoc _query, String JavaDoc _primaryKeyColumnName, String JavaDoc _displayColumnName, JTextField _textField) {
993
994         sSConnection = _sSConnection;
995         query = _query;
996         primaryKeyColumnName = _primaryKeyColumnName;
997         displayColumnName = _displayColumnName;
998         textField = _textField;
999
1000    }
1001
1002    /**
1003     * Sets the connection object to be used.
1004     *
1005     * @param _sSConnection connection object used for database.
1006     *
1007     * @deprecated
1008     * @see #setSSConnection
1009     */

1010    public void setConnection(SSConnection _sSConnection) {
1011        sSConnection = _sSConnection;
1012    }
1013
1014
1015    /**
1016     * Sets the new SSRowSet for the combo box.
1017     *
1018     * @param _sSRowSet SSRowSet to which the combo has to update values.
1019     *
1020     * @deprecated
1021     * @see #setSSRowSet
1022     */

1023    public void setRowSet(SSRowSet _sSRowSet) {
1024        sSRowSet = _sSRowSet;
1025        bind();
1026    }
1027
1028    /**
1029     * Sets the text field to which the underlying value is written to.
1030     *
1031     * @param _textField text field to which the selected item value has to
1032     * be written.
1033     *
1034     * @deprecated
1035     */

1036    public void setTextField(JTextField _textField) {
1037        textField = _textField;
1038    }
1039
1040    /**
1041     * Returns connection object used to get values from database.
1042     *
1043     * @return returns a SSConnection object.
1044     *
1045     * @deprecated
1046     * @see #getSSConnection
1047     */

1048    public SSConnection getConnection() {
1049        return sSConnection;
1050    }
1051
1052    /**
1053     * Returns the text field used to synchronize with the SSRowSet.
1054     *
1055     * @return returns the text field used to synchronize with the SSRowSet.
1056     *
1057     * @deprecated
1058     */

1059    public JTextField getTextField() {
1060        return textField;
1061    }
1062
1063    /**
1064     * returns the combo box that has to be displayed on screen.
1065     *
1066     * @return returns the combo box that displays the items.
1067     *
1068     * @deprecated
1069     */

1070    public JComboBox getComboBox() {
1071        return this;
1072    }
1073
1074    /**
1075     * Returns the combo box to be displayed on the screen.
1076     *
1077     * @return returns the combo box that displays the items.
1078     *
1079     * @deprecated
1080     */

1081    public Component getComponent() {
1082        return this;
1083    }
1084
1085
1086     /**
1087      * Deletes the item which has name equal to _name. If there are
1088      * more than one item with the same name then the first occurance is deleted.
1089      *
1090      * @param _name value of the item to be deleted.
1091      *
1092      * @return returns true on successful deletion else returns false.
1093      *
1094      * @deprecated
1095      */

1096     public boolean deleteItem(String JavaDoc _name) {
1097
1098        for (int i=0; i<getItemCount();i++) {
1099            if ( ((String JavaDoc)getItemAt(i)).equals(_name) ) {
1100                removeItemAt(i);
1101                columnVector.removeElementAt(i);
1102                numberOfItems--;
1103                return true;
1104            }
1105        }
1106        return false;
1107     }
1108
1109
1110     /**
1111      * Deletes the item which has display name equal to _name and corresponding value
1112      * as _value. If there is more than one item with same name and value then the first
1113      * occurance is deleted.
1114      *
1115      * @param _name name of item to be deleted
1116      * @param _value value of the item to be deleted.
1117      *
1118      * @return returns true on successful deletion else returns false.
1119      *
1120      * @deprecated
1121      */

1122     public boolean deleteItem(String JavaDoc _name, long _value) {
1123        for (int i=0; i<getItemCount();i++) {
1124            if ( ((String JavaDoc)getItemAt(i)).equals(_name) ) {
1125                if (((String JavaDoc)columnVector.elementAt(i)).equals(Long.toString(_value))) {
1126                    removeItemAt(i);
1127                    columnVector.removeElementAt(i);
1128                    numberOfItems--;
1129                    return true;
1130                }
1131            }
1132        }
1133        return false;
1134     }
1135
1136
1137} // end public class SSDBComboBox extends JComponent {
1138

1139
1140
1141/*
1142 * $Log: SSDBComboBox.java,v $
1143 * Revision 1.31 2005/02/22 16:07:10 prasanth
1144 * While checking if secondDisplayColumnName has to be used for displaying
1145 * text, in addition to checking for null, checking for empty string.
1146 *
1147 * Revision 1.30 2005/02/21 16:31:32 prasanth
1148 * In bind checking for empty columnName before binding the component.
1149 *
1150 * Revision 1.29 2005/02/13 15:38:20 yoda2
1151 * Removed redundant PropertyChangeListener and VetoableChangeListener class variables and methods from components with JComponent as an ancestor.
1152 *
1153 * Revision 1.28 2005/02/12 03:29:26 yoda2
1154 * Added bound properties (for beans).
1155 *
1156 * Revision 1.27 2005/02/11 22:59:27 yoda2
1157 * Imported PropertyVetoException and added some bound properties.
1158 *
1159 * Revision 1.26 2005/02/11 20:16:01 yoda2
1160 * Added infrastructure to support property & vetoable change listeners (for beans).
1161 *
1162 * Revision 1.25 2005/02/10 20:12:57 yoda2
1163 * Setter/getter cleanup & method reordering for consistency.
1164 *
1165 * Revision 1.24 2005/02/10 03:46:47 yoda2
1166 * Replaced all setDisplay() methods & calls with updateDisplay() methods & calls to prevent any setter/getter confusion.
1167 *
1168 * Revision 1.23 2005/02/07 20:26:06 yoda2
1169 * Updated to allow non-numeric primary keys. JavaDoc cleanup.
1170 *
1171 * Revision 1.22 2005/02/04 22:48:53 yoda2
1172 * API cleanup & updated Copyright info.
1173 *
1174 * Revision 1.21 2005/02/04 00:02:48 prasanth
1175 * 1. Removed commented out code.
1176 * 2. Using setDisplay in document listener.
1177 *
1178 * Revision 1.20 2005/02/02 23:36:58 yoda2
1179 * Removed setMaximiumSize() calls.
1180 *
1181 * Revision 1.19 2005/01/19 20:54:44 yoda2
1182 * API cleanup.
1183 *
1184 * Revision 1.18 2005/01/19 16:47:25 yoda2
1185 * Finished debugging and renamed some private variables to better distinguish between the bound column name and the column name representing the PK from the DB query.
1186 *
1187 * Revision 1.17 2005/01/19 03:17:08 yoda2
1188 * Rewrote to extend JComboBox rather than JComponent.
1189 *
1190 * Revision 1.16 2004/11/11 14:45:48 yoda2
1191 * Using TextPad, converted all tabs to "soft" tabs comprised of four actual spaces.
1192 *
1193 * Revision 1.15 2004/11/01 15:53:30 yoda2
1194 * Fixed various JavaDoc errors.
1195 *
1196 * Revision 1.14 2004/10/25 22:57:40 prasanth
1197 * Changed Connection to SSConnection.
1198 *
1199 * Revision 1.13 2004/10/25 22:03:18 yoda2
1200 * Updated JavaDoc for new datasource abstraction layer in 0.9.0 release.
1201 *
1202 * Revision 1.12 2004/10/25 19:51:03 prasanth
1203 * Modified to use the new SSRowSet instead of RowSet.
1204 *
1205 * Revision 1.11 2004/08/24 22:08:54 prasanth
1206 * Updating the numberOfItems variable in deleteItem & addItem.
1207 *
1208 * Revision 1.10 2004/08/12 23:52:36 prasanth
1209 * If seleted index is -1 the column value was not updated.
1210 * Now setting to null if the selected index is -1.
1211 *
1212 * Revision 1.9 2004/08/10 22:06:58 yoda2
1213 * Added/edited JavaDoc, made code layout more uniform across classes, made various small coding improvements suggested by PMD.
1214 *
1215 * Revision 1.8 2004/08/09 15:39:48 prasanth
1216 * Added key listener to transfer focus on enter key.
1217 *
1218 * Revision 1.7 2004/08/02 15:21:55 prasanth
1219 * 1. Deprecated setTextField function.
1220 * 2. Added setSelectedValue function.
1221 * 3. Also added addComponent (private) method.
1222 *
1223 * Revision 1.6 2004/03/08 16:43:37 prasanth
1224 * Updated copy right year.
1225 *
1226 * Revision 1.5 2004/02/23 16:37:41 prasanth
1227 * Added GENDER_OPTION.
1228 *
1229 * Revision 1.4 2003/11/26 21:21:14 prasanth
1230 * Functionality to format a date object before displaying in the combo.
1231 *
1232 * Revision 1.3 2003/10/31 16:06:25 prasanth
1233 * Added method setSeperator().
1234 *
1235 * Revision 1.2 2003/09/25 14:27:45 yoda2
1236 * Removed unused Import statements and added preformatting tags to JavaDoc descriptions.
1237 *
1238 * Revision 1.1.1.1 2003/09/25 13:56:43 yoda2
1239 * Initial CVS import for SwingSet.
1240 *
1241 */
Popular Tags