Java 将 JComboBox 放入 JTable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/457463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:51:45  来源:igfitidea点击:

Putting JComboBox into JTable

javajtablejcombobox

提问by Dan

I want to put individual JComboBoxes into each cells of a JTable. ie. The JComboBox content is not identical for each cell.

我想将单独的 JComboBoxes 放入 JTable 的每个单元格中。IE。每个单元格的 JComboBox 内容并不相同。

I basically would like to be able to just call the following code to add a row of JComboBox into the JTable. Anyone has any idea? Thanks

我基本上希望能够调用以下代码将一行 JComboBox 添加到 JTable 中。任何人有任何想法?谢谢

JComboBox cb1 = new JComboBox(...);
JComboBox cb2 = new JComboBox(...);
model.addRow(new Object[] {"Row name", cb1, cb2} );

JComboBox cb3 = new JComboBox(...);
JComboBox cb4 = new JComboBox(...);
model.addRow(new Object[] {"Row name 2", cb3, cb4} );

The closest example code I can find is as follows. But it is for where JComboBox content is identical for the individual column. Not the solution I need.

我能找到的最接近的示例代码如下。但它是针对单个列的 JComboBox 内容相同的地方。不是我需要的解决方案。

TableColumn col = table.getColumnModel().getColumn(vColIndex);
col.setCellEditor(new MyComboBoxEditor(values));

where

在哪里

public class MyComboBoxEditor extends DefaultCellEditor {
    public MyComboBoxEditor(String[] items) {
        super(new JComboBox(items));
    }
}

采纳答案by Cogsy

The easiest way is to implement your own TableModel

最简单的方法是实现自己的TableModel

public class MyModel extends AbstractTableModel {
    List rows;

    public int getRowCount() {
        return rows.size();
    }

    public int getColumnCount() {
         return 4;
    }

    public Object getValueAt(int row, int column) {
        return rows.get(row).getCol(col);  //assuming your row "Object" has a getCol()
    }

    public Class<?> getColumnClass(int col) {
        return Boolean.class;
    }

    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        rows.get(rowIndex).getCol(columnIndex).setValue(aValue);
    }

}

Load this into you JTable. If you haven't replaced the default cell renderer for Boolean's, all you cells will be rendered as check boxes thanks to you implementation of getColumnClass(). All user input to these check boxes is collected with our setValueAt().

将其加载到 JTable 中。如果您还没有为 Boolean 替换默认的单元格渲染器,那么由于您实现了 getColumnClass(),所有单元格都将被渲染为复选框。这些复选框的所有用户输入都通过我们的 setValueAt() 收集。

回答by Luke Woodward

This pagemight help you, although it seems you are restricted to having the same combobox in all the cells in a column.

此页面可能对您有所帮助,尽管您似乎仅限于在一列中的所有单元格中使用相同的组合框。

回答by willcodejavaforfood

You need to override:

您需要覆盖:

Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)

...in TableCellEditor. The value passed in to this method is what you can put in your JComboBox. That means that the 'value' for that particular cell needs to be something that can be translated into a collection. It could potentially just be a List of objects or it could be a POJO with fields that could be made into a JComboBox.

...在 TableCellEditor 中。传递给此方法的值是您可以放入 JComboBox 的值。这意味着该特定单元格的“值”需要是可以转换为集合的内容。它可能只是一个对象列表,也可能是一个 POJO,其中的字段可以制成 JComboBox。

So just edit MyComboBoxEditor to override that method and change your model to allow for an Object that actually represents several other objects.

因此,只需编辑 MyComboBoxEditor 以覆盖该方法并更改您的模型以允许实际代表多个其他对象的对象。

回答by Cogsy

You need to create a subclass of JTable to override the method TableCellEditor getCellEditor(int row, int column).

您需要创建 JTable 的子类来覆盖方法 TableCellEditor getCellEditor(int row, int column)。

This enables you to set arbitrary cell editors for any row and column combination. The default way is to set the cell editor for an entire column.

这使您可以为任何行和列组合设置任意单元格编辑器。默认方式是为整列设置单元格编辑器。

(You can also set individual cell renderers by overriding getCellRenderer.)

(您还可以通过覆盖 getCellRenderer 来设置单个单元格渲染器。)

回答by user74523

Extend JTable with this code:

使用以下代码扩展 JTable:

@Override
public TableCellEditor getCellEditor(int row, int column) {
   Object value = super.getValueAt(row, column);
   if(value != null) {
      if(value instanceof JComboBox) {
           return new DefaultCellEditor((JComboBox)value);
      }
            return getDefaultEditor(value.getClass());
   }
   return super.getCellEditor(row, column);
}

This will create a unique JComboBox cell editor for each combo box you get the a value for.

这将为您获得 a 值的每个组合框创建一个唯一的 JComboBox 单元格编辑器。

回答by Rogério

@Override
public TableCellEditor getCellEditor(int row, int column) {
   Object value = super.getValueAt(row, column);
   if(value != null) {
      if(value instanceof JComboBox) {
           return new DefaultCellEditor((JComboBox)value);
      }
            return getDefaultEditor(value.getClass());
   }
   return super.getCellEditor(row, column);
}

And then, override the toStringmethod from JComboBox.

然后,toStringJComboBox.

回答by Mujahid

I am sure this will solve your problem. Mention in which column you need to set the combo box in .getColumn(int column)

我相信这会解决你的问题。在 .getColumn(int column) 中提到你需要在哪一列设置组合框

private void addComboToTable(JComboBox combo) {
    TableColumn gradeColumn = YourTable.getColumnModel().getColumn(0);
    JComboBox comboBox = combo;
    comboBox.removeAllItems();
    try {
        comboBox.addItem("Item 1");
        comboBox.addItem("Item 2");
        comboBox.addItem("Item 3");
    } catch (NullPointerException e) {
    } catch (Exception e) {
        e.printStackTrace();
    }
    gradeColumn.setCellEditor(new DefaultCellEditor(comboBox));
}

回答by Ivar

The JComboBox content is render identical for each row selection because the JTable does not offer the capability to have more than one editor per column. You have to extend the JTable class to support an additional selection for rows.

JComboBox 内容对于每一行选择呈现相同,因为 JTable 不提供每列具有多个编辑器的功能。您必须扩展 JTable 类以支持额外的行选择。

This article explains it very well: http://www.javaworld.com/javaworld/javatips/jw-javatip102.html

这篇文章解释得很好:http: //www.javaworld.com/javaworld/javatips/jw-javatip102.html

回答by Adrian

In addition to cellEditor it is necessary to do the cellRenderer to paint the combobox in the cell, look at this:

除了cellEditor还需要做cellRenderer来绘制cell中的combobox,看这个:

 public void example(){  

      TableColumn tmpColum =table.getColumnModel().getColumn(1);
      String[] DATA = { "Data 1", "Data 2", "Data 3", "Data 4" };
      JComboBox comboBox = new JComboBox(DATA);

      DefaultCellEditor defaultCellEditor=new DefaultCellEditor(comboBox);
      tmpColum.setCellEditor(defaultCellEditor);
      tmpColum.setCellRenderer(new CheckBoxCellRenderer(comboBox));
      table.repaint();
   }


/**
   Custom class for adding elements in the JComboBox.
*/
class CheckBoxCellRenderer implements TableCellRenderer {
        JComboBox combo;
        public CheckBoxCellRenderer(JComboBox comboBox) {
            this.combo = new JComboBox();
            for (int i=0; i<comboBox.getItemCount(); i++){
                combo.addItem(comboBox.getItemAt(i));
            }
        }
        public Component getTableCellRendererComponent(JTable jtable, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            combo.setSelectedItem(value);
            return combo;
        }
    }