I have a JTable with JCombobox editor for a certain column.
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
public class TablePanel extends JPanel {
public TablePanel() {
JTable table = new JTable(new MyTableModel());
setComboboxColumn(table.getColumnModel().getColumn(1));
add(new JScrollPane(table));
}
public void setComboboxColumn(TableColumn cbColumn) {
JComboBox<String> comboBox = new JComboBox<>();
comboBox.addItem("Item 1");
comboBox.addItem("Item 2");
comboBox.addItem("Item 3");
cbColumn.setCellEditor(new DefaultCellEditor(comboBox));
}
private static class MyTableModel extends AbstractTableModel {
private String[] columnNames = {"Normal cell", "Combobox cell"};
private Object[][] data = {
{"Cell 1", "Item 2"},
{"Cell 2", "Item 1"},
{"Cell 3", "Item 1"},
{"Cell 4", "Item 3"},
};
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return data.length;
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
@Override
public Object getValueAt(int row, int col) {
return data[row][col];
}
@Override
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
@Override
public boolean isCellEditable(int row, int col) {
return true;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
data[rowIndex][columnIndex] = aValue;
}
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("TablePanel");
frame.getContentPane().add(new TablePanel());
frame.pack();
frame.setVisible(true);
}
});
}
}
What happens now:
- When I click for the first time on a cell of that column the combobox popup shows up immediately.
- If I click other cells of the same column, the combobox shows up but the popup remains closed.
- If I click on other cells and then back again on a cell of that column, the combobox popup shows up again immediately.
What I would like:
- First click on the cell of that column: the combobox shows up, but the popup list remains closed.
- Second click again on the same cell: the popup list shows up.
I know that I can use cellEditor.setClickCountToStart(2)
but in this case the second click must be performed in a short time after the first one, and I would like to avoid this limit.