001    package de.mospace.swing.text;
002    
003    /* Mp3dings - manage mp3 meta-information
004    * Copyright (C) 2003 Moritz Ringler
005    * $Id: FullTextStringCellEditor.java 109 2007-11-05 17:33:59Z 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.Component;
023    import java.awt.Point;
024    import java.awt.event.ActionEvent;
025    import java.awt.event.ActionListener;
026    import java.awt.event.FocusAdapter;
027    import java.awt.event.FocusEvent;
028    import javax.swing.AbstractAction;
029    import javax.swing.AbstractCellEditor;
030    import javax.swing.Action;
031    import javax.swing.JButton;
032    import javax.swing.JLayeredPane;
033    import javax.swing.JScrollPane;
034    import javax.swing.JTable;
035    import javax.swing.JTextArea;
036    import javax.swing.KeyStroke;
037    import javax.swing.RootPaneContainer;
038    import javax.swing.SwingUtilities;
039    import javax.swing.table.TableCellEditor;
040    import de.mospace.lang.FullTextString;
041    
042    /**
043    * A multiline string editor for JTables. The cell contents are displayed and
044    * edited in a text area aligned with the cell's top, left, and
045    * right bounds. The text area is displayed in the modal layer above the cell
046    * that is edited.
047    *
048    * @version $Revision: 109 $ ($Date: 2007-11-05 18:33:59 +0100 (Mo, 05 Nov 2007) $)
049    * @author Moritz Ringler
050    * @see de.mospace.lang.FullTextString
051    * @see FullTextStringCellRenderer
052    **/
053    public class FullTextStringCellEditor extends AbstractCellEditor
054    implements TableCellEditor {
055        /**The button is used as the primary cell editor. However, ist is nothing
056         * but a trigger for dialg which does the actual editing. */
057        private final ShortButton button = new ShortButton();
058        /** A JScrollPane containing a TextArea where the FullTextString
059         * is edited. */
060        private final MyDialog dialg = new MyDialog();
061    
062        /** The table one of whose cells is currently edited. **/
063        private JTable t;
064        /** The row of the cell that is currently edited. **/
065        private int row = 0;
066        /** The column of the cell that is currently edited. **/
067        private int col = 0;
068    
069    
070        /**
071        * Creates a new FullTextStringCellEditor object.
072        */
073        public FullTextStringCellEditor() {
074            /* set up the button. */
075            button.addActionListener(new ActionListener() {
076                public void actionPerformed(ActionEvent e) {
077                    dialg.show(button.getLocationOnScreen(), button.getWidth(),
078                    button);
079                }
080            });
081        }
082    
083        /** Returns the value contained in the editor.
084        * @return the last edited value as a FullTextString or <code>null</code>
085        *         for empty or invalid values
086        * @see de.mospace.lang.FullTextString
087        **/
088        public Object getCellEditorValue() {
089            String content = dialg.getText();
090            if (content == null || content.equals("")) {
091                return (FullTextString) null;
092            } else {
093                return new FullTextString(content);
094            }
095        }
096    
097        /**
098         * Returns the component that should be added to the client's Component
099         * hierarchy. Sets an initial value for the editor. This will cause the
100         * editor to stopEditing and lose any partially edited value if the
101         * editor is editing when this method is called.
102         * Once installed in the client's hierarchy the returned component will
103         * be able to draw and receive user input.
104         *
105         * @param table the JTable that is asking the editor to edit; can be null
106         * @param value the value of the cell to be edited, null is a valid value
107         * @param isSelected must be true, otherwise <code>null</code> is returned
108         * @param row the row of the cell being edited
109         * @param column the column of the cell being edited
110         * @return a JButton as the primary cell editor
111         **/
112       public Component getTableCellEditorComponent(JTable table, Object value,
113                boolean isSelected, int row, int column) {
114            if (dialg.isEditing()){
115                cancelCellEditing();
116            }
117    
118            /* remember the cell that is edited */
119            t = table;
120            this.row = row;
121            col = column;
122            if (!isSelected) {
123                return null;
124            }
125            /* store the current value of the cell in the button. */
126            button.setValue(value);
127            // Assures the dialog is openend.
128            // If we don't do this the dialog is not opened
129            // in Java < 1.6, and opened in Java 1.6.
130            SwingUtilities.invokeLater(new Runnable(){
131                    public void run(){
132                        if(dialg == null || !dialg.isVisible()){
133                            button.doClick();
134                        }
135                    }
136            });
137    
138            /* return the button as primary cell editor */
139            return (Component) button;
140        }
141    
142        /**
143        * Closes the editor, notifies the JTable that editing
144        * has cancelled, and returns focus to the JTable and the cell that
145        * have been edited.
146        */
147        public void cancelCellEditing() {
148            dialg.stopEditing();
149            super.cancelCellEditing();
150            selectCell();
151        }
152    
153        /**
154        * Stops editing and returns true to indicate that editing has stopped.
155        * Closes the editor, notifies the JTable that editing
156        * has stopped, and returns focus to the JTable and the cell that
157        * has been edited.
158        */
159        public boolean stopCellEditing() {
160            dialg.stopEditing();
161            boolean b = super.stopCellEditing();
162            selectCell();
163            return b;
164        }
165    
166        /** Selects the cell from which the editor was called and thus
167        * ensures that focus returns to this cell. */
168        private void selectCell(){
169            if(t != null){
170                t.changeSelection(row, col, false, false);
171                t.requestFocusInWindow();
172            }
173        }
174    
175        /** Sets the height for the text-area in which cell contents are edited.
176        * @param i the new height in pixels, default is 100
177        **/
178        public void setHeight(int i){
179            dialg.setHeight(i);
180        }
181    
182        /* MYDIALOG CLASS */
183        /** The dialog used to edit the multiline-string. **/
184        private class MyDialog extends JScrollPane {
185            private boolean added = false;
186            private boolean isEditing = false;
187            private final JTextArea myText = new JTextArea("");
188            private int height = 100;
189    
190            /**
191            * Creates a new MyDialog object.
192            */
193            public MyDialog() {
194                setViewportView(myText);
195                setVisible(false);
196                myText.addFocusListener(new FocusAdapter() {
197                    public void focusLost(FocusEvent e) {
198                        if(isEditing()){
199                            stopCellEditing();
200                        }
201                    }
202                });
203    
204                final Action cancelAction = new AbstractAction(){
205                    public void actionPerformed(ActionEvent e){
206                        cancelCellEditing();
207                    }
208                };
209    
210                final Action okAction = new AbstractAction(){
211                    public void actionPerformed(ActionEvent e){
212                        stopCellEditing();
213                    }
214                };
215    
216                myText.getInputMap().put(KeyStroke.getKeyStroke("ESCAPE"),"cancel");
217                myText.getInputMap().put(KeyStroke.getKeyStroke("shift ENTER"),"commit");
218                myText.getInputMap().put(KeyStroke.getKeyStroke("ctrl ENTER"),"commit");
219                myText.getInputMap().put(KeyStroke.getKeyStroke("alt ENTER"),"commit");
220                myText.getActionMap().put("commit", okAction);
221                myText.getActionMap().put("cancel", cancelAction);
222            }
223    
224            /**
225            * Returns whether this dialog is editing.
226            **/
227            public boolean isEditing() {
228                return isEditing;
229            }
230    
231            /** Closes this dialog and stops editing. **/
232            public void stopEditing(){
233                setVisible(false);
234                isEditing = false;
235            }
236    
237    
238            /**
239            * Returns the text the user has entered.
240            */
241            public String getText() {
242                return myText.getText();
243            }
244    
245            /**
246            * Sets the height of this dialog.
247            * @param i the new dialog height in pixels, default is 100
248            **/
249            public void setHeight(int i){
250                height = i;
251                if (isVisible()){
252                    setBounds(getBounds().x,
253                              getBounds().y,
254                              getBounds().width,
255                              height);
256                }
257            }
258    
259    
260            /**
261            * Displays this dialog.
262            *
263            * @param p position of the top-left corner relative to parent
264            * @param w width of the dialog
265            * @param c parent component
266            */
267            public void show(Point p, int w, Component c) {
268                isEditing = true;
269                JLayeredPane myRoot = ((RootPaneContainer) SwingUtilities.getWindowAncestor(
270                c)).getLayeredPane();
271                if (!added) {
272                    myRoot.add(this, JLayeredPane.MODAL_LAYER);
273                    added = true;
274                }
275                SwingUtilities.convertPointFromScreen(p, myRoot);
276                setBounds(p.x, p.y, w, height);
277                myText.setText(button.getValue());
278                myText.setCaretPosition(0);
279                setVisible(true);
280                myText.requestFocusInWindow();
281            }
282        }
283    
284        /* SHORTBUTTON CLASS */
285        /**
286        * A Button that represents the multi-line string when it is not being
287        * edited.
288        */
289        private class ShortButton extends JButton {
290    
291            private String text;
292    
293            /**
294            * Creates a new ShortButton object.
295            */
296            public ShortButton() {
297                setContentAreaFilled(false);
298            }
299    
300            /**
301            * Sets the value of the ShortButton.
302            * @param value the new value
303            */
304            public void setValue(Object value) {
305                text = (value == null) ? null : value.toString();
306                super.setText(shorten(text));
307            }
308    
309            /**
310            * Returns the current value of the ShortButton as a String.
311            */
312            public String getValue() {
313                return (text == null) ? "" : text;
314            }
315    
316            /**
317            * Truncates the string str to a single line
318            * of at most 29 characters and adds
319            * three dots if appropriate.
320            */
321            private String shorten(String str) {
322                if (str == null) {
323                    return "";
324                }
325                if (str.length() == 0) {
326                    return "";
327                }
328    
329                int iend = str.length();
330                int inull = str.indexOf(0);
331                int ibreak = str.indexOf('\n');
332                int i = Math.min(iend, 29);
333                if ((inull > -1) && (inull < i)) {
334                    i = inull;
335                }
336                if ((ibreak > -1) && ibreak < i) {
337                    i = ibreak;
338                }
339    
340                String shortstr = str.substring(0, i);
341                if (i < iend) {
342                    shortstr = shortstr.concat("...");
343                }
344                return shortstr;
345            }
346        }
347    }