Numerous bug fixes and updates
[debian/openrocket] / src / net / sf / openrocket / gui / components / UnitCellEditor.java
1 package net.sf.openrocket.gui.components;
2
3 import java.awt.Component;
4 import java.awt.event.ActionEvent;
5 import java.awt.event.ActionListener;
6
7 import javax.swing.AbstractCellEditor;
8 import javax.swing.JComboBox;
9 import javax.swing.JTable;
10 import javax.swing.table.TableCellEditor;
11
12 import net.sf.openrocket.unit.Unit;
13 import net.sf.openrocket.unit.UnitGroup;
14
15
16 /**
17  * A cell editor that returns a combo box containing a selection of units.
18  * Using classes must implement the {@link #getUnitGroup(Unit, int, int)} method
19  * to return the appropriate unit group for the selection.
20  * 
21  * @author Sampo Niskanen <sampo.niskanen@iki.fi>
22  */
23 public abstract class UnitCellEditor extends AbstractCellEditor 
24 implements TableCellEditor, ActionListener {
25
26         private final JComboBox editor;
27         
28         
29         public UnitCellEditor() {
30                 editor = new JComboBox();
31                 editor.setEditable(false);
32                 editor.addActionListener(this);
33         }
34         
35         
36         @Override
37         public Component getTableCellEditorComponent(JTable table, Object value,
38                         boolean isSelected, int row, int column) {
39
40                 Unit unit = (Unit) value;
41                 UnitGroup group = getUnitGroup(unit, row, column);
42                 
43                 editor.removeAllItems();
44                 for (Unit u: group.getUnits()) {
45                         editor.addItem(u);
46                 }
47                 
48                 editor.setSelectedItem(unit);
49                 
50                 return editor;
51         }
52
53         
54         @Override
55         public Object getCellEditorValue() {
56                 return editor.getSelectedItem();
57         }
58         
59
60         
61         @Override
62         public void actionPerformed(ActionEvent e) {
63                 // End editing when a value has been selected
64                 this.fireEditingStopped();
65         }
66
67
68         /**
69          * Return the unit group corresponding to the specified cell.
70          * 
71          * @param value         the cell's value.
72          * @param row           the cell's row.
73          * @param column        the cell's column.
74          * @return                      the unit group of this cell.
75          */
76         protected abstract UnitGroup getUnitGroup(Unit value, int row, int column);
77         
78 }