我有一个有jComboBox列的jTable。但是我遇到了一个问题,除非你先点击它,否则我无法显示jComboBox。其他人使用了same problem,it seems。
所以我后来了解到除了CellEditor之外我还需要制作一个CellRenderer。所以我做了......
public class MyCellRenderer extends JComboBox<CustomItem> implements TableCellRenderer{
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column){
if(isSelected){
setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
} else{
setForeground(table.getForeground());
setBackground(table.getBackground());
}
setSelectedItem(value);
return this;
}
}
顺便说一下,我也在使用ComboBoxRenderer,因为我需要它来显示包含项目的文本。
public class MyComboBoxRenderer extends BasicComboBoxRenderer{
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus){
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(value != null){
CustomItem customItem = (CustomItem) value;
setText(customItem.getText());
}
if(index == -1){
CustomItem customItem = (CustomItem) value;
setText("" + customItem.getText());
}
return this;
}
}
现在它有效!它确实在我的jTable中显示jComboBox默认 BUT 现在每行上的每个jComboBox都有永久焦点!只有我点击的第一个实际显示菜单。其余的被选中&#39;但他们没有回应。
编辑:以下是我创建表格的方法。
private void initializeTable(){
JTable jTable1 = new javax.swing.JTable();
DefaultTableModel dtm = new DefaultTableModel();
dtm.addColumn("one");
dtm.addColumn("two");
dtm.addColumn("three");
jTable1.setModel(dtm);
JComboBox<CustomItem> items = new JComboBox<>();
items.setRenderer(new MyComboBoxRenderer());
items.add(new CustomItem(1, "soup", false);
items.add(new CustomItem(33, "sauce", false);
items.setSelectedIndex(0);
jTable1.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(items));
jTable1.getColumnModel().getColumn(2).setCellRenderer(new MyCellRenderer());
}