2011-05-18 23 views
1

我有JTable的問題,我試圖放入每行JComboBoxes和JTextFields,但是當我加載應用程序時,我的表是空的。函數getCmb *和getTxt *返回JComboBox和JTextField,這工作正常,我檢查。添加組件後,JTable爲空

 JTable tblCommands; 
     String[] columnTitles=new String[]{"Command","Offset","Type","Value","Units","Value Type","R/W"}; 
     Object[][] data=new Object[20][7]; 
     int row=0; 
     for(MessageCSVView message:messageContainer.getRows()){ 
      data[row][0]=message.getCmbName();//this works 
      data[row][1]=message.getCmbOffset();//this works 
      data[row][2]=message.getTxtType();//this works 
      data[row][3]=message.getTxtValue();//this works 
      data[row][4]=message.getTxtUnit();//this works 

      data[row][5]=message.getTxtValueType();//this works 
      data[row][6]=message.getCmbRW();//this works 
      row++; 
     } 
     tblCommands=new JTable(data,columnTitles); 

有人可以告訴我我做錯了什麼嗎?

+2

請閱讀本教程http://download.oracle.com/javase/tutorial/uiswing/components/table.html#combobox以及關於JComboBox的示例 – mKorbel 2011-05-18 10:11:09

回答

2

您誤解輸入與JTable一起使用的方式。

您需要創建TableCellEditor實現並將它們添加到表格的每一列。

查看有關JTable的Swing教程以獲取更多信息。

+0

正確答案+1。並感謝您將錯誤指向我的帖子。 – 2011-05-18 10:09:09

1

摘要示例

public class JComboBoxCellEditor extends DefaultCellEditor {  
    JComboBox comboBox;  
    public JComboBoxCellEditor() { 
     super(new JComboBox()); 
     comboBox = (JComboBox) getComponent(); 
    } 
} 

然後包括像下面,

TableColumn column = myTable.getColumnModel().getColumn(0); 
column.setCellEditor(new JComboBoxCellEditor()); 

延伸閱讀:

這裏是你最好的選擇,Swing tutorial for JTable

+1

這段代碼不會編譯,因爲'JComboBox'不是'TableCellEditor'。 – jfpoilpret 2011-05-18 09:52:56

+0

@jfpoilpret:謝謝你指出。 – 2011-05-18 10:02:38