001    package de.mospace.swing.text;
002    
003    /* de.mospace.swing library
004    * Copyright (C) 2005 Moritz Ringler
005    * $Id: HistoryTextField.java 12 2007-07-27 09:48:53Z ringler $
006    *
007    * This program is free software; you can redistribute it and/or
008    * modify it under the terms of the GNU General Public License
009    * as published by the Free Software Foundation; either version 2
010    * of the License, or (at your option) any later version.
011    *
012    * This program is distributed in the hope that it will be useful,
013    * but WITHOUT ANY WARRANTY; without even the implied warranty of
014    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
015    * GNU General Public License for more details.
016    *
017    * You should have received a copy of the GNU General Public License
018    * along with this program; if not, write to the Free Software
019    * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
020    */
021    
022    import java.awt.event.ActionEvent;
023    import java.awt.event.ActionListener;
024    import java.util.prefs.Preferences;
025    import javax.swing.DefaultComboBoxModel;
026    import javax.swing.JComboBox;
027    
028    /** A text field that remembers the last values entered. The GUI representation
029    * is actually a JComboBox that can be retrieved with the {@link #getComboBox
030    * getJComboBox} method.
031    * @author Moritz Ringler
032    * @version $Revision: 12 $ ($Date: 2007-07-27 11:48:53 +0200 (Fr, 27 Jul 2007) $)
033    **/
034    public class HistoryTextField {
035        private final static int MINIMUM_LENGTH = 5;
036        private JComboBox jcb;
037        private int length = MINIMUM_LENGTH;
038        private final Preferences loadedFrom;
039        private final int loadId;
040        private ActionListener autoSaver = null;
041        private boolean autosave = false;
042    
043        /** Constructs a HistoryTextField with the specified id
044        * and initializes it with at most <code>len</code>
045        * previously saved values.
046        * @param prefNode the preference node that values will be loaded from
047        * @param id an integer identifying the history text field whose values
048        * to load
049        * @param len the maximum number of values to load from the preferences,
050        * if it is {0 | negative} then {all | no} saved values will be loaded
051        */
052        public HistoryTextField(Preferences prefNode, int id, int len) {
053            loadedFrom = prefNode;
054            loadId = id;
055            load(prefNode, id, len);
056            jcb.setEditable(true);
057        }
058    
059        /** Constructs a HistoryTextField with the specified id
060        * and initializes it with all previously saved values.
061        * @param prefNode the preference node that values will be loaded from
062        * @param id an integer identifying this history text field whose values
063        * to load
064        */
065        public HistoryTextField(Preferences prefNode, int id)
066        {
067            this(prefNode, id, 0);
068        }
069    
070    
071        private void load(Preferences prefNode, int id, int llen){
072            String hist = prefNode.get("HistoryTextField"+id,"\n\n\n\n");
073            String[] loadedItems = hist.split("\n",-1);
074            int len = llen;
075            int hlen = loadedItems.length;
076            if (len == 0){
077                len = hlen;
078            }
079            if (len < MINIMUM_LENGTH) {
080                len = MINIMUM_LENGTH;
081            }
082            DefaultComboBoxModel mod = new DefaultComboBoxModel(new String[len]);
083            int i=0;
084            int xlen = Math.min(len,hlen);
085            for(; i<xlen; i++){
086                mod.insertElementAt(loadedItems[i],i);
087            }
088            for(; i<len;i++){
089                mod.insertElementAt(" ",i);
090            }
091            jcb = new JComboBox(mod);
092            jcb.setEditable(true);
093            jcb.setSelectedItem(loadedItems[0]);
094        }
095    
096        /** Saves this text fields history to the specified preference node
097        * and id.
098        * @param prefNode the preference node that values will be written to
099        * @param id an integer identifying this history text field
100        */
101        public void save(Preferences prefNode, int id){
102            StringBuffer hist = new StringBuffer(length*20);
103            for(int i=0; i<length-1;i++){
104                hist.append(jcb.getItemAt(i).toString()).append("\n");
105            }
106            if (length>0){
107                hist.append(jcb.getItemAt(length-1));
108            }
109            prefNode.put("HistoryTextField"+id,hist.toString());
110        }
111    
112        /** Adds a new string to this text field's history.
113        * @param str the string to add
114        */
115        public void addToHistory(String str){
116            ((DefaultComboBoxModel) jcb.getModel()).insertElementAt(str,0);
117        }
118    
119        /** Adds the item that is currently edited to this text field's history.
120        */
121        public void addCurrentItem(){
122            addToHistory(jcb.getSelectedItem().toString());
123        }
124    
125        /** Clears this text field's history. */
126        public void clearHistory(){
127            ((DefaultComboBoxModel) jcb.getModel()).removeAllElements();
128        }
129    
130        /** Gets the single JComboBox object that serves as a GUI representation of
131        * this history text field.
132        * @return the combo box for this history text field
133        * @see #setAutoSave
134        */
135        public JComboBox getComboBox(){
136            return jcb;
137        }
138    
139        /** Sets whether items newly added to this text field's combo box will
140        * automatically be added to the history and saved under the preference node
141        * and id that this text field has been loaded from.
142        * @param b whether new items should be saved automatically
143        * @see #isAutoSave
144        */
145        public synchronized void setAutoSave(boolean b){
146            if(b && !autosave){
147                if(autoSaver == null){
148                    autoSaver = new ActionListener(){
149                        public void actionPerformed(ActionEvent e){
150                            JComboBox cb = (JComboBox) e.getSource();
151    
152                            /* only add new items to the history */
153                            if (cb.getSelectedIndex() != -1){
154                                return;
155                            }
156                            Object item = cb.getSelectedItem();
157                            /* only add non-null items */
158                            if(item == null){
159                                return;
160                            }
161                            addToHistory(item.toString());
162                            save(loadedFrom,loadId);
163                        }
164                    };
165                }
166                jcb.addActionListener(autoSaver);
167                autosave = true;
168            } else if (!b && autosave){
169                jcb.removeActionListener(autoSaver);
170                autosave = false;
171            }
172        }
173    
174        /** Returns whether items newly added to this text field's combo box will
175        * automatically be added to the history and saved under the preference node
176        * and id that this text field has been loaded from.
177        * @return whether new items are saved automatically
178        * @see #setAutoSave
179        */
180        public synchronized boolean isAutoSave(){
181            return autosave;
182        }
183    
184        /** Returns the items in this text field's history as a newly allocated
185        * String array.
186        * @return this text field's history
187        */
188        public String[] getStringArray(){
189            String[] history = new String[length];
190            for(int i=0; i<length; i++){
191                history[i] = jcb.getItemAt(i).toString();
192            }
193            return history;
194        }
195    }