1

我有一个 jTable,它有一个 jComboBox 列。但是,我遇到了一个问题,除非您先单击它,否则我无法显示 jComboBox。其他人似乎也有同样的问题

所以我后来了解到除了 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现在每行上的每个 jComboBox 都具有永久焦点!只有我点击的第一个实际显示菜单。其余的被“选中”,但它们没有响应。

编辑:这是我创建表格的方式。

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());
}
4

0 回答 0