Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libUI / src / org / gvsig / gui / beans / comboBoxItemsSeeker / JComboBoxItemsSeekerDynamic.java @ 6706

History | View | Annotate | Download (60.1 KB)

1 6573 ppiqueras
package org.gvsig.gui.beans.comboBoxItemsSeeker;
2
3
import java.awt.Color;
4
import java.awt.event.ActionEvent;
5
import java.awt.event.FocusAdapter;
6
import java.awt.event.FocusEvent;
7
import java.awt.event.FocusListener;
8
import java.awt.event.KeyAdapter;
9
import java.awt.event.KeyEvent;
10
import java.awt.event.KeyListener;
11
import java.beans.PropertyChangeEvent;
12
import java.beans.PropertyChangeListener;
13
14
import javax.swing.ComboBoxEditor;
15
import javax.swing.ComboBoxModel;
16
import javax.swing.JComboBox;
17
import javax.swing.JOptionPane;
18
import javax.swing.event.DocumentEvent;
19
import javax.swing.event.DocumentListener;
20
import javax.swing.event.ListDataEvent;
21
import javax.swing.event.ListDataListener;
22 6666 ppiqueras
import javax.swing.event.PopupMenuEvent;
23
import javax.swing.event.PopupMenuListener;
24 6573 ppiqueras
import javax.swing.text.AttributeSet;
25
import javax.swing.text.BadLocationException;
26
import javax.swing.text.JTextComponent;
27
import javax.swing.text.PlainDocument;
28
29
30
import com.iver.andami.PluginServices;
31
32
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
33
 *
34
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
35
 *
36
 * This program is free software; you can redistribute it and/or
37
 * modify it under the terms of the GNU General Public License
38
 * as published by the Free Software Foundation; either version 2
39
 * of the License, or (at your option) any later version.
40
 *
41
 * This program is distributed in the hope that it will be useful,
42
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
43
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
44
 * GNU General Public License for more details.
45
 *
46
 * You should have received a copy of the GNU General Public License
47
 * along with this program; if not, write to the Free Software
48
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
49
 *
50
 * For more information, contact:
51
 *
52
 *  Generalitat Valenciana
53
 *   Conselleria d'Infraestructures i Transport
54
 *   Av. Blasco Ib??ez, 50
55
 *   46010 VALENCIA
56
 *   SPAIN
57
 *
58
 *      +34 963862235
59
 *   gvsig@gva.es
60
 *      www.gvsig.gva.es
61
 *
62
 *    or
63
 *
64
 *   IVER T.I. S.A
65
 *   Salamanca 50
66
 *   46005 Valencia
67
 *   Spain
68
 *
69
 *   +34 963163400
70
 *   dac@iver.es
71
 */
72
73
/**  VERSI?N EN DESARROLLO
74
 *  REVISAR COMENTARIOS Y C?DIGO QUE PUEDA SOBRAR
75
* This class allows users to insert a chain of characters and show all the sentences of the JComboBox that match its first ones characters with it.
76
* This class is also a Java Bean, and is made according the MVC (Model - View - Controller) pattern.
77
* This class has the View, the Control and can access to the Model.
78 6577 ppiqueras
* The behavior of this componet can be configurated by 7 flags: (Esto lo cambio!!!!!)
79 6573 ppiqueras
*  + The appearence of the items showed at the beginning and when the user presses the ESCAPE key: (This is configured with 2 flags -> 3 different states are possible)
80
*             -> maintainPositionItems -> When we see the list of all items, this are showed in the ordenation as they have been introduced (if true); (if false) each new item
81 6577 ppiqueras
*           when we write on the TextField of this Component will be showed at the end (esto ?ltimo creo q. no -> revisarlo)
82 6573 ppiqueras
*      -> all_Alphanumeric_Sorted -> All items we can see in this Component will be showed in alphanumeric ordenation (if true)
83
*  + The list of the items showed when the user makes a search writting or pressing the BACK-SPACE key (This is configured with 1 flag -> 2 different states are possible)
84
*      -> alphanumericSortedSearches -> When we write on the TextField of this Component all results (items) are showed in alphanumeric ordenation (if true)
85
*  + Key Sensitive or not when the user writes
86
*      -> key_Sensitive -> When we write on the TextField it can discriminate upper cases from down cases (if true) or not (if false) (This is configured with 1 flag -> 2 different states are possible)
87
*  + Show all items always
88
*      -> showAllItems -> If true -> this component shows all items always; if false -> this component only shows items that their first characters match with the string written by the user
89
*  + Use one color (black) or 2 colors (black by default and red if the string written doesn't match with the beginning of all items)
90
*      -> only_One_Color -> The text on the textField only will be showed on black color (if true); false -> if the text on the textField doesn't match with any current item of this component -> the text
91
*            will be showed on red color
92
*  +            * @param boolean (completeMatchedItem (explicar))
93 6576 ppiqueras
*  + @param boolean (useBeep (explicar))
94 6573 ppiqueras
*
95
* Default Values of the Flags:
96
*  -> maintainPositionItems -> true
97
*  -> all_Alphanumeric_Sorted -> true
98
*  -> alphanumericSortedSearches -> false
99
*  -> key_Sensitive -> false
100
*  -> showAllItems -> false
101
*  -> only_One_Color -> false
102
*
103
*  The flags are distributed in two classes:
104
*  -> ComboBoxSearcheableDynamicModel -> maintainPositionItems, all_Alphanumeric_Sorted, alphanumericSortedSearches, key_Sensitive, showAllItems
105
*  -> JComboBoxSearcheableDynamic -> only_One_Color
106
*
107
* Combinations of flags not allowed:
108
*         ->        maintainPositionItems == allAlphanumericSorted == true
109
*        ->        ((maintain_Position_Items == false) && (all_Alphanumeric_Sorted == true) && (alphanumeric_Sorted_Searches == false))
110
*   ->  showAllItems == true && maintainPositionItems == false (Creo que esta mal)
111
*
112
* Limitations:
113
* -> When we add more than one item with the same name (string value) -> the behavior of this component only considers one item in most of the cases when it does a search
114
* -> If this component has Hundreds,Thousands or even Million/s of items is probably that had quite delay to respond the evens of the user; this also depends of the machine where it's executed and other factors
115
*
116
* @author Pablo Piqueras Bartolom? (p_queras@hotmail.com)
117
*/
118
public class JComboBoxItemsSeekerDynamic extends JComboBox implements java.io.Serializable {
119
        //private static final long serialVersionUID = -1853812970336818959L;
120 6666 ppiqueras
        // PONER SERIALIZACI?N
121 6573 ppiqueras
122
        // eSTAS HAY QUE BORRARLAS!
123
/*        private Vector defaultItems;
124
        private Set notRemovedItems;
125
        private Set removedItems;*/
126
127 6638 ppiqueras
        private final int BEGINNING_VIEW_STATE = 0;
128
        private final int START_VIEW_STATE = 1;
129
        private final int SEARCH_VIEW_STATE = 2;
130
        private int currentShowState; // 0 -> at the beginning; 1 -> when is showing the start list of items; 2 -> when is showing a search list of items
131
132 6577 ppiqueras
133 6573 ppiqueras
        // CONFIGURATION FLAGS
134
        private boolean onlyOneColor;
135
        private boolean completeMatchedItem;
136 6576 ppiqueras
        private boolean useBeep;
137 6573 ppiqueras
        // END FLAGS
138
139
        // PUEDE QUE TB. sOBren
140
//        private boolean allItemsAreSorted;
141
142 6649 ppiqueras
        // Last selected item
143 6666 ppiqueras
        private Object selectedItem;
144
        private Object lastSelectedItem; // This is used for only update (refresh) de popup when a different item is selected
145
146 6573 ppiqueras
147
        // pueDE QUE TB. SOBRE
148 6613 ppiqueras
        private int num = 0;
149 6573 ppiqueras
//        private JTextField txtField;
150
151 6649 ppiqueras
        private final int POPUP_LIST_ITEMS_HEIGHT = 8;
152 6573 ppiqueras
        // Reference to the ui
153
        //private MetalComboBoxItemsSeekerUI ui;
154
155
        // Reference to the model
156
        private ComboBoxItemsSeekerDynamicModel model;
157
158
        // Some listeners for the Control between the View and de Model
159
        private KeyListener editorKeyListener;
160
        private FocusListener editorFocusListener;
161
        private DocumentListener documentListener;
162 6666 ppiqueras
        private ListDataListener modelListDataListener;
163
        private PopupMenuListener popupMenuListener;
164 6573 ppiqueras
165
        // Reference to the document of the Editor of this component for optimize the seeks
166
        private PlainDocumentSeeker document;
167
168 6638 ppiqueras
//        private String writtenString;
169 6573 ppiqueras
170 6649 ppiqueras
        private boolean continueOnStartViewState;
171 6677 ppiqueras
//        private boolean specialKeys; // ESC and TAB keys
172 6666 ppiqueras
        private boolean textKeyPressed;
173 6706 ppiqueras
        private boolean lastWasTheBeginningState;
174
//        private boolean keyPressed;
175 6677 ppiqueras
//        private boolean updatePopUp;
176 6646 ppiqueras
//        private boolean upOrDownKeyPressed;
177
//        private boolean deleteKeyPressed;
178
//        private boolean escapeKeyPressed;
179 6573 ppiqueras
180
        // OTRAS FLAGS que puede que sobren alguNAS
181
        private boolean selecting=false;
182
        private boolean hidePopupOnFocusLoss;
183
        private boolean hitBackspace=false;
184 6638 ppiqueras
        private boolean hitBackspaceOnSelection;
185
186 6573 ppiqueras
187
        /**
188
         * Default Constructor
189
         */
190
        public JComboBoxItemsSeekerDynamic() {
191
                // Invokes to the parent class constructor
192
                super();
193
194
                // Create attributes and set initial values
195
                this.initialize();
196
197
                // Set the default values of the flags
198 6576 ppiqueras
                this.onlyOneColor = false;
199
                this.completeMatchedItem = false; //true;
200
                this.useBeep = false; //true;
201 6573 ppiqueras
202
                // Other configuration tasks
203
                this.createDefaultListeners();
204
                this.configure();
205
                //this.configure();
206
        }
207
208
        /**
209
         * Default Constructor with four parameters: configure the 4 flags
210
         *
211
         * @param boolean (true -> maintains the position of the items; false -> don't maintains the position of the items)
212
         * @param boolean (true -> all items showed when we write on the textfield will be showed in alphanumeric ordenation; false -> they don't have to be in alphanumeric ordenation)
213
         * @param boolean (true -> all items showed will be in alphanumeric ordenation; false -> they don't have to be in alphanumeric ordenation)
214
         * @param boolean (true -> discriminates capital letters from small letters; false -> don't discriminates capital letters from small letters)
215
         */
216 6613 ppiqueras
        public JComboBoxItemsSeekerDynamic(int start_Behavior, int search_Behavior, boolean key_Sensitive)        {
217 6573 ppiqueras
                // Invokes to the parent class constructor
218
                super();
219
220
                // Create attributes and set initial values
221
                this.initialize();
222
223
                // Sets the options selected by the user
224 6613 ppiqueras
//                this.model.setMaintainPositionItems(maintain_Position_Items);
225
//                this.model.setAllAlphanumericSorted(all_Alphanumeric_Sorted);
226
//                this.model.setAlphanumericSortedSearches(alphanumeric_Sorted_Searches);
227
                this.model.setStartBehavior(start_Behavior);
228
                this.model.setStartBehavior(search_Behavior);
229 6573 ppiqueras
                this.model.setKeySensitive(key_Sensitive);
230
                this.model.setShowAllItems(false);
231 6576 ppiqueras
                this.onlyOneColor = false;
232 6625 ppiqueras
                this.completeMatchedItem = false; //true;
233 6613 ppiqueras
                this.useBeep = true;
234 6573 ppiqueras
235
                if (!testFlagsConfigurationOK())
236
                        JOptionPane.showMessageDialog(this, PluginServices.getText(this, "error_message_JComboBoxSearcheableDynamic"), PluginServices.getText(this, "exportJOP2Title"), JOptionPane.ERROR_MESSAGE);
237
                else
238
                        this.configure();
239
        }
240
241
        /**
242
         * Default Constructor with six parameters: configure the 6 flags
243
         *
244
         * @param boolean (true -> maintains the position of the items; false -> don't maintains the position of the items)
245
         * @param boolean (true -> all items showed when we write on the textfield will be showed in alphanumeric ordenation; false -> they don't have to be in alphanumeric ordenation)
246
         * @param boolean (true -> all items showed will be in alphanumeric ordenation; false -> they don't have to be in alphanumeric ordenation)
247
         * @param boolean (true -> discriminates capital letters from small letters; false -> don't discriminates capital letters from small letters)
248
         * @param boolean (true -> the text on the textField only will be showed on black color (if true); false -> if the text on the textField doesn't match with any current item of this component -> the text
249
         *                           will be showed on red color)
250
           * @param boolean (true -> this component shows all items always; false -> this component only shows items that their first characters match with the string written by the user)
251
           * @param boolean (completeMatchedItem (explicar))
252 6576 ppiqueras
           * @param boolean (useBeep (explicar))
253 6573 ppiqueras
         */
254 6613 ppiqueras
        public JComboBoxItemsSeekerDynamic(int start_Behavior, int search_Behavior, boolean key_Sensitive, boolean only_One_Color, boolean show_All_Items, boolean complete_Matched_Item, boolean use_Beep) {
255 6573 ppiqueras
                // Invokes to the parent class constructor
256
                super();
257
258
                // Create attributes and set initial values
259
                this.initialize();
260
261
                // Sets the options selected by the user
262 6613 ppiqueras
//                this.model.setMaintainPositionItems(maintain_Position_Items);
263
//                this.model.setAllAlphanumericSorted(all_Alphanumeric_Sorted);
264
//                this.model.setAlphanumericSortedSearches(alphanumeric_Sorted_Searches);
265
                this.model.setStartBehavior(start_Behavior);
266
                this.model.setStartBehavior(search_Behavior);
267 6573 ppiqueras
                this.model.setKeySensitive(key_Sensitive);
268
                this.model.setShowAllItems(show_All_Items);
269 6576 ppiqueras
                this.onlyOneColor = only_One_Color;
270
                this.completeMatchedItem = complete_Matched_Item;
271
                this.useBeep = use_Beep;
272 6573 ppiqueras
273
                if (!testFlagsConfigurationOK())
274
                        JOptionPane.showMessageDialog(this, PluginServices.getText(this, "error_message_JComboBoxSearcheableDynamic"), PluginServices.getText(this, "exportJOP2Title"), JOptionPane.ERROR_MESSAGE);
275
                else
276
                        this.configure();
277
        }
278
279
280
        /**
281
         *
282
         */
283
        private void initialize() {
284
//                // Creates the ui for this component and gets it reference
285
//                super.setUI(new MetalComboBoxItemsSeekerUI());
286
//                this.ui = (MetalComboBoxItemsSeekerUI) super.getUI();
287 6666 ppiqueras
//                super.setUI(new MetalComboBoxItemsSeekerUI());
288 6573 ppiqueras
289
                // Creates the model for this component and gets it reference
290
                super.setModel(new ComboBoxItemsSeekerDynamicModel());
291
                this.model = (ComboBoxItemsSeekerDynamicModel) super.getModel();
292
293
        // Allows user to edit on the combobox
294
                super.setEditable(true);
295
296 6638 ppiqueras
                // By default the last state of showign items was showing all the items (at the beginning of this component)
297
                currentShowState = BEGINNING_VIEW_STATE;
298
299 6573 ppiqueras
                // Set the last selected item -> if there isn't any item -> -1; else -> this will be 0
300 6649 ppiqueras
                super.setSelectedIndex(-1);
301 6666 ppiqueras
                this.selectedItem = null;
302
//                System.out.println("selectedItem: " + this.getSelectedIndex());
303 6573 ppiqueras
304
                // By default the keys Up and Down aren't pressed
305 6646 ppiqueras
//                this.upOrDownKeyPressed = false;
306
307
                // By default the keys Delete aren't pressed
308
//                this.escapeKeyPressed = false;
309 6649 ppiqueras
310 6706 ppiqueras
                // By default any text key has been pressed
311 6666 ppiqueras
                textKeyPressed = false;
312
313 6706 ppiqueras
314
315
316
//                // By default any key has been pressed
317
//                keyPressed = false;
318
319 6677 ppiqueras
//                specialKeys = false;
320
//                updatePopUp = false;
321 6666 ppiqueras
322 6649 ppiqueras
                // Remove the default mouse listener
323
//                super.removeMouseListener(super.getMouseListeners()[0]);
324 6573 ppiqueras
        }
325
326
        /**
327
         *
328
         */
329
        private void createDefaultListeners() {
330 6638 ppiqueras
                // TODO Auto-generated method stub
331 6573 ppiqueras
332
        // Define the key listener for the editor of this component
333
        this.defineEditorKeyListener(this);
334 6666 ppiqueras
335 6573 ppiqueras
        // Define the focus listener for the editor of this component
336
        this.defineEditorFocusListener(this);
337
338
        // Define a document listener for changes of text
339
        this.defineDocumentListener();
340
341
                // Define the list data listener for the model of this component
342
        this.defineModelListDataListener();
343 6666 ppiqueras
344
        // Define a popup menu listener for the popup of this component
345
        this.definePopUpMenuListener(this);
346 6573 ppiqueras
        }
347
348
        /**
349
         *  Define a document listener for changes of text
350
         */
351
        private void defineDocumentListener() {
352
                // TODO Auto-generated method stub
353
               documentListener = new DocumentListener() {
354
355
                        public void changedUpdate(DocumentEvent arg0) {
356
                                // TODO Auto-generated method stub
357
                        }
358
359
                        public void insertUpdate(DocumentEvent arg0) {
360
                                // TODO Auto-generated method stub
361 6706 ppiqueras
                                System.out.println("NUM: " + num + " DocumentListener->insertUpdate");
362
                                try {
363
                                        System.out.println("Texto insertado: ->" + document.getText(0, document.getLength()) + "<-");
364
365
                                } catch (BadLocationException e) {
366
                                        // TODO Auto-generated catch block
367
                                        e.printStackTrace();
368
                                }
369 6685 ppiqueras
                                num++;
370 6573 ppiqueras
371 6685 ppiqueras
                                // Indicate to the model that now is disabled the start view
372 6638 ppiqueras
                                 // This is used for the first text inserted to the document when the component is loaded and it does setSelectedIndex(0), to avoid use a search view
373 6649 ppiqueras
                                if (currentShowState == BEGINNING_VIEW_STATE)
374 6638 ppiqueras
                                {
375 6649 ppiqueras
                                        currentShowState = START_VIEW_STATE;
376 6706 ppiqueras
                                        lastWasTheBeginningState = true;
377 6649 ppiqueras
                                        continueOnStartViewState = true;
378 6706 ppiqueras
                                        System.out.println("Pasa al estado 1 (de vista inicial)");
379 6685 ppiqueras
                                }
380 6573 ppiqueras
                        }
381
382
                        public void removeUpdate(DocumentEvent arg0) {
383
                                // TODO Auto-generated method stub
384 6706 ppiqueras
                                System.out.println("NUM: " + num + " DocumentListener->removeUpdate");
385 6625 ppiqueras
                                num++;
386 6573 ppiqueras
                        }
387
                };
388
        }
389 6638 ppiqueras
390 6649 ppiqueras
        private void updateLastSelectionItem() {
391 6666 ppiqueras
                setSelectedItem(selectedItem);
392 6638 ppiqueras
        }
393 6573 ppiqueras
394
        /**
395
         *
396
         */
397
        private void configure() {
398
                // TODO Auto-generated method stub
399
400
                // Configure the document of the editor of this component
401
                this.configureDocument();
402
403
                // Configure the editor (ComboBoxEditor) of this component
404
                this.configureEditor(this.getEditor());
405
406
                // Configure the model of this component
407
                this.configureModel();
408 6638 ppiqueras
409 6666 ppiqueras
                // Configure the popup of this component
410
                this.configurePopUp();
411
412 6573 ppiqueras
        }
413
414 6666 ppiqueras
        /**
415
         *
416
         *
417
         */
418
        private void configurePopUp() {
419
                // TODO Auto-generated method stub
420
                this.addPopupMenuListener(this.popupMenuListener);
421
        }
422
423 6573 ppiqueras
//        /**
424
//         *
425
//         */
426
//        private void uninstallDefaultListeners() {
427
//
428
//
429
//        }
430
431
        /**
432
         *
433
         */
434
        private void configureModel() {
435
                // TODO Auto-generated method stub
436
                this.model.addListDataListener(this.modelListDataListener);
437
        }
438
439
        /**
440
         *
441
         */
442
        private void configureDocument() {
443
                // TODO Auto-generated method stub
444
445
                // Creates the document of the editor of this component
446
        document = new PlainDocumentSeeker();
447
        document.setJComboBoxItemsSeekerDynamicReference(this);
448
449
                // Set the written String
450 6638 ppiqueras
//                writtenString = "";
451 6573 ppiqueras
452
                // Remove all Previous document Listeners
453
//                DocumentListener documentListener[] = document.getDocumentListeners();
454
//                for (int i=0; i < documentListener.length; i++)
455
//                        document.removeDocumentListener(documentListener[i]);
456
457
                // Defines and add a Document listener for changes on the document of the editor of this component
458
                document.addDocumentListener(this.documentListener);
459
        }
460
461
462
        /**
463
         * Define the list data listener for the model of this component
464
         */
465
    public void defineModelListDataListener() {
466
467
                this.modelListDataListener = new ListDataListener()        {
468
469
                        public void contentsChanged(ListDataEvent e) {
470
                                // TODO Auto-generated method stub
471
//                                System.out.println("ContentsChanged");
472
473
                                // This flag indicates to the 'insertString' and 'remove' methods of the PlainDocumentSeeker that the text of the item selected or written by the user
474
                                //  hasn't been written on the TextEditor of ths component
475
                                selecting = false;
476
                        }
477
478
                        public void intervalAdded(ListDataEvent e) {
479
                                // TODO Auto-generated method stub
480
        //                        System.out.println("intervalAdded");
481
                        }
482
483
                        public void intervalRemoved(ListDataEvent e) {
484
                                // TODO Auto-generated method stub
485
        //                        System.out.println("intervalRemoved");
486
                        }
487
488
                };
489
490
    }
491
492
        /**
493
         * ?Sobra? Contiene c?digo interesante
494
         */
495
        private void defineAndAddPropertyChangeListener() {
496
                // Define and add a Listener for changes on the editor or the model of the JComboBox
497
        super.addPropertyChangeListener(new PropertyChangeListener() {
498
            public void propertyChange(PropertyChangeEvent ev) {
499
                if (ev.getPropertyName().equals("editor"))
500
                        configureEditor((ComboBoxEditor) ev.getNewValue());
501
                if (ev.getPropertyName().equals("model"))
502
                        model = (ComboBoxItemsSeekerDynamicModel) ev.getNewValue();
503
            }
504
        });
505
        }
506
507
        /**
508 6677 ppiqueras
         * ?SOBRA? De momento la estoy usando, pero no s? si sobra o no (S? SE EST? USANDO)
509 6573 ppiqueras
         */
510
        private void defineEditorFocusListener(JComboBoxItemsSeekerDynamic combo_Box) {
511
                final JComboBoxItemsSeekerDynamic comboBox = combo_Box;
512
513
                // TODO Auto-generated method stub
514
                // Highlight whole text when gaining focus
515
                editorFocusListener = new FocusAdapter() {
516
                        public void focusGained(FocusEvent e) {
517
                                highlightCompletedText(0);
518
                        }
519
520
                        public void focusLost(FocusEvent e) {
521
                                // Workaround for Bug 5100422 - Hide Popup on focus loss
522
                                if (hidePopupOnFocusLoss) comboBox.setPopupVisible(false);
523
                        }
524
                };
525
        }
526
527
        /**
528
         *
529
         */
530
        private void defineEditorKeyListener(JComboBoxItemsSeekerDynamic combo_Box) {
531
                final JComboBoxItemsSeekerDynamic comboBoxReference = combo_Box;
532
533 6706 ppiqueras
//                keyPressed = true;
534
535
536 6638 ppiqueras
                // This flag indicates to the 'insertString' and 'remove' methods of the PlainDocumentSeeker that the text of the item selected or written by the user
537
                //  hasn't been written on the TextEditor of ths component
538
539 6573 ppiqueras
                // TODO Auto-generated method stub
540
                editorKeyListener = new KeyAdapter()
541
                {
542 6649 ppiqueras
                        public void keyPressed(KeyEvent ke)  // Executed on the Start view state or Search view state
543 6573 ppiqueras
                        {
544 6706 ppiqueras
                                System.out.println("Tecla apretada: ->" + ke.getKeyChar() + "<-");
545 6638 ppiqueras
546 6685 ppiqueras
                                if (model.getParentSize() == 0)
547 6573 ppiqueras
                                {
548 6685 ppiqueras
                                        if (useBeep)
549
                                                comboBoxReference.getToolkit().beep(); // when available use: UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
550
                                }
551
                                else
552
                                {
553
                                        // This flag indicates to the 'insertString' and 'remove' methods of the PlainDocumentSeeker that the text of the item selected or written by the user
554
                                        //  hasn't been written on the TextEditor of ths component
555
                                        selecting = false;
556 6613 ppiqueras
557 6706 ppiqueras
                                        // This resolves the bug when the popup wasn't seen any time and the uses press a key that updates the view of the popup (the bug is that popup has the items but
558
                                        //  aren't seen
559
                                        if (lastWasTheBeginningState)
560
                                        {
561
                                                // This maintains visible the popup
562
                                                if (comboBoxReference.isDisplayable())
563
                                                        comboBoxReference.setPopupVisible(true);
564
                                                lastWasTheBeginningState = false;
565
                                        }
566 6685 ppiqueras
567
                                        hitBackspace=false;
568
569
                                        JTextComponent editor = (JTextComponent) comboBoxReference.getEditor().getEditorComponent();
570
571
                                        switch (ke.getKeyCode())
572
                                        {
573
                                                // determine if the pressed key is backspace (needed by the remove method)
574
                                                case KeyEvent.VK_BACK_SPACE :
575
                                                        hitBackspace=true;
576
                                                        hitBackspaceOnSelection=editor.getSelectionStart()!=editor.getSelectionEnd();
577 6706 ppiqueras
578 6685 ppiqueras
                                                        break;
579
                                                // ignore delete key
580
                                                case KeyEvent.VK_DELETE : // supr key in spanish keyboard
581
        //                                                specialKeys = true;
582 6706 ppiqueras
//                                                         This avoids that popup listener could report about it detected item (Este no va)
583
//                                                        textKeyPressed = true;
584 6677 ppiqueras
585 6685 ppiqueras
                                                        // If we remove characters by default if we use two color -> set color red ; and if the item would match in the lookUp algorithm of the PlainDocumentSeeker
586
                                                        //    text will be on black color
587
                                                if (!isOnlyOneColor())
588
                                                        comboBoxReference.getEditor().getEditorComponent().setForeground(Color.RED);
589
590
                                                        // Remove selected text:
591 6706 ppiqueras
                                                        System.out.println("GETMARK: " + editor.getCaret().getMark() + "GETCARETPOSITION" + editor.getCaretPosition());
592
593 6685 ppiqueras
                                                        try {
594
                                                                // If no characters are selected
595
                                                                if (editor.getCaret().getMark() == editor.getCaretPosition())
596
                                                                {
597
                                                                        // Remove the character which is on the right of the caret position
598 6706 ppiqueras
                                                                        if (editor.getCaretPosition() < document.getLength())
599
                                                                                document.remove(editor.getCaretPosition(), 1);
600 6685 ppiqueras
                                                                }
601
                                                                else // If there are characters selected
602
                                                                {
603
                                                                        // Remove the characters which are selected
604
        //                                                                int documentLength = document.getLength();
605
                                                                        int length = Math.abs(editor.getCaret().getMark() - editor.getCaretPosition());
606 6649 ppiqueras
607 6685 ppiqueras
                                                                        // Remove the characters which are selected
608
                                                                        document.remove(Math.min(editor.getCaret().getMark(), editor.getCaretPosition()), length);
609
                                                                }
610 6706 ppiqueras
                                                        } catch (BadLocationException e) {
611
                                                                // TODO Auto-generated catch block
612
                                                                e.printStackTrace();
613
                                                        }
614
615
                                                        switch(currentShowState)
616
                                                        {
617
                                                                case START_VIEW_STATE :
618
                                                                        if (document.getLength() > 0)
619
                                                                        {
620
                                                                                // If dynamic searches:
621
                                                                                try {
622
                                                                                        // If the search will be dynamic:
623
                                                                                        if (isDynamicSearchConfiguration())
624
                                                                                        {
625
                                                                                                model.setWrittenText(document.getText(0, document.getLength()));
626
                                                                                                System.out.println("Texto que se le env?a al modelo desde SUPR: ->" + document.getText(0, document.getLength()) + "<-");
627
                                                                                        }
628
                                                                                } catch (BadLocationException e) {
629
                                                                                        // TODO Auto-generated catch block
630
                                                                                        e.printStackTrace();
631
                                                                                }
632
633
                                                                                // Indicate to the model that now is disabled the start view
634
                                                                                if (currentShowState == START_VIEW_STATE)
635
                                                                                {
636
                                                                                        model.setStartViewFlag(false);
637
                                                                                        currentShowState = SEARCH_VIEW_STATE;
638
                        //                                                                updateLastSelectionItem();
639
                                                                                }
640
                                                                        }
641
                                                                        break;
642
                                                                case SEARCH_VIEW_STATE :
643
                                                                         // If there isn't characters
644
                                                                        if (document.getLength() == 0)
645
                                                                        {
646
                                                                                // This instruction avoids popup could failure when got invisible
647
                                                                                hidePopup();
648 6649 ppiqueras
649 6706 ppiqueras
                                                                                // If it's a dynamic search
650
                                                                                if (isDynamicSearchConfiguration())
651
                                                                                {
652
                                                                                        model.setWrittenText("");
653
                                                                                        System.out.println("Texto que se le env?a al modelo desde SUPR: ->\"\"<-");
654
                                                                                }
655 6685 ppiqueras
656
                                                                                // Return to the start view state
657
                                                                                model.setStartViewFlag(true);
658
                                                                                currentShowState = START_VIEW_STATE;
659 6706 ppiqueras
660
                                                                                // Select the first Item
661
                                                                                setSelectedIndex(0);
662
663
                                                                                highlightCompletedText(0);
664 6685 ppiqueras
                                                                        }
665 6706 ppiqueras
                                                                        else
666
                                                                        {
667
                                                                                // If dynamic searches:
668
                                                                                try {
669
                                                                                        // If the search will be dynamic:
670
                                                                                        if (isDynamicSearchConfiguration())
671
                                                                                        {
672
                                                                                                model.setWrittenText(document.getText(0, document.getLength()));
673
                                                                                                System.out.println("Texto que se le env?a al modelo desde SUPR: ->" + document.getText(0, document.getLength()) + "<-");
674
                                                                                        }
675
                                                                                } catch (BadLocationException e) {
676
                                                                                        // TODO Auto-generated catch block
677
                                                                                        e.printStackTrace();
678
                                                                                }
679
                                                                        }
680
                                                                        break;
681
                                                        }
682 6649 ppiqueras
683 6706 ppiqueras
                                                        updatePopUpView();
684 6677 ppiqueras
685 6685 ppiqueras
                                                        break;
686
                                                case KeyEvent.VK_ENTER :
687
        //                                                try {
688
        //                                                        specialKeys = true;
689 6706 ppiqueras
                                                                System.out.println("ENTRA EN EL C?DIGO DE ENTER");
690 6685 ppiqueras
691 6677 ppiqueras
                                                                // Reports about the written text to the model
692 6685 ppiqueras
                                                        try {
693
                                                                        // Reports about the written text to the model
694
                                                                        if (model.isDynamicSearch())
695
                                                                                model.setWrittenText(document.getText(0, document.getLength()));
696
                                                        } catch (BadLocationException e1) {
697 6677 ppiqueras
                                                                // TODO Auto-generated catch block
698 6685 ppiqueras
                                                                e1.printStackTrace();
699 6677 ppiqueras
                                                        }
700 6685 ppiqueras
701
                                                                // Indicate to the model that now is disabled the start view
702
                                                                if (currentShowState == START_VIEW_STATE)
703
                                                                {
704
                                                                        model.setStartViewFlag(false);
705
                                                                        currentShowState = SEARCH_VIEW_STATE;
706
        //                                                                updateLastSelectionItem();
707
                                                                }
708
709
710
        //                                                        String text = document.getText(0, document.getLength());
711
        //                                                        document.remove(0, document.getLength());
712
        //                                                        document.insertString(0, text, null);
713
        //
714
        //
715
        //
716
        ////                                                        // If the text doesn't completely match with the selectedItem.toString() -> if allow 2 colors -> set foreground color to red
717
        ////                                                        if (!onlyOneColor)
718
        ////                                                        {
719
        ////                                                                if (model.isKeySensitive())
720
        ////                                                                {
721
        ////                                                                        if (text.compareTo(getSelectedItem().toString()) != 0)
722
        ////                                                                                editor.setForeground(Color.RED);
723
        ////                                                                }
724
        ////                                                                else
725
        ////                                                                {
726
        ////                                                                        if (text.toUpperCase().compareTo(getSelectedItem().toString().toUpperCase()) != 0)
727
        ////                                                                                editor.setForeground(Color.RED);
728
        ////                                                                }
729
        ////                                                        }
730
        //                                                } catch (BadLocationException e1) {
731
        //                                                        // TODO Auto-generated catch block
732
        //                                                        e1.printStackTrace();
733
        //                                                }
734
                                                        hidePopup();
735
                                                        break;
736
                                                case KeyEvent.VK_DOWN :
737
                                                    // If the key (typed, pressed and) released has been the Down Key -> when there isn't any text (item of the list) selected, select the first
738
        //                                                ke.consume();
739
                //                                        selecting = true; // For indicate to the 'insertString' of the 'PlainDocumentSeeker' class that an item has been selected
740
        //                                                upOrDownKeyPressed = true;
741
        //                                                continueOnStartViewState = true;
742 6677 ppiqueras
743 6685 ppiqueras
                                                        // This allows user press the key DOWN for select another item of the start view list
744
        //                                                if ((model.isStartViewFlag()) && (lastWasStartShow))
745
        //                                                        lastWasStartShow = true;
746 6649 ppiqueras
747 6685 ppiqueras
        //                                                // Reports about the written text to the model
748
        //                                                try {
749
        //                                                        if (model.isDynamicSearch())
750
        //                                                                model.setWrittenText(document.getText(0, document.getLength()));
751
        //                                                } catch (BadLocationException e2) {
752
        //                                                        // TODO Auto-generated catch block
753
        //                                                        e2.printStackTrace();
754
        //                                                }
755 6649 ppiqueras
756 6685 ppiqueras
                                                        // If items are disordered -> get the index of the selected item
757
                                                        if (model.nowItemsAreDisordered())
758
                                                                updateLastSelectionItem();
759
760
                                                        if (getItemCount() > 0)
761
                                                        {
762
                                                                if (getSelectedIndex() == (getItemCount()-1))
763
                                                                        ((JComboBox)comboBoxReference).setSelectedIndex(0);
764
                                                                else
765
                                                                        ((JComboBox)comboBoxReference).setSelectedIndex(getSelectedIndex()+1);
766 6677 ppiqueras
                                                        }
767
768 6685 ppiqueras
        //                                                model.setCurrentString(getSelectedItem().toString());
769 6649 ppiqueras
770 6685 ppiqueras
        //                                                lastSelectedIndex = getSelectedIndex();
771 6666 ppiqueras
                                                        selectedItem = getSelectedItem();
772 6685 ppiqueras
                                                        showPopup();
773
                                                        break;
774
                                                case KeyEvent.VK_UP :
775
                                                    // If the key (typed, pressed and) released has been the Up Key -> when there isn't any text (item of the list) selected, select the last
776
        //                                                ke.consume();
777
                //                                        selecting = true; // For indicate to the 'insertString' of the 'PlainDocumentSeeker' class that an item has been selected
778
        //                                                upOrDownKeyPressed = true;
779
        //                                                continueOnStartViewState = true;
780 6677 ppiqueras
781 6685 ppiqueras
                                                        // This allows user press the key UP for select another item of the start view list
782
        //                                                if ((model.isStartViewFlag()) && (lastWasStartShow))
783
        //                                                        lastWasStartShow = true;
784
785
        //                                                // Reports about the written text to the model
786
        //                                                try {
787
        //                                                        if (model.isDynamicSearch())
788
        //                                                                model.setWrittenText(document.getText(0, document.getLength()));
789
        //                                                } catch (BadLocationException e2) {
790
        //                                                        // TODO Auto-generated catch block
791
        //                                                        e2.printStackTrace();
792
        //                                                }
793
794
                                                        // If items are disordered -> get the index of the selected item
795
                                                        if (model.nowItemsAreDisordered())
796
                                                                updateLastSelectionItem();
797
798
                                                        switch(getSelectedIndex())
799 6573 ppiqueras
                                                        {
800 6685 ppiqueras
                                                                case -1: case 0:
801
                                                                        ((JComboBox)comboBoxReference).setSelectedIndex(getItemCount()-1);
802
                                                                        break;
803
                                                                default:
804
                                                                        ((JComboBox)comboBoxReference).setSelectedIndex(getSelectedIndex()-1);
805 6573 ppiqueras
                                                        }
806 6685 ppiqueras
807
        //                                                model.setCurrentString(getSelectedItem().toString());
808
                                                        selectedItem = getSelectedItem();
809
        //                                                lastSelectedIndex = getSelectedIndex();
810
                                                        showPopup();
811
                                                        break;
812
                                                case KeyEvent.VK_LEFT :
813
                                                        // Move the caret to left
814
                                                        if (editor.getCaretPosition() > 0)
815
                                                                editor.setCaretPosition(editor.getCaretPosition() - 1);
816 6573 ppiqueras
                                                        else
817
                                                        {
818 6685 ppiqueras
                                                // User hit backspace with the cursor positioned on the start => beep
819
                                                    if (useBeep)
820
                                                            getToolkit().beep(); // when available use: UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
821 6573 ppiqueras
                                                        }
822 6685 ppiqueras
                                                        //ke.consume();
823
                                                        break;
824
                                                case  KeyEvent.VK_RIGHT :
825
                                                        // Move the caret to right
826 6677 ppiqueras
                                                        try {
827 6685 ppiqueras
                                                                if (editor.getCaretPosition() < (document.getText(0, document.getLength())).length())
828
                                                                        editor.setCaretPosition(editor.getCaretPosition() + 1);
829
                                                                else
830
                                                                {
831
                                                                    // User hit backspace with the cursor positioned on the start => beep
832
                                                                        if (useBeep)
833
                                                                                getToolkit().beep(); // when available use: UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
834
                                                                }
835
                                                        } catch (BadLocationException e) {
836 6677 ppiqueras
                                                                // TODO Auto-generated catch block
837 6685 ppiqueras
                                                                e.printStackTrace();
838 6677 ppiqueras
                                                        }
839 6685 ppiqueras
                                                        //ke.consume();
840
                                                        break;
841
                                                case  KeyEvent.VK_PAGE_DOWN :
842
                                                        if (getSelectedIndex() != -1)
843
                                                        {
844
        //                                                        // Reports about the written text to the model
845
        //                                                        try {
846
        //                                                                if (model.isDynamicSearch())
847
        //                                                                        model.setWrittenText(document.getText(0, document.getLength()));
848
        //                                                        } catch (BadLocationException e2) {
849
        //                                                                // TODO Auto-generated catch block
850
        //                                                                e2.printStackTrace();
851
        //                                                        }
852
853
                                                                int index = getSelectedIndex() + POPUP_LIST_ITEMS_HEIGHT;
854
855
                                                                if (index < getItemCount())
856
                                                                        setSelectedIndex(index);
857
                                                                else
858
                                                                        setSelectedIndex(getItemCount()-1);
859
860
                                                                selectedItem = getSelectedItem();
861
                                                        }
862
863
                                                //        ke.consume();
864
                                                        break;
865
                                                case KeyEvent.VK_PAGE_UP :
866
                                                        if (getSelectedIndex() != -1)
867
                                                        {
868
        //                                                        // Reports about the written text to the model
869
        //                                                        try {
870
        //                                                                if (model.isDynamicSearch())
871
        //                                                                        model.setWrittenText(document.getText(0, document.getLength()));
872
        //                                                        } catch (BadLocationException e2) {
873
        //                                                                // TODO Auto-generated catch block
874
        //                                                                e2.printStackTrace();
875
        //                                                        }
876
877
                                                                int index = getSelectedIndex() - POPUP_LIST_ITEMS_HEIGHT;
878
879
                                                                if (index > -1)
880
                                                                        setSelectedIndex(index);
881
                                                                else
882
                                                                        setSelectedIndex(0);
883
884
                                                                selectedItem = getSelectedItem();
885
                                                        }
886
887
                                                //        ke.consume();
888
                                                        break;
889
                                                case KeyEvent.VK_HOME : // 'Inicio' key on the spanish keyboard
890
                                                        editor.setCaretPosition(0);
891
                                                        break;
892
                                                case KeyEvent.VK_END :  // 'Fin' key on the spanish keyboard
893
                                                        editor.setCaretPosition(document.getLength());
894
                                                        break;
895
                                                case KeyEvent.VK_TAB :
896
        //                                                specialKeys = true;
897 6677 ppiqueras
898 6706 ppiqueras
                                                        // This avoids that popup listener could report about it detected item
899
                                                        textKeyPressed = true;
900
901 6685 ppiqueras
                                                        if (model.getSize() > 0)
902 6649 ppiqueras
                                                        {
903 6685 ppiqueras
        //                                                        System.out.println("SelectedIndex: " + getSelectedIndex());
904
        //                                                        boolean update = false;
905
906
                                                                if (((JComboBox)comboBoxReference).getSelectedIndex() == -1)
907
                                                                {
908
        //                                                                lastSelectedIndex = 0;
909
        //                                                                ((JComboBox)comboBoxReference).setSelectedIndex(0);
910
                                                                        //updatePopUp = true; // Indicate to the document.insertString that has update the popup after insert
911
        //                                                                updatePopUpView();
912
        //                                                                comboBoxReference.setSelectedIndex(0);
913
                                                                        selectedItem = comboBoxReference.getItemAt(0); //.getSelectedItem();
914
                                                                }
915
                                                                else
916
                                                                {
917
        //                                                                lastSelectedIndex = getSelectedIndex();
918
        //                                                                updatePopUp = true; // Indicate to the document.insertString that has update the popup after insert
919
        //                                                                updatePopUpView();
920
                                                                        selectedItem = comboBoxReference.getSelectedItem();
921
922
        //                                                                setSelectedIndex());        // Complete the item string value in the document of the editor
923
        //                                                                update = true;
924
                                                                }
925
926
                                                                document.setText(selectedItem.toString());
927
928
                                                                // Reports about the written text to the model
929
//                                                                try {
930
                                                                if (model.isDynamicSearch()) {
931
                                                                        model.setWrittenText(selectedItem.toString());
932 6706 ppiqueras
                                                                        System.out.println("Texto que se le env?a al modelo: ->" + selectedItem.toString() + "<-");
933 6685 ppiqueras
                                                                }
934
935
//                                                                } catch (BadLocationException e2) {
936
//                                                                        // TODO Auto-generated catch block
937
//                                                                        e2.printStackTrace();
938
//                                                                }
939
//
940
                                                                if (currentShowState == START_VIEW_STATE)
941
                                                                {
942
                                                                        model.setStartViewFlag(false);
943
                                                                        currentShowState = SEARCH_VIEW_STATE;
944
        //                                                                updatePopUpView(); // Update to the new popup view
945
                                                                }
946
947
948
                                                                // It's supposed that the text on the document is equal as the string value of the selected item -> then text must be on black color
949
                                                                comboBoxReference.getEditor().getEditorComponent().setForeground(Color.BLACK);
950
951
                                                                updatePopUpView();
952
953
954
        //                                                        document.setText(selectedItem.toString());
955
956
        //                                                        continueOnStartViewState = false;
957
958
                                                                // HidePopUp + ShowPopUp to force update the popup list of items
959
        //                                                        hidePopup();
960
        //                                                        showPopup();
961
        ////                                                        hidePopup();
962 6649 ppiqueras
                                                        }
963 6685 ppiqueras
                                                        break;
964
                                                case KeyEvent.VK_ESCAPE :
965
                                                        // Reset to the Start View State
966
        //                                                model.setStartViewFlag(true);
967 6677 ppiqueras
968 6685 ppiqueras
                                                        // Force update the popup
969
                                                        if (isPopupVisible())
970
                                                                hidePopup();
971
972
                                                        model.setWrittenText("");
973 6706 ppiqueras
                                                        selectedItem = null;
974 6677 ppiqueras
975 6685 ppiqueras
        //                                                currentShowState = START_VIEW_STATE;
976
                                                        if (currentShowState == SEARCH_VIEW_STATE)
977
                                                        {
978
                                                                try {
979
                                                                        document.remove(0, document.getLength());
980
                                                                } catch (BadLocationException e) {
981
                                                                        // TODO Auto-generated catch block
982
                                                                        e.printStackTrace();
983
                                                                }
984
985
        //                                                        setSelectedItem(selectedItem);
986
        //                                                        setSelectedIndex(model.getIndexOf(selectedItem));
987
988
                                                                // Return to the start view state
989
                                                                model.setStartViewFlag(true);
990
                                                                currentShowState = START_VIEW_STATE;
991
                //                                                escapeKeyPressed = true;
992
        //                                                        continueOnStartViewState = true;
993
994
                                                                // If items are disordered -> get the index of the selected item
995
        //                                                        if (model.nowItemsAreDisordered())
996
        //                                                                updateLastSelectionItem();
997 6706 ppiqueras
998
                                                                // Select the first Item
999
                                                                setSelectedIndex(0);
1000
//                                                                selectFirstItemAddedToModel();
1001 6685 ppiqueras
1002
        //                                                        updatePopUp = true;
1003
        //                                                        updatePopUpView();
1004
1005
                                                                //updateLastSelectionItem();
1006
                //                                                setSelectedIndex(lastSelectedIndex);
1007
                                                                highlightCompletedText(0);
1008
                                                                // HidePopUp + ShowPopUp to force update the popup list of items
1009
                //                                                hidePopup();
1010
                //                                                showPopup();
1011 6649 ppiqueras
                                                        }
1012 6685 ppiqueras
                                                        else
1013
                                                        {
1014 6706 ppiqueras
        //                                                         Select the first Item
1015
                                                                setSelectedIndex(0);
1016
//                                                                selectFirstItemAddedToModel();
1017 6685 ppiqueras
1018
                                                                highlightCompletedText(0);
1019
                                                        }
1020
                                                        updatePopUpView();
1021
                                                        break;
1022
                                                case KeyEvent.VK_SHIFT : // Do nothing
1023
                                                        break;
1024
                                                case KeyEvent.VK_ALT_GRAPH : // Do nothing
1025
                                                        break;
1026
                                                case KeyEvent.VK_ALT : // Do nothing
1027
                                                        break;
1028
                                                case KeyEvent.VK_CONTROL : // Do nothing
1029
                                                        break;
1030 6706 ppiqueras
                                                case KeyEvent.VK_NUM_LOCK : // Do nothing
1031
                                                        break;
1032
                                                case KeyEvent.VK_CAPS_LOCK : // Do nothing
1033
                                                        break;
1034 6685 ppiqueras
                                                default:
1035 6706 ppiqueras
                                                        System.out.println("Actualiza view flag a false");
1036
1037
                                                        System.out.println("LASTITEM1 :" + lastSelectedItem);
1038
1039
                                                        System.out.println("GETMARK: " + editor.getCaret().getMark() + "GETCARETPOSITION" + editor.getCaretPosition());
1040
1041 6685 ppiqueras
                                                if (model.isDynamicSearch())
1042
                                                {
1043 6706 ppiqueras
                                                        // Force update the popup
1044
//                                                        hidePopup();
1045
1046 6685 ppiqueras
                                                        String text;
1047
                                                        if (editor.getCaretPosition() == editor.getCaret().getMark())
1048
                                                                text = editor.getText().substring(0, editor.getCaretPosition()) + ke.getKeyChar() + editor.getText().substring(editor.getCaretPosition(), editor.getText().length());
1049
                                                        else
1050
                                                        {
1051
                                                                text = "" + editor.getText().substring(0, (int) Math.min(editor.getCaretPosition(), editor.getCaret().getMark())) + ke.getKeyChar();
1052
                                                                text += editor.getText().substring((int) Math.max(editor.getCaretPosition(), editor.getCaret().getMark()), editor.getText().length());
1053
                                                        }
1054
1055
                                                            // Reports about the written text to the model
1056 6706 ppiqueras
                                                                   System.out.println("Texto que se le env?a KEY al modelo: ->" + text + "<-");
1057 6685 ppiqueras
                                                            model.setWrittenText(text);
1058 6649 ppiqueras
1059 6685 ppiqueras
1060
                                                            // Indicate to the model that now is disabled the start view
1061
                                                            if (currentShowState == START_VIEW_STATE)
1062
                                                            {
1063
                                                                    model.setStartViewFlag(false);
1064
                                                                    currentShowState = SEARCH_VIEW_STATE;
1065
        //                                                            updateLastSelectionItem();
1066
                                                            }
1067
1068
1069
        //                                                    textKeyPressed = false;
1070
                                                }
1071
1072
                                                updatePopUpView();
1073 6706 ppiqueras
                                                        textKeyPressed = true;
1074 6649 ppiqueras
1075
1076 6706 ppiqueras
                                                        System.out.println("Key Pressed:" + ke.getKeyCode());
1077 6685 ppiqueras
                                        }
1078 6666 ppiqueras
1079 6685 ppiqueras
                                        // Consume the key event for not to use the handler of the keyboard of other components
1080
                                        ke.consume();
1081
                    }
1082
                        }
1083 6573 ppiqueras
                };
1084 6706 ppiqueras
1085
//                keyPressed = false;
1086 6573 ppiqueras
        }
1087
1088 6649 ppiqueras
        /**
1089
         *
1090
         */
1091 6666 ppiqueras
        private void definePopUpMenuListener(JComboBoxItemsSeekerDynamic combo_Box) {
1092 6649 ppiqueras
                final JComboBoxItemsSeekerDynamic comboBoxReference = combo_Box;
1093 6666 ppiqueras
1094
                        this.popupMenuListener = new PopupMenuListener() {
1095 6649 ppiqueras
1096
                        /*
1097 6666 ppiqueras
                         *  (non-Javadoc)
1098
                         * @see javax.swing.event.PopupMenuListener#popupMenuCanceled(javax.swing.event.PopupMenuEvent)
1099 6649 ppiqueras
                         */
1100 6666 ppiqueras
                        public void popupMenuCanceled(PopupMenuEvent e) {
1101
                                // TODO Auto-generated method stub
1102 6706 ppiqueras
                                System.out.println("MenuCANCELED");
1103 6666 ppiqueras
                        }
1104
1105
                        /*
1106
                         *  (non-Javadoc)
1107
                         * @see javax.swing.event.PopupMenuListener#popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent)
1108
                         */
1109
                        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
1110
                                // TODO Auto-generated method stub
1111 6706 ppiqueras
                                System.out.println("MenuBECOMEINVISIBLE");
1112 6666 ppiqueras
1113
                                if (!textKeyPressed)
1114
                                {
1115 6685 ppiqueras
                                        if (lastSelectedItem != null)
1116 6666 ppiqueras
                                        {
1117 6685 ppiqueras
                                        // If the user has select a different item with the mouse, and this is in the Start View State -> change to the Search View State
1118
                                                if (!getSelectedItem().equals(lastSelectedItem))
1119 6666 ppiqueras
                                                {
1120 6706 ppiqueras
                                                        System.out.println("POPUP: NO SON IGUALES");
1121 6685 ppiqueras
1122
                                                        // Reports about the written text to the model
1123
                                                        if (model.isDynamicSearch())
1124 6706 ppiqueras
                                                        {
1125 6685 ppiqueras
                                                                model.setWrittenText(getSelectedItem().toString());
1126 6706 ppiqueras
                                                                System.out.println("Texto que le envia POPUP al modelo: ->" + getSelectedItem().toString() + "<-");
1127
                                                        }
1128 6685 ppiqueras
1129
                                                        if (currentShowState == START_VIEW_STATE)
1130
                                                        {
1131
                                                                model.setStartViewFlag(false);
1132
                                                                currentShowState = SEARCH_VIEW_STATE;
1133
                //                                                updateLastSelectionItem();
1134
                                                        }
1135 6706 ppiqueras
                                                        System.out.println("Selected index of item: " + lastSelectedItem.toString() + " is " + getSelectedIndex());
1136 6685 ppiqueras
        //                                                updatePopUpView();
1137
        //                                                setSelectedIndex(1);
1138 6666 ppiqueras
                                                }
1139 6706 ppiqueras
                                                else
1140
                                                        System.out.println("POPUP: SON IGUALES");
1141 6666 ppiqueras
                                        }
1142
                                }
1143
                        }
1144
1145
                        /*
1146
                         *  (non-Javadoc)
1147
                         * @see javax.swing.event.PopupMenuListener#popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent)
1148
                         */
1149
                        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
1150
                                // TODO Auto-generated method stub
1151 6706 ppiqueras
                                System.out.println("MenuBECOMEVISIBLE");
1152 6666 ppiqueras
                                lastSelectedItem = selectedItem; // This object is used for know if the user has select a different item with the mouse
1153
                        }
1154 6649 ppiqueras
                };
1155 6666 ppiqueras
         }
1156
1157 6706 ppiqueras
1158
/**
1159
 * Returns true if the model has a dynamic search configuration
1160
 *
1161
 * @return
1162
 */
1163
private boolean isDynamicSearchConfiguration() {
1164
        switch(model.getSearchBehavior())
1165
        {
1166
                case ComboBoxItemsSeekerDynamicModel.MAINTAIN_ORIGINAL_POSITION_DYNAMIC_SEARCH :
1167
                case ComboBoxItemsSeekerDynamicModel.ORDERED_DYNAMIC_SEARCH :
1168
                case ComboBoxItemsSeekerDynamicModel.DISORDERED_DYNAMIC_SEARCH :
1169
                        return true;
1170
        }
1171
1172
        return false;
1173
}
1174 6666 ppiqueras
1175
1176
//                comboBoxReference.getUI().
1177
//                for (int i=0; i<comboBoxReference.getComponentCount(); i++) {
1178
//                        System.out.println("Componente: " + comboBoxReference.getComponent(i).getName());
1179
//                        comboBoxReference.getComponent(i).addMouseListener(editorMouseListener);
1180
//
1181
//                        }
1182 6649 ppiqueras
//                this.addMouseListener(editorMouseListener);
1183 6666 ppiqueras
//        }
1184 6649 ppiqueras
1185 6706 ppiqueras
        /**
1186
         * Selects the first item added to the model
1187
         */
1188
        public void selectFirstItemAddedToModel() {
1189 6649 ppiqueras
                // Select the first Item added
1190
                Object item = model.getFirstItemAdded();
1191
                if (item != null)
1192
                        setSelectedItem(item);
1193
        }
1194
1195 6573 ppiqueras
        private void configureEditor(ComboBoxEditor newEditor) {
1196
            JTextComponent editor = (JTextComponent) this.getEditor().getEditorComponent();
1197
1198
            // If there isn't any change on the editor
1199
            if (editor == newEditor)
1200
                    return;
1201
1202
                // Remove the default or last keyListener and FocusListener of the editor of this component
1203
        if (editor != null) {
1204
            editor.removeKeyListener(this.editorKeyListener);
1205 6649 ppiqueras
//            editor.removeMouseListener(this.editorMouseListener);
1206 6573 ppiqueras
            editor.removeFocusListener(this.editorFocusListener);
1207
        }
1208
1209
        // Add the new keyListener and FocusListener for this editor and sets
1210
        //   it document as a PlainDocument to optimize the searches of items
1211
        //   when user writes on this editor
1212
        if (newEditor != null) {
1213
            editor = (JTextComponent) newEditor.getEditorComponent();
1214
            editor.addKeyListener(this.editorKeyListener);
1215 6649 ppiqueras
//            editor.addMouseListener(this.editorMouseListener);
1216 6573 ppiqueras
            editor.addFocusListener(this.editorFocusListener);
1217
            editor.setDocument(this.document);
1218
1219
                    // Disable the focus transversal keys (Example: CTRL+TAB) for enable the TAB key
1220
                    editor.setFocusTraversalKeysEnabled(false);
1221
        }
1222
        }
1223
1224
        /**
1225
         * Marks text since 'start' position to its end on a grey color
1226
         *
1227
         * @param start Start position for mark the text
1228
         */
1229
    private void highlightCompletedText(int start) {
1230
            JTextComponent editor = (JTextComponent) this.getEditor().getEditorComponent();
1231
1232
        editor.setCaretPosition(document.getLength());
1233
        editor.moveCaretPosition(start);
1234
    }
1235
1236 6649 ppiqueras
    /**
1237
     *
1238
     */
1239
    private void updatePopUpView() {
1240
            // HidePopUp + ShowPopUp to force update the popup list of items
1241
                hidePopup();
1242
                showPopup();
1243 6706 ppiqueras
                this.setVisible(true);
1244 6649 ppiqueras
    }
1245
1246 6573 ppiqueras
////// REDEFINITION OF SOME METHODS OF JCOMBOBOX //////
1247
1248
1249
        /*
1250
         *  (non-Javadoc)
1251
         * @see javax.swing.JComboBox#actionPerformed(java.awt.event.ActionEvent)
1252
         */
1253
        public void actionPerformed(ActionEvent e)
1254
        {
1255
                super.actionPerformed(e);
1256
//                System.out.println("Action-Performed");
1257
1258
                // This flag indicates to the 'insertString' method of the PlainDocumentSeeker that the text of the item selected or written by the user
1259
                //  hasn't been written on the TextEditor of ths component
1260
                selecting = false;
1261
        }
1262
1263
1264
    /*
1265
     * (non-Javadoc)
1266
     * @see javax.swing.JComboBox#addItem(java.lang.Object)
1267
     */
1268
    public void addItem(Object anObject) {
1269 6706 ppiqueras
                // Adds the item to this component
1270 6573 ppiqueras
                model.addElement(anObject);
1271
1272 6576 ppiqueras
//                System.out.println("LastSelectedIndexWas: " + this.lastSelectedIndex);
1273 6706 ppiqueras
1274
                // Set the last selected item -> by default select the first item:
1275
                // This is used to show the first item that model returns when we add a new item. This also
1276
                //  corrects the 'mistake' produced by 'ComboBoxModel' when is added a new item and there wasn't
1277
                //  any selected -> that the 'ComboBoxModel' selects by default the first added (that in our case
1278
                //  might not be the same as the first item seen in the popup list)
1279
                if (this.getSelectedIndex() != 0)
1280 6573 ppiqueras
                {
1281 6649 ppiqueras
                        this.setSelectedIndex(0);
1282 6666 ppiqueras
                        this.selectedItem = this.getSelectedItem();
1283 6573 ppiqueras
                }
1284
        }
1285
1286 6706 ppiqueras
    /*
1287
     * (non-Javadoc)
1288
     * @see javax.swing.JComboBox#removeAllItems()
1289
     */
1290
    public void        removeAllItems() {
1291
            // Removes all items from the model
1292
            model.removeAllElements();
1293
1294
            currentShowState = BEGINNING_VIEW_STATE;
1295
    }
1296
1297
    /*
1298
     * (non-Javadoc)
1299
     * @see javax.swing.JComboBox#removeItem(java.lang.Object)
1300
     */
1301
    public void        removeItem(Object anObject) {
1302
            // Removes an object from the model
1303
            model.removeElement(anObject);
1304
1305
            if (model.getSize() == 0)
1306
                    currentShowState = BEGINNING_VIEW_STATE;
1307
    }
1308
1309
    /*
1310
     * (non-Javadoc)
1311
     * @see javax.swing.JComboBox#removeItemAt(int)
1312
     */
1313
    public void        removeItemAt(int anIndex) {
1314
               // Removes an object, which is in a determinated position (index), from the model
1315
            model.removeElementAt(anIndex);
1316
1317
            if (model.getSize() == 0)
1318
                    currentShowState = BEGINNING_VIEW_STATE;
1319
    }
1320
1321 6573 ppiqueras
//    /*
1322
//     * (non-Javadoc)
1323
//     * @see javax.swing.JComboBox#getSelectedIndex()
1324
//     */
1325
//    public int getSelectedIndex() {
1326
//            // ??Modificarlo??
1327
//            return super.getSelectedIndex();
1328
//    }
1329
1330
    /*
1331
     * (non-Javadoc)
1332
     * @see javax.swing.JComboBox#getItemCount()
1333
     */
1334
    public int getItemCount() {
1335
            return model.getSize();
1336
    }
1337
1338
    /*
1339
     * (non-Javadoc)
1340
     * @see javax.swing.JComboBox#getItemAt(int)
1341
     */
1342
    public Object getItemAt(int index) {
1343
            return model.getElementAt(index);
1344
    }
1345
1346
    /*
1347
     * (non-Javadoc)
1348
     * @see javax.swing.JComboBox#setModel(javax.swing.ComboBoxModel)
1349
     */
1350
    public void setModel(ComboBoxModel aModel) { //PROBLEMA
1351
1352
            // Depending on the type of class of the current object, this object will execute different code
1353
            if (aModel instanceof ComboBoxItemsSeekerDynamicModel)
1354
            {
1355
//                    System.out.println("A");
1356
                    //super.setModel(aModel);
1357
                    super.setModel(aModel);
1358
                    model = (ComboBoxItemsSeekerDynamicModel)super.getModel();
1359
1360
                    // If we insert a model with items -> select by default the first
1361
                    if (aModel.getSize() > 0)
1362
                    {
1363 6649 ppiqueras
                            this.setSelectedIndex(0);
1364 6666 ppiqueras
                            this.selectedItem = this.getSelectedItem();
1365 6573 ppiqueras
//                            model.setCurrentString(this.getSelectedItem().toString());
1366
                    }
1367
                    else
1368
                    {
1369
                            // Else -> set the default index (-1) and current showed string ("")
1370 6666 ppiqueras
                            this.selectedItem = null;
1371 6649 ppiqueras
                            this.setSelectedIndex(-1);
1372 6573 ppiqueras
//                            model.setCurrentString("");
1373
                    }
1374
1375
                    this.configureModel();
1376
            }
1377
            else
1378
            {
1379
                    // If it's an instance of DefaultComboBoxModel:
1380
1381
//                    System.out.println("B");
1382
                    super.setModel(aModel);
1383
            }
1384
     }
1385
1386
    /*
1387
     * (non-Javadoc)
1388
     * @see javax.swing.JComboBox#setSelectedIndex(int)
1389
     */
1390
    public void setSelectedIndex(int anIndex) {
1391
            super.setSelectedIndex(anIndex);
1392 6666 ppiqueras
            this.selectedItem = super.getSelectedItem();
1393 6576 ppiqueras
1394 6649 ppiqueras
//            this.lastSelectedIndex = anIndex;
1395 6576 ppiqueras
1396
            try {
1397
                        document.remove(0, document.getLength());
1398
                        if (getSelectedIndex() > -1)
1399
                                document.insertString(0, getSelectedItem().toString(), null);
1400 6649 ppiqueras
//                        else
1401
//                                this.lastSelectedIndex = -1;
1402 6576 ppiqueras
1403
                } catch (BadLocationException e) {
1404
                        // TODO Auto-generated catch block
1405
                        e.printStackTrace();
1406
                }
1407 6573 ppiqueras
    }
1408
1409
    /*
1410 6638 ppiqueras
     * (non-Javadoc)
1411
     * @see javax.swing.JComboBox#getSelectedIndex()
1412
     */
1413
    public int getSelectedIndex() {
1414
            Object item = this.getSelectedItem();
1415
1416
            if (item == null)
1417
                    return -1;
1418
            else
1419
                    return model.getIndexOf(item);
1420
    }
1421
1422
    /*
1423 6576 ppiqueras
     *  (non-Javadoc)
1424
     * @see javax.swing.JComboBox#setSelectedItem(java.lang.Object)
1425 6573 ppiqueras
     */
1426 6576 ppiqueras
    public void setSelectedItem(Object anObject) {
1427
            super.setSelectedItem(anObject);
1428 6666 ppiqueras
            this.selectedItem = super.getSelectedItem();
1429 6649 ppiqueras
//            this.lastSelectedIndex = model.getIndexOf(anObject);
1430 6576 ppiqueras
//            System.out.println("Posici?n: " + this.lastSelectedIndex);
1431
1432
            //super.setSelectedIndex(this.lastSelectedIndex);
1433
1434
//            try {
1435
//                        document.remove(0, document.getLength());
1436
//                        if (getSelectedIndex() > -1)
1437
//                                document.insertString(0, getSelectedItem().toString(), null);
1438
//                        else
1439
//                                this.lastSelectedIndex = -1;
1440
//
1441
//                } catch (BadLocationException e) {
1442
//                        // TODO Auto-generated catch block
1443
//                        e.printStackTrace();
1444
//                }
1445
    }
1446
1447 6573 ppiqueras
//
1448
    ////// END REDEFINITION OF SOME METHODS OF JCOMBOBOX //////
1449
1450
1451
1452
1453
1454
        ////// METHODS FOR THE BEHAVIOR FLAGS  //////
1455
1456
        /**
1457
         * This method tests the configuration of the flags and returns true or false if its ok or not with the
1458
         *   logical behavior of this component
1459
         *
1460
         * @return boolean True if the configuration of the flags is oks, false if not
1461
         */
1462
        public boolean testFlagsConfigurationOK() {
1463
                return this.model.testFlagsConfigurationOK();
1464
        }
1465
1466 6613 ppiqueras
        public int getStartBehavior() {
1467
                return this.model.getStartBehavior();
1468 6573 ppiqueras
        }
1469
1470 6613 ppiqueras
        public void setStartBehavior(int start_Behavior) {
1471
                this.model.setStartBehavior(start_Behavior);
1472 6573 ppiqueras
1473
                if (!this.model.testFlagsConfigurationOK())
1474
                        JOptionPane.showMessageDialog(this, PluginServices.getText(this, "error_message_JComboBoxSearcheableDynamic"), PluginServices.getText(this, "exportJOP2Title"), JOptionPane.ERROR_MESSAGE);
1475 6638 ppiqueras
                else
1476 6649 ppiqueras
                        updateLastSelectionItem();
1477 6613 ppiqueras
        }
1478 6573 ppiqueras
1479 6613 ppiqueras
        public int getSearchBehavior() {
1480
                return this.model.getSearchBehavior();
1481
        }
1482 6573 ppiqueras
1483 6613 ppiqueras
        public void setSearchBehavior(int search_Behavior) {
1484
                this.model.setSearchBehavior(search_Behavior);
1485 6573 ppiqueras
1486
                if (!this.model.testFlagsConfigurationOK())
1487
                        JOptionPane.showMessageDialog(this, PluginServices.getText(this, "error_message_JComboBoxSearcheableDynamic"), PluginServices.getText(this, "exportJOP2Title"), JOptionPane.ERROR_MESSAGE);
1488 6638 ppiqueras
                else
1489 6649 ppiqueras
                        updateLastSelectionItem();
1490 6573 ppiqueras
        }
1491 6613 ppiqueras
1492 6573 ppiqueras
1493
        /**
1494
         * Gets the flag of the configuration of the keySensitive flag of this component
1495
         * (true -> discriminates capital letters from small letters ,false -> don't discriminates capital letters from small letters)
1496
         *
1497
         * @return boolean The value of the flag
1498
         */
1499
        public boolean isKeySensitive() {
1500
                return this.model.isKeySensitive();
1501
        }
1502
1503
        /**
1504
         * Sets the flag of the configuration of the keySensitive flag of this component
1505
         * (true -> discriminates capital letters from small letters ,false -> don't discriminates capital letters from small letters)
1506
         *
1507
         * @param boolean The value of the flag
1508
         */
1509
        public void setKeySensitive(boolean key_Sensitive) {
1510
                this.model.setKeySensitive(key_Sensitive);
1511
1512
                if (!this.model.testFlagsConfigurationOK())
1513
                        JOptionPane.showMessageDialog(this, PluginServices.getText(this, "error_message_JComboBoxSearcheableDynamic"), PluginServices.getText(this, "exportJOP2Title"), JOptionPane.ERROR_MESSAGE);
1514
        }
1515
1516
        /**
1517
         * Gets the flag of the configuration of the onlyOneColor flag of this component
1518
         * (true -> The text on the textField only will be showed on black color; false -> if the text on the textField doesn't match with any current item of this
1519
         *            component -> the text will be showed on red color)
1520
         *
1521
         * @return boolean The value of the flag
1522
         */
1523
        public boolean isOnlyOneColor() {
1524
                return onlyOneColor;
1525
        }
1526
1527
1528
        /**
1529
         * Sets the flag of the configuration of the onlyOneColor flag of this component
1530
         * (true -> discriminates capital letters from small letters ,false -> don't discriminates capital letters from small letters)
1531
         *
1532
         * @param boolean The value of the flag
1533
         */
1534
        public void setOnlyOneColor(boolean only_One_Color) {
1535
                this.onlyOneColor = only_One_Color;
1536
1537
                if (!this.model.testFlagsConfigurationOK())
1538
                        JOptionPane.showMessageDialog(this, PluginServices.getText(this, "error_message_JComboBoxSearcheableDynamic"), PluginServices.getText(this, "exportJOP2Title"), JOptionPane.ERROR_MESSAGE);
1539
        }
1540
1541
        /**
1542
         * Gets the flag of the configuration of the showAllItems flag of this component
1543
         * (true -> this component shows all items always; false -> this component only shows items that their first characters match with the string written by the user)
1544
         *
1545
         * @return boolean The value of the flag
1546
         */
1547
        public boolean isShowAllItems() {
1548
                return this.model.isShowAllItems();
1549
        }
1550
1551
        /**
1552
         * Sets the flag of the configuration of the showAllItems flag of this component
1553
         * (true -> this component shows all items always; false -> this component only shows items that their first characters match with the string written by the user)
1554
         *
1555
         * @return boolean The value of the flag
1556
         */
1557
        public void setShowAllItems(boolean show_All_Items) {
1558
                this.model.setShowAllItems(show_All_Items);
1559
1560
//                if (this.model.isShowAllItems() == false)
1561
//                        this.setModel(getCopyOfModel());
1562
        }
1563
1564
        ////// END METHODS FOR THE BEHAVIOR FLAGS  //////
1565
1566
1567
        /** REVISAR COMENTARIOS Y C?DIGO
1568
         * Inner class for optimize the seek of items
1569
         *
1570
         * @author Pablo Piqueras Bartolom? (p_queras@hotmail.com)
1571
         *
1572
         */
1573
        private class PlainDocumentSeeker extends PlainDocument{
1574
                private JComboBoxItemsSeekerDynamic comboBox;
1575
1576
                /**
1577
                 * Default Constructor
1578
                 */
1579
                public PlainDocumentSeeker() {
1580
                        super();
1581
                }
1582
1583
                /**
1584
                 * Sets a reference of the combo_Box
1585
                 *
1586
                 * @param combo_Box
1587
                 */
1588
                public void setJComboBoxItemsSeekerDynamicReference(JComboBoxItemsSeekerDynamic combo_Box) {
1589
                        comboBox = combo_Box;
1590
                }
1591
1592
                /* REVISAR
1593
                 *  (non-Javadoc)
1594
                 * @see javax.swing.text.Document#remove(int, int)
1595
                 */
1596
                public void remove(int offs, int len) throws BadLocationException {
1597
                // return immediately when selecting an item
1598
                if (selecting) return;
1599
1600
                if (hitBackspace)
1601
                {
1602
                    // user hit backspace => move the selection backwards
1603
                    // old item keeps being selected
1604
                    if (offs>0)
1605
                    {
1606
                        if (hitBackspaceOnSelection)
1607
                                offs--;
1608
                    }
1609
                    else
1610
                    {
1611
                        // User hit backspace with the cursor positioned on the start => beep
1612 6576 ppiqueras
                            if (useBeep)
1613
                                    comboBox.getToolkit().beep(); // when available use: UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
1614 6573 ppiqueras
                    }
1615
1616
                    highlightCompletedText(offs);
1617
                }
1618
                else
1619
                {
1620
                    super.remove(offs, len);
1621
                }
1622 6666 ppiqueras
//
1623
//                        if (updatePopUp)
1624
//                        {
1625
//                                updatePopUpView();
1626
//                                updatePopUp = false;
1627
//                        }
1628
1629 6573 ppiqueras
            }
1630
1631
                /*REVISAR
1632
                 *  (non-Javadoc)
1633
                 * @see javax.swing.text.Document#insertString(int, java.lang.String, javax.swing.text.AttributeSet)
1634
                 */
1635
            public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
1636
//                    super.insertString(offs, str, a);
1637 6706 ppiqueras
                    System.out.println("INSERTSTRING: " + str);
1638 6685 ppiqueras
//                    model.setCurrentString(str);
1639 6573 ppiqueras
1640 6685 ppiqueras
                    if (model.getParentSize() > 0)
1641
                    {
1642 6573 ppiqueras
                        // Insert the string into the document
1643
1644 6706 ppiqueras
                        // If we aren't in the particular case of show al items at the beginning and is enabled the flag for complete the matched item:
1645 6625 ppiqueras
                        //   this is for not insert two strings to the document of the editor of this component
1646 6638 ppiqueras
                        if (!((completeMatchedItem) && (model.isStartViewFlag())))
1647 6685 ppiqueras
        //                        if (!completeMatchedItem)
1648 6625 ppiqueras
                                super.insertString(offs, str, a);
1649 6685 ppiqueras
1650
1651 6573 ppiqueras
                        // Lookup and select a matching item
1652
                        Object item = lookupItem(getText(0, getLength()));
1653
1654
                        if (item != null)
1655
                        {
1656 6706 ppiqueras
                                System.out.println("ITEM NOT NULL");
1657
                                if (completeMatchedItem)
1658
                                        setSelectedItem(item);
1659 6666 ppiqueras
1660 6685 ppiqueras
1661
        //                            model.setCurrentString(getSelectedItem().toString());
1662
        //                            lastSelectedIndex = getSelectedIndex();
1663 6573 ppiqueras
                        }
1664
                        else
1665
                        {
1666 6706 ppiqueras
                                System.out.println("ITEM NULL");
1667 6573 ppiqueras
                            // Keep old item selected if there is no match
1668
                            item = comboBox.getSelectedItem();
1669 6706 ppiqueras
                            System.out.println("ITEM QUE SELECCIONA CUANDO NULL: ->" + item.toString() + "<-");
1670 6573 ppiqueras
1671
                            // Imitate no insert (later on offs will be incremented by str.length(): selection won't move forward)
1672
                            offs = offs-str.length();
1673
1674
                            // Provide feedback to the user that his input has been received but can not be accepted
1675 6576 ppiqueras
                            if (useBeep)
1676
                                    comboBox.getToolkit().beep(); // when available use: UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
1677 6573 ppiqueras
                        }
1678
1679
                        // Set the complete item value matched
1680
                        if (completeMatchedItem)
1681
                                setText(item.toString());
1682
1683
                        // Select the completed part
1684
                        highlightCompletedText(offs+str.length());
1685 6677 ppiqueras
1686
                        if (textKeyPressed)
1687
                        {
1688 6706 ppiqueras
//                                updatePopUpView();
1689 6677 ppiqueras
1690
                                textKeyPressed = false;
1691
                        }
1692 6685 ppiqueras
                    }
1693 6573 ppiqueras
            }
1694
1695
            /** ?Sobra?
1696
             * This method sets the string value of the item to the PlainDocument removing the previous value of the PlainDocument
1697
             *
1698
             * @param text The string value of the item
1699
             */
1700
            private void setText(String text) {
1701
                try
1702
                {
1703
                    // remove all text and insert the completed string
1704
                    super.remove(0, super.getLength());
1705
                    super.insertString(0, text, null);
1706
                }
1707
                catch (BadLocationException e)
1708
                {
1709
                    throw new RuntimeException(e.toString());
1710
                }
1711
            }
1712
1713 6677 ppiqueras
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730 6573 ppiqueras
            /**
1731
             *
1732
             */
1733
            private Object lookupItem(String pattern) {
1734 6706 ppiqueras
                    System.out.println("LOOKUP -> patr?n ->" + pattern + "<-");
1735 6573 ppiqueras
                    // Reset the color to the default
1736 6613 ppiqueras
//                    editor.getEditorComponent().setForeground(Color.BLACK);
1737 6573 ppiqueras
1738 6613 ppiqueras
                // If no item starts with the pattern => return null and set the text written on red color if it's allowed
1739
1740 6573 ppiqueras
                Object selectedItem = model.getSelectedItem();
1741
1742 6649 ppiqueras
//                if (selectedItem.toString().length() >= pattern.length())
1743
//                {
1744
                        // only search for a different item if the currently selected does not match
1745
                        if ((selectedItem != null) && (startsWithIgnoreCase(selectedItem.toString(), pattern)))
1746
                        {
1747
                                editor.getEditorComponent().setForeground(Color.BLACK);
1748
                            return selectedItem;
1749
                        }
1750
                        else
1751
                        {
1752
                            // iterate over all items
1753
                            for (int i=0, n=model.getSize(); i < n; i++)
1754
                            {
1755
                                Object currentItem = model.getElementAt(i);
1756
1757
                                // current item starts with the pattern?
1758
                                if ((currentItem != null) && (startsWithIgnoreCase(currentItem.toString(), pattern)))
1759
                                {
1760
                                        editor.getEditorComponent().setForeground(Color.BLACK);
1761
                                    return currentItem;
1762
                                }
1763
                            }
1764
                        }
1765 6573 ppiqueras
1766
                return null;
1767
            }
1768
1769
1770
            /**
1771
             * Checks if the starts of two strings agrees
1772
             */
1773
            private boolean startsWithIgnoreCase(String str1, String str2) {
1774
                    if (comboBox.isKeySensitive())
1775
                            return str1.startsWith(str2);
1776
                    else
1777
                            return str1.toUpperCase().startsWith(str2.toUpperCase());
1778
            }
1779
        }
1780
}