将JComboBox放入JTable [英] Putting JComboBox into JTable

查看:134
本文介绍了将JComboBox放入JTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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.

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

其中

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


推荐答案

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

The easiest way is to implement your own 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);
    }

}

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

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().

这篇关于将JComboBox放入JTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆