3

I have a class containing Enum with values. (names) In other class I would like to enter inside a table a cell type of JCombobox that will use these enums values. my problem is to combain between string values and the enum. for example the enum class:

enum item_Type {entree, main_Meal, Dessert, Drink}

for example the table class: setTitle("Add new item" ); 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 );

I know that at the dataValues array I cant use aaa (the enum jcombobox). How can I do that?

thanks in advance.

4

1 回答 1

4

您需要在 上设置TableCellEditorJTable显示组合框。

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

如果您还没有,我强烈建议您查看如何使用表格教程。它更详细地解释了这一点,并包含示例代码。

于 2010-04-25T13:27:43.077 回答