如何将JComboBox添加到JTable中的特定单元格

我想只在选择表中的特定单元格时才将defaultCellEditor更改为JComboBox。

覆盖JTable的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 editors = new ArrayList(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); // return (TableCellEditor)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); } } 

让您的TableModel从该单元格的isCellEditable()返回true。

如果使用netbeans,则在执行的jbutton操作下键入此代码。

你应该有jtable,jcombobox有几个项目。 试试这个单一代码:

 jTable1.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(jComboBox1));