簡體   English   中英

JTable 中的 JComboBox 不保存選擇

[英]JComboBox within JTable not saving selection

我有一個包含NameChoice列的 JTable。 我希望Choice列包含一個JComboBox組件,該組件對每一行都有相同的選擇,盡管允許對每個唯一行進行獨立選擇。

目前,與列中的JComboBox交互允許出現下拉菜單以進行選擇; 但是,沒有保存任何選擇。

在此處輸入圖像描述

相反,所做的選擇會遷移到我單擊的任何JComboBox 例如,我點擊第一行的JComboBox和 select “Choice B”,但所有選項仍然顯示為“Choice A”。 直到我單擊另一行的JComboBox時才會出現下拉菜單並突出顯示“Choice B”選項。

該表使用的代碼如下:

final String[] choices = new String[]{"Choice A", "Choice B", "Choice C"};
final Collection<String> mockData = Arrays.asList("First", "Second", "Third", "Fourth", "Fifth", "Sixth");
table.setModel(new MasterTableModel(mockData.stream().map(s -> {
    return new Object[]{s, new JComboBox<>(choices)};
}).collect(Collectors.toSet())));
table.setDefaultEditor(JComboBox.class, new DefaultCellEditor(new JComboBox<>(choices)));
table.setDefaultRenderer(JComboBox.class, new MasterTableComboRenderer(table.getDefaultRenderer(JComboBox.class)));

我有三個選項,用於初始化填充Choice列的JComboBox 我將DefaultRenderer設置為我的自定義MasterTableComboRenderer object,它實現了TableCellRenderer接口,以便讓JComboBox顯示為Component ,而不是打印 object 的地址。 它只需要覆蓋一個方法:

class MasterTableComboRenderer ...
@Override
public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
    return value instanceof Component ? (Component) value : renderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}

最后, MasterTableModelAbstractTableModel的一個簡單擴展,它定義了列標題[Name, Choice]並保存了一個代表JTable數據的Object[][] 我已經覆蓋isCellEditablegetColumnClass如下:

class MasterTableModel...
@Override
public boolean isCellEditable(final int rowIndex, final int columnIndex) {
    return getColumnName(columnIndex).equals("Choice");
}

@Override
public Class<?> getColumnClass(final int columnIndex) {
    return getValueAt(0, columnIndex).getClass();
}

為了實現JComboBox的功能,我是否缺少一些東西來保存其選擇並且沒有選擇突出顯示遷移到其他框?

JComboBox不應存儲在TableModel中。 String值存儲在 model 中。

閱讀 Swing 教程中有關使用組合框作為渲染器的部分以獲取工作示例。

如果您希望渲染器看起來像一個組合框,那么您需要使用組合框作為渲染器。 就像是:

class ComboBoxRenderer extends JComboBox implements TableCellRenderer
{
    public ComboBoxRenderer()
    {
        setBorder(null);
    }

    public Component getTableCellRendererComponent(
        JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        removeAllItems();
        addItem( value );

        return this;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM