2013-03-06 69 views
0

我試圖製作一個JTable,它有一個單元格中的JComboBox。我知道我可以使用celleditor,但訣竅是我需要每行的組合框中有不同的信息。表中的每一行代表一個對象,在那個對象上有一個數組列表,它是我想要的組合列表中的數組列表的內容。這是我迄今爲止的思考過程。JTable和JComboBox的組合使用

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); 

現在,當我後來調用該方法(通過按下一個按鈕),我想插入新行與明杆中的5獨特的組合框,但我不知道怎麼做。我嘗試過。

public void fillTable(String text){ 
    tableModel.insertRow(tableModel.getRowCount(), "" }); 
    tableModel.fireTableRowsInserted(
    tableModel.getRowCount(), 
    tableModel.getRowCount()); 

    comboBox.addItem(text); 

}

+0

的輸入是fillTable是字符串,因爲它似乎更容易給串的例子indput代替陣列 – 2013-03-06 10:17:38

+0

使用一個'ComboBoxCellEditor',當'getTableCellEditorComponent'被調用時,檢查該行的索引並重新加載' ComboBoxModel' – MadProgrammer 2013-03-06 10:35:56

+0

This [Example](http://stackoverflow.com/questions/13699467/add-different-combobox-for-each-row-of-a-column-in-a-jtable/13703143#13703143)解決了你的問題問題。 – Amarnath 2013-03-06 19:00:27

回答

2

不過此時,相應的方法是使用一個單元格編輯器。

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