[英]Combined use of JTable and JComboBox
我正在嘗試制作一個JTable,它在一個單元格中有一個JComboBox。 我知道我可以使用celleditor,但訣竅是我想在每一行的組合框中提供不同的信息。 表中的每一行代表一個對象,在該對象上有一個arraylist,它是我在組合框中想要的那個arraylist的內容。 到目前為止,這是我的思考過程。
table = new JTable(tableModel);
tableModel = new DefaultTableModel();
forestTable.setModel(tableModelForest);
tmpColum = forestTable.getColumnModel().getColumn(5);
tmpColum.setCellEditor(new DefaultCellEditor(comboBox));
comboBox = new JComboBox<Tree> ();
comboBox.setEditable(false);
現在當我稍后調用該方法(通過按下按鈕)時,我想在coloum 5中插入一個帶有獨特組合框的新行,但我不知道它是怎么做的。 我試過了。
public void fillTable(String text){
tableModel.insertRow(tableModel.getRowCount(), "" } );
tableModel.fireTableRowsInserted(
tableModel.getRowCount(),
tableModel.getRowCount());
comboBox.addItem(text);
}
適當的方式仍然是使用單元格編輯器。
tmpColum.setCellEditor(new DefaultCellEditor(comboBox) {
@Override
public Component getTableCellEditorComponent(JTable table,
Object value,
boolean isSelected,
int row,
int column) {
JComboBox comboBox = (JComboBox)super.getTableCellEditorComponent(
table, value, isSelected, row, column);
// stuff the combobox with values and selection.
ComboBoxModel cbmodel = getMyCBModel(row); // Or (ComboBoxModel)value
comboBox.setModel(cbmodel);
// Or:
if (value == null)
comboBox.setSelectedIndex(-1);
else
comboBox.setSelectedItem(value);
return comboBox;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.