SCCEE here:
import java.awt.EventQueue;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
public class TC extends JFrame{
public TC(){
begin();
}
private void begin(){
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setTitle("nothing.");
String[] options = {"One", "Two", "Three"};
JComboBox<String> combo = new JComboBox<>(options);
JTable table = new JTable(new Object[2][2], new String[]{"One", "Two"});
TableColumn col0 = table.getColumnModel().getColumn(0);
col0.setCellEditor(new DefaultCellEditor(combo));
class MyRender extends DefaultTableCellRenderer {
public MyRender() {
}
@Override
public void setValue(Object value) {
if (value instanceof JComboBox) {
setText(((JComboBox) value).getSelectedItem().toString());
}
}
}
MyRender renderer = new MyRender();
col0.setCellRenderer(renderer);
JScrollPane sp = new JScrollPane(table);
getContentPane().add(sp);
pack();
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
@Override
public void run() {
TC tc = new TC();
}
});
}
}
My problem is: setting the TableCellRenderer makes the combo choose an empty option atop of all other values, without anyone telling it to do so. The empty entry comes from nowhere.
How can I make the combo select the "One" entry at first moment, instead of " "? Something I missed when implementing the custom renderer?? I followed here:
Oracle tutorial of How to Use Tables - Swing - Java SE
Also, the combo is not shown until I click it. I don't think it's the proper way to show it. I tried to follow another example here:
Show a JComboBox with custom editor and renderer, example from java2s.com
but I remain confused.