开发者

JCombobox containing enum values inside a table

开发者 https://www.devze.com 2022-12-27 21:54 出处:网络
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 th开发者_如何学编程at will use these enums values.

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 th开发者_如何学编程at 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消