views:

117

answers:

1

Hello,

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.

+1  A: 

You need to set a TableCellEditor on the JTable to display the combo box.

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

In your dataValues array, just use a placeholder for the combo box:

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

You will, of course, need to set the column editor after creating the table:

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

I highly recommend that you take a look at the How to Use Tables tutorial, if you haven't already. It explains this in greater detail, and includes sample code.

Jason Day