2010-04-25 53 views
2

我有一個包含Enum值的類。 (姓名) 在其他類中,我想在表格中輸入JCombobox的單元格類型,它將使用這些枚舉值。 我的問題是在字符串值和枚舉之間進行連接。 例如枚舉類:JCombobox在表中包含枚舉值

枚舉ITEM_TYPE {主菜,main_Meal,甜品,飲料}

例如表類: 的setTitle( 「添加新的項」); setSize(300,80); setBackground(Color.gray);

// Create a panel to hold all other components 
    topPanel = new JPanel(); 
    topPanel.setLayout(new BorderLayout()); 
    getContentPane().add(topPanel); 

    //new JComboBox(item_Type.values()); 
    JComboBox aaa = new JComboBox(); 
    aaa = new JComboBox(item_Type.values()); 
    TableColumn sportColumn = table.getColumnModel().getColumn(2); 

    // Create columns names 
    String columnNames[] = {"Item Description", "Item Type", "Item Price"}; 

    // Create some data 
    String dataValues[][] = {{ "0", aaa, "0" }}; 
    // Create a new table instance 
    table = new JTable(dataValues, columnNames); 

    // Add the table to a scrolling pane 
    scrollPane = new JScrollPane(table); 
    topPanel.add(scrollPane, BorderLayout.CENTER); 

我知道在dataValues數組我不能使用aaa(enum jcombobox)。 我該怎麼做?

在此先感謝。

回答

3

您需要在JTable上設置TableCellEditor才能顯示組合框。

TableColumn column = table.getColumnModel().getColumn(2); 
column.setCellEditor(new DefaultCellEditor(aaa)); 

在你dataValues陣列,只需使用一個佔位符組合框:

String dataValues[][] = {{ "0", "entree", "0" }}; 

你會的,當然,需要設置列編輯後創建表:

String dataValues[][] = {{ "0", "entree", "0" }}; 
JTable table = new JTable(dataValues, columnNames); 
TableColumn column = table.getColumnModel().getColumn(2); 
column.setCellEditor(new DefaultCellEditor(aaa)); 

我強烈建議你看看How to Use Tables教程,如果你還沒有。它更詳細地解釋了這一點,幷包含示例代碼。