Share the post "JComboBox CellEditor And “component must be showing on the screen to determine its location” Error"
If you use a JComboBox as a cell editor in a JTable and you get this error message “component must be showing on the screen to determine its location”, chances are your cell editor is inherited from DefaultCellEditor. Thomas Bang saved us all the trouble in trying to figure out how to make a workaround for this problem by creating a ComboBoxCellEditor class inheriting from AbstractCellEditor.
Pretty cool. This class actually did the trick.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.Serializable; import javax.swing.AbstractCellEditor; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.table.TableCellEditor; public class ComboBoxPaneledCellEditor extends AbstractCellEditor implements ActionListener, TableCellEditor, Serializable { private JComboBox comboBox; public ComboBoxPaneledCellEditor(JComboBox comboBox) { this.comboBox = comboBox; this.comboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE); // hitting enter in the combo box should stop cellediting (see below) this.comboBox.addActionListener(this); } private void setValue(Object value) { comboBox.setSelectedItem(value); } @Override public void actionPerformed(java.awt.event.ActionEvent e) { // Selecting an item results in an actioncommand "comboBoxChanged". // We should ignore these ones. // Hitting enter results in an actioncommand "comboBoxEdited" if(e.getActionCommand().equals("comboBoxEdited")) { stopCellEditing(); } } // Implementing CellEditor @Override public Object getCellEditorValue() { return comboBox.getSelectedItem(); } @Override public boolean stopCellEditing() { if (comboBox.isEditable()) { // Notify the combo box that editing has stopped (e.g. User pressed F2) comboBox.actionPerformed(new ActionEvent(this, 0, "")); } fireEditingStopped(); return true; } @Override public Component getTableCellEditorComponent(javax.swing.JTable table, Object value, boolean isSelected, int row, int column) { setValue(value); return comboBox; } } |