PageRenderTime 106ms CodeModel.GetById 40ms app.highlight 41ms RepoModel.GetById 20ms app.codeStats 0ms

/src/mpv5/ui/beans/MPCombobox.java

http://mp-rechnungs-und-kundenverwaltung.googlecode.com/
Java | 460 lines | 264 code | 55 blank | 141 comment | 38 complexity | a3e6106fd36aa900d95a767d3e31f3a7 MD5 | raw file
  1/*
  2 * To change this template, choose Tools | Templates
  3 * and open the template in the editor.
  4 */
  5
  6/*
  7 * LabeledTextField.java
  8 *
  9 * Created on 20.11.2008, 19:26:39
 10 */
 11package mpv5.ui.beans;
 12
 13import java.awt.Font;
 14import java.awt.event.ActionEvent;
 15import java.awt.event.ActionListener;
 16import java.awt.event.KeyEvent;
 17import java.awt.event.KeyListener;
 18import java.awt.event.MouseEvent;
 19import java.awt.event.MouseListener;
 20import java.util.Arrays;
 21import java.util.List;
 22import java.util.Vector;
 23import javax.swing.ComboBoxEditor;
 24import javax.swing.DefaultComboBoxModel;
 25import javax.swing.JComboBox;
 26import javax.swing.JTable;
 27import mpv5.db.common.ConnectionTypeHandler;
 28import mpv5.db.common.Context;
 29import mpv5.db.common.DatabaseObject;
 30import mpv5.db.common.DatabaseSearch;
 31import mpv5.db.common.NodataFoundException;
 32import mpv5.globals.Messages;
 33import mpv5.handler.MPEnum;
 34import mpv5.logging.Log;
 35import mpv5.ui.panels.DataPanel;
 36import mpv5.utils.models.*;
 37import mpv5.utils.renderer.ComboBoxRendererForTooltip;
 38
 39/**
 40 *
 41 *  
 42 */
 43public class MPCombobox extends javax.swing.JPanel {
 44
 45    private static final long serialVersionUID = 1L;
 46    public boolean SEARCH_ON_ENTER = false;
 47    private Context context;
 48    private int sortmode = 0;
 49    private JTable table;
 50    private boolean instantiated;
 51    private DataPanel receiver;
 52    private String prevSearch = "";
 53
 54    /**
 55     * If this combobox is within a table cell, set the table here
 56     * @param table
 57     */
 58    public void setTable(JTable table) {
 59        this.table = table;
 60    }
 61
 62    /** Creates new form LabeledTextField */
 63    public MPCombobox() {
 64        initComponents();
 65        jComboBox1.getEditor().getEditorComponent().addKeyListener(new KeyListener() {
 66
 67            @Override
 68            public void keyTyped(KeyEvent e) {
 69            }
 70
 71            @Override
 72            public void keyPressed(KeyEvent e) {
 73
 74                if (SEARCH_ON_ENTER && (e.getKeyCode() == KeyEvent.VK_ENTER) && getContext() != null) {
 75                    search();
 76                }
 77//                if (table != null) {
 78                jComboBox1.showPopup();
 79//                }
 80//                if (table != null) {
 81//                    JComboBox combobox = getComboBox();
 82//                    if (!combobox.isPopupVisible()) {
 83//                        combobox.hidePopup();
 84//                    } else {
 85//                        combobox.showPopup();
 86//                    }
 87//                }
 88            }
 89
 90            @Override
 91            public void keyReleased(KeyEvent e) {
 92            }
 93        });
 94
 95
 96        jComboBox1.getComponent(0).addMouseListener(new MouseListener() {
 97
 98            @Override
 99            public void mouseClicked(MouseEvent e) {
100            }
101
102            @Override
103            public void mousePressed(MouseEvent e) {
104                if (SEARCH_ON_ENTER && !instantiated) {
105                    if (table == null) {
106                        jComboBox1.setModel(new DefaultComboBoxModel(new String[]{""}));
107                    }
108                    search();
109//                    if (table != null) {
110                    jComboBox1.showPopup();
111//                    }
112                }
113            }
114
115            @Override
116            public void mouseReleased(MouseEvent e) {
117            }
118
119            @Override
120            public void mouseEntered(MouseEvent e) {
121            }
122
123            @Override
124            public void mouseExited(MouseEvent e) {
125            }
126        });
127
128
129        jComboBox1.setRenderer(new ComboBoxRendererForTooltip());
130//        jComboBox1.setToolTipText(Messages.SEARCHABLE.toString());
131        setModel();
132    }
133
134    /**
135     * Creates a new ComboBox with {@link MPCombobox#setSearchOnEnterEnabled(boolean)} enabled and the given search {@link Context}
136     * 
137     * @param c
138     * @param table
139     */
140    public MPCombobox(Context c, JTable table) {
141        this();
142        setSearchEnabled(true);
143        setContext(c);
144        setTable(table);
145        getComboBox().putClientProperty("JComboBox.isTableCellEditor", table != null);
146    }
147
148    public JComboBox getComboBox() {
149        return jComboBox1;
150    }
151
152    /**
153     * Triggers the search functionality
154     */
155    public void search() {
156        search(false);
157    }
158
159    /**
160     * Triggers the search functionality
161     * @param hidePopup
162     */
163    public synchronized void search(final boolean hidePopup) {
164        if (SEARCH_ON_ENTER) {
165            instantiated = true;
166            Runnable runnable = new Runnable() {
167
168                @Override
169                public void run() {
170                    ComboBoxEditor cbField = jComboBox1.getEditor();
171                    Object value = cbField.getItem();
172                    jComboBox1.setSelectedItem(new MPComboBoxModelItem(-1, value.toString()));
173                    if (prevSearch == null) {
174                        prevSearch = String.valueOf(value);
175                    } else {
176                        value = String.valueOf(value).equals(prevSearch) ? "" : String.valueOf(value);
177                        prevSearch = null;
178                    }
179                    Object[][] data = null;
180                    if (getComboBox().isEditable()) {
181                        if (getContext().equals(Context.getProduct())) {
182                            data = new DatabaseSearch(getContext(), 200).getValuesFor2("ids, " + ConnectionTypeHandler.concat("cname","' '", ConnectionTypeHandler.getToChar("externalnetvalue")), String.valueOf(value), null, true, true);
183                        } else if (((getContext().equals(Context.getCustomer()) || getContext().equals(Context.getManufacturer()) || getContext().equals(Context.getSupplier())) && mpv5.db.objects.User.getCurrentUser().getProperties().getProperty("org.openyabs.uiproperty", "companiesovernames")) || getContext().isCompany()==true) {
184                            data = new DatabaseSearch(getContext(), 200).getValuesFor("ids, company", "company", jComboBox1.getSelectedItem().toString(), true);
185                        } else {
186                            data = new DatabaseSearch(getContext(), 200).getValuesFor("ids, cname", "cname", jComboBox1.getSelectedItem().toString(), true);
187                        }
188                    } else {
189                        data = new DatabaseSearch(getContext(), 200).getValuesFor("ids, cname", "cname", "", true);
190                    }
191
192                    jComboBox1.setModel(MPComboBoxModelItem.toModel(MPComboBoxModelItem.toItems(data, true, true)));
193                    if (data.length > 1) {
194                        if (table != null) {
195                            table.editCellAt(table.getSelectedRow(), 4);
196                        }
197                        if (!hidePopup) {
198                            jComboBox1.showPopup();
199                        }
200                    }
201                }
202            };
203            if (getContext() != null) {
204                new Thread(runnable).start();
205            }
206        }
207    }
208
209    /**
210     *
211     * @return The model
212     */
213    public MPComboboxModel getModel() {
214        return (MPComboboxModel) jComboBox1.getModel();
215    }
216
217    /**
218     *
219     * @param values
220     */
221    public void setModel(MPEnum[] values) {
222        jComboBox1.setModel(MPComboBoxModelItem.toModel(values));
223    }
224
225    /**
226     * 
227     * @param values
228     * @param compareMode
229     */
230    public void setModel(MPEnum[] values, int compareMode) {
231        jComboBox1.setModel(MPComboBoxModelItem.toModel(values, compareMode, new java.util.Vector<Integer>()));
232    }
233
234    /**
235     * Uses enum.name() as ID, and enum.toString() as value.
236     * @param values
237     */
238    public void setModel(Enum[] values) {
239        String[][] val = new String[values.length][2];
240        for (int i = 0; i < values.length; i++) {
241            Enum enum1 = values[i];
242            val[i][0] = enum1.name();
243            val[i][1] = enum1.toString();
244        }
245        setModel(val);
246    }
247
248    /**
249     * Delegates to setModel(MPComboBoxModelItem.toModel(data));
250     * {id (hidden), value (shown in the list)}
251     * @param data
252     */
253    public void setModel(Object[][] data) {
254        jComboBox1.setModel(MPComboBoxModelItem.toModel(data));
255    }
256
257    /**
258     *
259     * @return An {@link MPComboBoxModelItem} or null if nothing is selected
260     */
261    public MPComboBoxModelItem getSelectedItem() {
262        if (jComboBox1.getSelectedItem() instanceof MPComboBoxModelItem) {
263            return (MPComboBoxModelItem) jComboBox1.getSelectedItem();
264        } else {
265            return null;
266        }
267    }
268
269    /**
270     * The textual representation of the seleceted item
271     * @return
272     */
273    public String getSelectedValue() {
274        return String.valueOf(jComboBox1.getSelectedItem());
275    }
276
277    /**
278     * Set the model. Should contain only {@link MPComboBoxModelItem}s
279     * @param model
280     */
281    public void setModel(MPComboboxModel model) {
282        jComboBox1.setModel(model);
283    }
284
285    /**
286     * Convenience Method to set a single {@link DatabaseObject} as the model of the combobox.<br/>
287     * Will set the DO as the selected item after adding.
288     * @param obj
289     */
290    public void setModel(DatabaseObject obj) {
291        setModel(new Vector<DatabaseObject>(Arrays.asList(new DatabaseObject[]{
292                    obj
293                })));
294        setSelectedIndex(0);
295    }
296
297    /**
298     * Convenience Method to set a {@link List} of {@link DatabaseObject}s as the model of the combobox.<br/>
299     * @param vector
300     */
301    public void setModel(List<DatabaseObject> vector) {
302        setModel(new MPComboboxModel(MPComboBoxModelItem.toItems(vector)));
303    }
304
305    /**
306     * Delegates to getComboBox().setSelectedIndex(itemID);
307     * @param itemID
308     */
309    public void setSelectedIndex(int itemID) {
310        if (itemID >= 0 && itemID < getComboBox().getItemCount()) {
311            getComboBox().setSelectedIndex(itemID);
312        }
313    }
314
315    /**
316     * Sets the item with the given value as selected item
317     * @param valueOfItem
318     */
319    public void setSelectedItem(String valueOfItem) {
320        jComboBox1.setSelectedIndex(MPComboBoxModelItem.getItemIDfromValue(valueOfItem, jComboBox1.getModel()));
321    }
322
323    /**
324     * Sets the item with the given ID as selected item
325     * @param ID
326     */
327    public void setSelectedItem(Object ID) {
328        jComboBox1.setSelectedIndex(MPComboBoxModelItem.getItemID(ID, jComboBox1.getModel()));
329    }
330
331    /**
332     * If set to true, hitting "Enter" on the text field will trigger a search for the entered value and popup the results if any.
333     * <br/>{@link LabeledCombobox#setContext(Context)} must be called before this can work.
334     * @param enabled
335     */
336    public void setSearchEnabled(boolean enabled) {
337        SEARCH_ON_ENTER = enabled;
338        jComboBox1.setEditable(enabled);
339        if (enabled) {
340            jComboBox1.setToolTipText(Messages.SEARCHABLE.toString());
341        }
342    }
343
344    /**
345     * Set the context for database queries
346     * @param c
347     */
348    public void setContext(Context c) {
349        this.context = c;
350    }
351
352    /** This method is called from within the constructor to
353     * initialize the form.
354     * WARNING: Do NOT modify this code. The content of this method is
355     * always regenerated by the Form Editor.
356     */
357    @SuppressWarnings("unchecked")
358    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
359    private void initComponents() {
360
361        jComboBox1 = new javax.swing.JComboBox();
362
363        setBorder(null);
364        setOpaque(false);
365        setLayout(new java.awt.BorderLayout());
366
367        jComboBox1.setAutoscrolls(true);
368        jComboBox1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(138, 138, 138), 1, true));
369        jComboBox1.setMinimumSize(new java.awt.Dimension(33, 18));
370        jComboBox1.setPreferredSize(new java.awt.Dimension(100, 20));
371        jComboBox1.addMouseListener(new java.awt.event.MouseAdapter() {
372            public void mouseClicked(java.awt.event.MouseEvent evt) {
373                jComboBox1MouseClicked(evt);
374            }
375        });
376        add(jComboBox1, java.awt.BorderLayout.CENTER);
377    }// </editor-fold>//GEN-END:initComponents
378
379    private void jComboBox1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jComboBox1MouseClicked
380        search();
381    }//GEN-LAST:event_jComboBox1MouseClicked
382    // Variables declaration - do not modify//GEN-BEGIN:variables
383    private javax.swing.JComboBox jComboBox1;
384    // End of variables declaration//GEN-END:variables
385
386    /**
387     * @return the _text
388     */
389    public MPComboBoxModelItem getValue() {
390        return (MPComboBoxModelItem) jComboBox1.getSelectedItem();
391    }
392
393    @Deprecated
394    public void set_LabelFont(Font font) {
395    }
396
397    @Override
398    public void setEnabled(boolean enabled) {
399        jComboBox1.setEnabled(enabled);
400    }
401
402    /**
403    Sets the selected item in the combo box display area to the object in the argument. If anObject is in the list, the display area shows anObject selected.
404    If anObject is not in the list and the combo box is uneditable, it will not change the current selection. For editable combo boxes, the selection will change to anObject.
405    If this constitutes a change in the selected item, ItemListeners added to the combo box will be notified with one or two ItemEvents. If there is a current selected item, an ItemEvent will be fired and the state change will be ItemEvent.DESELECTED. If anObject is in the list and is not currently selected then an ItemEvent will be fired and the state change will be ItemEvent.SELECTED.
406    ActionListeners added to the combo box will be notified with an ActionEvent when this method is called.
407    Parameters:
408    anObject - the list object to select; use null to clear the selection
409     * @param text
410     */
411    public void setValue(String text) {
412        jComboBox1.setSelectedItem(text);
413        jComboBox1.setPopupVisible(false);
414    }
415
416    /**
417     * Sets an empty model
418     */
419    public void setModel() {
420        setModel(new Vector<DatabaseObject>());
421    }
422
423    /**
424     * Trigger a search on the combo box
425     */
426    public void triggerSearch() {
427        search(true);
428    }
429
430    public void setReceiver(final DataPanel panel) {
431        this.receiver = panel;
432        jComboBox1.addActionListener(new ActionListener() {
433
434            public void actionPerformed(ActionEvent e) {
435                try {
436                    if (getSelectedItem() != null) {
437                        panel.setDataOwner(DatabaseObject.getObject(getContext(), Integer.valueOf(getSelectedItem().getId())), true);
438                    }
439                } catch (NodataFoundException ex) {
440                    Log.Debug(this, ex.getMessage());
441                }
442            }
443        });
444    }
445
446    /**
447     *
448     * @return The id obj of the selected entry or NULL if nothing is selected
449     */
450    public Object getSelectedItemId() {
451        return getSelectedItem().getIdObject();
452    }
453
454    /**
455     * @return the context
456     */
457    public Context getContext() {
458        return context;
459    }
460}