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

时间:2013-02-21 22:32:39

标签: java swing jtable jcombobox

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

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

编辑:有一件事我忘了提到的是;而不是像之前那样声明DefaultTableModel data之前的项目,而是使用model.addRow();

将项目添加到DTM中

2 个答案:

答案 0 :(得分:2)

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

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

阅读Using Custom Renderers上的Swing教程中的部分以获取更多信息。

答案 1 :(得分:1)

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

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<comboBox.getItemCount(); i++){
        combo.addItem(comboBox.getItemAt(i));
    }
    }
    public Component getTableCellRendererComponent(JTable jtable, 
                           Object value, 
                           boolean isSelected, 
                           boolean hasFocus, 
                           int row, int column) {
    combo.setSelectedItem(value);
    return combo;
    }
}

或者您可以像this示例中那样自定义默认渲染器。

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是可点击的。我使用了第二个例子,结果可以看到here

相关问题