PageRenderTime 145ms CodeModel.GetById 60ms app.highlight 42ms RepoModel.GetById 39ms app.codeStats 0ms

/src/mpv5/ui/beans/LightMPComboBox.java

http://mp-rechnungs-und-kundenverwaltung.googlecode.com/
Java | 343 lines | 190 code | 39 blank | 114 comment | 17 complexity | 34e055fb70e68fec5859b88e6f7dc996 MD5 | raw file
  1/*
  2 *  This file is part of YaBS.
  3 *
  4 *      YaBS is free software: you can redistribute it and/or modify
  5 *      it under the terms of the GNU General Public License as published by
  6 *      the Free Software Foundation, either version 3 of the License, or
  7 *      (at your option) any later version.
  8 *
  9 *      YaBS is distributed in the hope that it will be useful,
 10 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 11 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 12 *      GNU General Public License for more details.
 13 *
 14 *      You should have received a copy of the GNU General Public License
 15 *      along with YaBS.  If not, see <http://www.gnu.org/licenses/>.
 16 */
 17package mpv5.ui.beans;
 18
 19import java.awt.Font;
 20import java.awt.event.ActionEvent;
 21import java.awt.event.ActionListener;
 22import java.awt.event.KeyEvent;
 23import java.awt.event.KeyListener;
 24import java.awt.event.MouseEvent;
 25import java.awt.event.MouseListener;
 26import java.util.Arrays;
 27import java.util.List;
 28import java.util.Vector;
 29import javax.swing.ComboBoxEditor;
 30import javax.swing.DefaultComboBoxModel;
 31import javax.swing.JComboBox;
 32import javax.swing.JTable;
 33import javax.swing.SwingUtilities;
 34import mpv5.db.common.Context;
 35import mpv5.db.common.DatabaseObject;
 36import mpv5.db.common.DatabaseSearch;
 37import mpv5.handler.MPEnum;
 38import mpv5.logging.Log;
 39import mpv5.ui.frames.MPView;
 40import mpv5.utils.models.MPComboBoxModelItem;
 41import mpv5.utils.models.MPComboboxModel;
 42import mpv5.utils.renderer.ComboBoxRendererForTooltip;
 43
 44/**
 45 *
 46 */
 47public class LightMPComboBox extends JComboBox {
 48
 49    private static final long serialVersionUID = 1L;
 50    public boolean SEARCH_ON_ENTER = false;
 51    public static final String VALUE_SEARCHFIELDS = ".lightmpcomboboxsearchvalue";
 52    private Context context;
 53    private int sortmode = 0;
 54    private JTable table;
 55
 56    /**
 57     * If this combobox is within a table cell, set the table here
 58     * @param table
 59     */
 60    public void setTable(JTable table) {
 61        this.table = table;
 62    }
 63    private boolean initiated;
 64
 65    /** Creates new form LabeledTextField */
 66    public LightMPComboBox() {
 67        super();
 68        getEditor().getEditorComponent().addKeyListener(new KeyListener() {
 69
 70            @Override
 71            public void keyTyped(KeyEvent e) {
 72            }
 73
 74            @Override
 75            public void keyPressed(KeyEvent e) {
 76                if (SEARCH_ON_ENTER && (e.getKeyCode() == KeyEvent.VK_F2) && context != null) {
 77                    search();
 78                }
 79//                  if (SEARCH_ON_ENTER && (e.getKeyCode() == KeyEvent.VK_DOWN) && context != null) {
 80//                    showPopup();
 81//                }
 82            }
 83
 84            @Override
 85            public void keyReleased(KeyEvent e) {
 86            }
 87        });
 88
 89
 90        getComponent(0).addMouseListener(new MouseListener() {
 91
 92            @Override
 93            public void mouseClicked(MouseEvent e) {
 94            }
 95
 96            @Override
 97            public void mousePressed(MouseEvent e) {
 98                if (SEARCH_ON_ENTER && !initiated) {
 99                    if (table == null) {
100                        setModel(new DefaultComboBoxModel(new String[]{""}));
101                    }
102                    search();
103//                    if (table != null) {
104//                        showPopup();
105////                    }
106                }
107            }
108
109            @Override
110            public void mouseReleased(MouseEvent e) {
111            }
112
113            @Override
114            public void mouseEntered(MouseEvent e) {
115            }
116
117            @Override
118            public void mouseExited(MouseEvent e) {
119            }
120        });
121
122        setRenderer(new ComboBoxRendererForTooltip());
123        setModel();
124    }
125
126    /**
127     * Creates a new ComboBox with {@link MPCombobox#setSearchOnEnterEnabled(boolean)} enabled and the given search {@link Context}
128     *
129     * @param c
130     * @param table
131     */
132    public LightMPComboBox(Context c, JTable table) {
133        this();
134        setSearchOnEnterEnabled(true);
135        setContext(c);
136        setTable(table);
137        putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
138        addActionListener(new ActionListener() {
139
140            @Override
141            public void actionPerformed(ActionEvent e) {
142                for (int i = 0; i < receiver.size(); i++) {
143                    MPCBSelectionChangeReceiver mPCBSelectionChangeReceiver = receiver.get(i);
144                    mPCBSelectionChangeReceiver.changeSelection((MPComboBoxModelItem) getItemAt(getSelectedIndex()), context);
145                }
146            }
147        });
148    }
149
150    public JComboBox getComboBox() {
151        return this;
152    }
153
154    /**
155     * Triggers the search functionality
156     */
157    public void search() {
158        initiated = true;
159        Runnable runnable = new Runnable() {
160
161            @Override
162            public void run() {
163                ComboBoxEditor cbField = getEditor();
164                Object value = cbField.getItem();
165                if (value == null) {
166                    value = "";
167                }
168                String params = "ids, cname";
169                String vars = null;
170                if (mpv5.db.objects.User.getCurrentUser().getProperties().hasProperty(context + VALUE_SEARCHFIELDS)) {
171                    params = "ids";
172                    vars = mpv5.db.objects.User.getCurrentUser().getProperties().getProperty(context + VALUE_SEARCHFIELDS);
173                    String[] vaars = vars.split("_\\$");
174
175                    for (int i = 0; i < vaars.length; i++) {
176                        try {
177                            if (vaars[i] != null && vaars[i].contains("$_")) {
178                                params += "," + vaars[i].split("\\$_")[0].replace(",", "").replace("'", "`");
179                            }
180                        } catch (Exception e) {
181                            Log.Debug(e);
182                        }
183                    }
184                }
185
186                Object[][] data = new DatabaseSearch(context, 200).getValuesFor2(params, String.valueOf(value), null, true, true);
187                setModel(MPComboBoxModelItem.toModel(MPComboBoxModelItem.toItems(data, true, MPComboBoxModelItem.COMPARE_BY_VALUE, vars)));
188                try {
189                    table.editCellAt(table.getSelectedRow(), 4);
190                } catch (Exception e) {
191                }
192//                   showPopup();//avoid flickering
193            }
194        };
195        new Thread(runnable).start();
196    }
197
198    /**
199     *
200     * @return The model
201     */
202    public MPComboboxModel getMPModel() {
203        return (MPComboboxModel) getModel();
204    }
205
206    /**
207     *
208     * @param values
209     */
210    public void setModel(MPEnum[] values) {
211        setModel(MPComboBoxModelItem.toModel(values));
212    }
213
214    /**
215     *
216     * @param values
217     * @param compareMode
218     */
219    public void setModel(MPEnum[] values, int compareMode) {
220        setModel(MPComboBoxModelItem.toModel(values, compareMode, new java.util.Vector<Integer>()));
221    }
222
223    /**
224     * Delegates to setModel(MPComboBoxModelItem.toModel(data));
225     * {id (hidden), value (shown in the list)}
226     * @param data
227     */
228    public void setModel(Object[][] data) {
229        setModel(MPComboBoxModelItem.toModel(data));
230    }
231
232    /**
233     * Set the model. Should contain only {@link MPComboBoxModelItem}s
234     * @param model
235     */
236    public void setModel(MPComboboxModel model) {
237        super.setModel(model);
238    }
239
240    /**
241     * Convenience Method to set a single {@link DatabaseObject} as the model of the combobox.<br/>
242     * Will set the DO as the selected item after adding.
243     * @param obj
244     */
245    public void setModel(DatabaseObject obj) {
246        setModel(new Vector<DatabaseObject>(Arrays.asList(new DatabaseObject[]{
247                    obj
248                })));
249        setSelectedIndex(0);
250    }
251
252    /**
253     * Convenience Method to set a {@link List} of {@link DatabaseObject}s as the model of the combobox.<br/>
254     * @param vector
255     */
256    public void setModel(List<DatabaseObject> vector) {
257        setModel(new MPComboboxModel(MPComboBoxModelItem.toItems(vector)));
258    }
259
260    /**
261     * Sets the item with the given value as selected item
262     * @param valueOfItem
263     */
264    public void setSelectedItem(String valueOfItem) {
265        setSelectedIndex(MPComboBoxModelItem.getItemIDfromValue(valueOfItem, getModel()));
266    }
267
268    @Override
269    public void setSelectedIndex(int index) {
270        super.setSelectedIndex(index);
271//        for (int i = 0; i < receiver.size(); i++) {
272//            MPCBSelectionChangeReceiver mPCBSelectionChangeReceiver = receiver.get(i);
273//            mPCBSelectionChangeReceiver.changeSelection((MPComboBoxModelItem) getItemAt(index), context);
274//        }
275    }
276    List<MPCBSelectionChangeReceiver> receiver = new Vector<MPCBSelectionChangeReceiver>();
277
278    /**
279     *
280     * @param rec
281     */
282    public void addSelectionChangeReceiver(MPCBSelectionChangeReceiver rec) {
283        receiver.add(rec);
284    }
285
286//    /**
287//     * Sets the item with the given ID as selected item
288//     * @param ID
289//     */
290//    public void setSelectedItem(Object ID) {
291//            setSelectedIndex(MPComboBoxModelItem.getItemID(ID,getModel()));
292//    }
293    /**
294     * If set to true, hitting "Enter" on the text field will trigger a search for the entered value and popup the results if any.
295     * <br/>{@link LabeledCombobox#setContext(Context)} must be called before this can work.
296     * @param enabled
297     */
298    public void setSearchOnEnterEnabled(boolean enabled) {
299        SEARCH_ON_ENTER = enabled;
300        setEditable(true);
301    }
302
303    /**
304     * Set the context for database queries
305     * @param c
306     */
307    public void setContext(Context c) {
308        this.context = c;
309    }
310
311    /**
312     * @return the _text
313     */
314    public MPComboBoxModelItem getValue() {
315        return (MPComboBoxModelItem) getSelectedItem();
316    }
317
318    @Override
319    public void setEnabled(boolean enabled) {
320        setEnabled(enabled);
321    }
322
323    /**
324    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.
325    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.
326    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.
327    ActionListeners added to the combo box will be notified with an ActionEvent when this method is called.
328    Parameters:
329    anObject - the list object to select; use null to clear the selection
330     * @param text
331     */
332    public void setValue(String text) {
333        setSelectedItem(text);
334        setPopupVisible(false);
335    }
336
337    /**
338     * Sets an empty model
339     */
340    public void setModel() {
341        setModel(new Vector<DatabaseObject>());
342    }
343}