Problem/Question Using JComboBox as a tablecelleditor

D

dieselmachine

I have the following code, which uses two different methods of editing
a cell with a jcombobox. With the first column, i can click once, and
have the menu pop up, but when i select a value, the popup disappears,
but the arrow indicating a dropdown remains, and the color of the cell
remains the color of the dropdown.

In the second column, this problem is not present. I am wondering what
changes I would need to make to the first column's editor code in
order to have it behave the same way as the second column's editor. Or
more in general, what is the method that causes the editor to vanish
and yield to the cellrenderer?

Here is the code in its entirety:

import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.table.*;

class comboTest extends JFrame
{ private JPanel panel;
private JTable table;
private JScrollPane scrollpane;

public comboTest()
{
setSize( 300, 200 );

panel = new JPanel();
panel.setLayout(new BorderLayout());
getContentPane().add(panel);

String columns[] = {"Type 1","Type 2"};
String combochoices[] = {"value1","value2","value3"};
String data[][] =
{
{"value1","value2"},
{"value2","value3"}
};
table = new JTable( data, columns );

TableColumn col0 = table.getColumnModel().getColumn(0);
col0.setCellEditor(new comboBoxEditor(combochoices));
TableColumn col1 = table.getColumnModel().getColumn(1);
col1.setCellEditor(new comboBoxEditor2(combochoices));

scrollpane = new JScrollPane( table );
panel.add( scrollpane, BorderLayout.CENTER );
}

public static void main( String args[] )
{ comboTest frame = new comboTest();
frame.setVisible(true);
}
}

class comboBoxEditor extends AbstractCellEditor implements
TableCellEditor
{ JComponent component;

public comboBoxEditor(String[] choices)
{ component = new JComboBox(choices);
}
public Object getCellEditorValue()
{ return ((JComboBox)component).getSelectedItem();
}
public JComponent getTableCellEditorComponent
(JTable table, Object value, boolean isSelected, int rowIndex, int
vColIndex)
{ ((JComboBox)component).setSelectedItem(value);
return component;
}
}
class comboBoxEditor2 extends DefaultCellEditor
{ public comboBoxEditor2(String[] choices)
{ super(new JComboBox(choices));
}
public Object getCellEditorValue()
{ return ((JComboBox)getComponent()).getSelectedItem();
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,818
Messages
2,569,727
Members
45,675
Latest member
benn

Latest Threads

Top