001    // GraphLab Project: http://graphlab.sharif.edu
002    // Copyright (C) 2008 Mathematical Science Department of Sharif University of Technology
003    // Distributed under the terms of the GNU General Public License (GPL): http://www.gnu.org/licenses/
004    package graphlab.ui.components.gpropertyeditor.editors.inplace;
005    
006    import graphlab.platform.attribute.AtomAttribute;
007    import graphlab.ui.components.gpropertyeditor.EditingFinishedListener;
008    import graphlab.ui.components.gpropertyeditor.GBasicCellEditor;
009    import graphlab.ui.components.gpropertyeditor.GCellRenderer;
010    
011    import javax.swing.*;
012    import java.awt.*;
013    import java.awt.event.ActionEvent;
014    import java.awt.event.ActionListener;
015    
016    /**
017     * User: root
018     */
019    public abstract class GComboEditor implements GBasicCellEditor, ActionListener {
020        EditingFinishedListener listener;
021    
022        public void setEditingFinishedListener(EditingFinishedListener listener) {
023            this.listener = listener;
024        }
025    
026        JComboBox cbox;
027        Object initValue;
028    
029        public Component getEditorComponent(Object value) {
030            initValue = value;
031            cbox = new JComboBox(getValues());
032            cbox.addActionListener(this);
033            if (value instanceof AtomAttribute) {
034                AtomAttribute v = (AtomAttribute) value;
035                cbox.setSelectedItem(v.getValue());
036            } else {
037                cbox.setSelectedItem(value);
038            }
039            cbox.setRenderer(new ListCellRenderer() {
040                public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
041                    return GCellRenderer.getRendererFor(value);
042                }
043            });
044            cbox.setBackground(Color.white);
045            return cbox;
046        }
047    
048        public abstract Object[] getValues();
049    
050        public void cancelEditing() {
051            //nothing to do :D
052        }
053    
054        public Object getEditorValue() {
055            return getSelectedItem();
056        }
057    
058        /**
059         * occurs when one item of combo list selected
060         *
061         * @param e
062         */
063        public void actionPerformed(ActionEvent e) {
064            listener.editingFinished(getSelectedItem());
065        }
066    
067        /**
068         * returns the selected item in combo list
069         */
070        public Object getSelectedItem() {
071            if (initValue instanceof AtomAttribute) {
072                ((AtomAttribute) initValue).setValue(cbox.getSelectedItem());
073                return initValue;
074            } else
075                return cbox.getSelectedItem();
076        }
077    }