表单中的Java JComboBox在单击单元格之前未显示

好的,所以我有一个表设置,我已经在这里的示例中添加了一个JComboBox到特定的单元格,但由于某种原因,combobox将不会显示,直到选中该单元格。 如果我选择该单元格,combobox将打开它的列表供我选择。 无论我是否更改选择,如果单击表格中的另一个单元格,它将显示从combobox中选择的项目的文本,就好像它是根据需要显示在表格中的简单字符串一样。

我的问题是:如何让它在JComboBox中显示所选值而无需先选择单元格?

编辑:我忘了提到的一件事是; 而不是像之前那样手工声明DefaultTableModel data ,而是稍后使用model.addRow();将项目添加到DTM中model.addRow();

您可以尝试创建自己的渲染器,如本例所示。

 public void example(){ TableColumn tmpColum =table.getColumnModel().getColumn(1); String[] DATA = { "Data 1", "Data 2", "Data 3", "Data 4" }; JComboBox comboBox = new JComboBox(DATA); DefaultCellEditor defaultCellEditor=new DefaultCellEditor(comboBox); tmpColum.setCellEditor(defaultCellEditor); tmpColum.setCellRenderer(new CheckBoxCellRenderer(comboBox)); table.repaint(); } /** Custom class for adding elements in the JComboBox. */ class CheckBoxCellRenderer implements TableCellRenderer { JComboBox combo; public CheckBoxCellRenderer(JComboBox comboBox) { this.combo = new JComboBox(); for (int i=0; i 

或者您可以自定义此示例中的默认渲染器。

 final JComboBox combo = new JComboBox(items); TableColumn col = table.getColumnModel().getColumn(ITEM_COL); col.setCellRenderer(new DefaultTableCellRenderer(){ @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); label.setIcon(UIManager.getIcon("Table.descendingSortIcon")); return label; } }); 

第一个示例使单元格在单击后看起来像JComboBox。 第二个示例向JComboCox添加一个箭头图标,显示JComboBox是可点击的。 我用了第二个例子,结果可以在这里看到。

这是正常行为。 表使用渲染器和编辑器。 单元格的默认渲染器只是一个JLabel,所以你看到的只是文本。 当您单击单元格时,将调用编辑器,以便您看到combobox。

如果您希望单元格看起来像一个combobox,即使它没有被编辑,那么您需要为该列创建一个combobox渲染器。

有关更多信息,请阅读使用自定义渲染器的Swing教程中的部分。