我有一个使用模型创建的 JTable,该模型基于对象矩阵。
对于每一行,我想使用 JComboBox 在特定列(第 5 列)中放入一些信息。我尝试了以下方法:

for(int i=0; i < n ; i++) {
    .....
    data[i][5] = new JComboBox(aux); // aux is a Vector of elements I wanna insert
}
table.setModel(new MyTableModel()); // MyTableModel() already takes into consideration the data[][] object
问题在于 data[i][5] = new JComboBox(aux); 不会在 JTable 的特定单元格中创建 JComboBox 对象,而是将代码粘贴到行中。我能做些什么来解决这个问题?

最佳答案

一种方法是覆盖 getCellEditor() 方法以返回适当的编辑器。这是一个让您入门的示例:

import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.table.*;

public class TableComboBoxByRow extends JFrame
{
    List<TableCellEditor> editors = new ArrayList<TableCellEditor>(3);

    public TableComboBoxByRow()
    {
        // Create the editors to be used for each row

        String[] items1 = { "Red", "Blue", "Green" };
        JComboBox comboBox1 = new JComboBox( items1 );
        DefaultCellEditor dce1 = new DefaultCellEditor( comboBox1 );
        editors.add( dce1 );

        String[] items2 = { "Circle", "Square", "Triangle" };
        JComboBox comboBox2 = new JComboBox( items2 );
        DefaultCellEditor dce2 = new DefaultCellEditor( comboBox2 );
        editors.add( dce2 );

        String[] items3 = { "Apple", "Orange", "Banana" };
        JComboBox comboBox3 = new JComboBox( items3 );
        DefaultCellEditor dce3 = new DefaultCellEditor( comboBox3 );
        editors.add( dce3 );

        //  Create the table with default data

        Object[][] data =
        {
            {"Color", "Red"},
            {"Shape", "Square"},
            {"Fruit", "Banana"},
            {"Plain", "Text"}
        };
        String[] columnNames = {"Type","Value"};
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        JTable table = new JTable(model)
        {
            //  Determine editor to be used by row
            public TableCellEditor getCellEditor(int row, int column)
            {
                int modelColumn = convertColumnIndexToModel( column );

                if (modelColumn == 1 && row < 3)
                    return editors.get(row);
                else
                    return super.getCellEditor(row, column);
            }
        };
        System.out.println(table.getCellEditor());

        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );
    }

    public static void main(String[] args)
    {
        TableComboBoxByRow frame = new TableComboBoxByRow();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible(true);
    }
}

编辑:代码更新为使用垃圾神的建议。

关于java - JTable 单元格中的 JComboBox,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3256086/

10-12 14:59