将JComboBox添加到JTable单元

时间:2013-01-16 10:02:38

标签: java swing jtable jcombobox tablecelleditor

  

可能重复:
  How to add a JComboBox to a JTable cell?

我发现很难将JComboBox添加到JTable的其中一个单元格中,我尝试了下面的代码,但它不起作用..

如何将jcombobox添加到特定单元格?

enter后,新的jcombobox应自动添加到所需的列中。

jTable1 = new javax.swing.JTable();
mod=new DefaultTableModel();
mod.addColumn("No");
mod.addColumn("Item ID");
mod.addColumn("Units");
mod.addColumn("Amount");
mod.addColumn("UOM");
mod.addColumn("Delivery Date");
mod.addColumn("Total Amount");
mod.addColumn("Notes");
mod.addColumn("Received");
mod.addRow(new Object [][] {
        {1, null, null, null, null, null, null, null, null}
    });
jTable1.setModel(mod);
jTable1.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(generateBox()));
jTable1.setColumnSelectionAllowed(true);


Code to generate ComboBox

private JComboBox generateBox()
 {
     JComboBox bx=null;
     Connection con=CPool.getConnection();
     try
     {
         Statement st=con.createStatement();
         String query="select distinct inid from inventory where company_code="+"'"+ims.MainWindow.cc+"'";
         ResultSet rs=st.executeQuery(query);
         bx=new JComboBox();
         while(rs.next()){
             bx.addItem(rs.getString(1));
         }
         CPool.closeConnection(con);
         CPool.closeStatement(st);
         CPool.closeResultSet(rs);
     }catch(Exception x)
     {
         System.out.println(x.getMessage());
     }
             return bx;

 }

2 个答案:

答案 0 :(得分:11)

答案 1 :(得分:8)

通过扩展DefaultCellEditor

JComboBox添加到JTable

示例:

TableColumn comboCol1 = table.getColumnModel().getColumn(0);
comboCol1.setCellEditor(new CustomComboBoxEditor());

/**
   Custom class for adding elements in the JComboBox.
*/
public class CustomComboBoxEditor extends DefaultCellEditor {

  // Declare a model that is used for adding the elements to the `Combo box`
  private DefaultComboBoxModel model;

  public CustomComboBoxEditor() {
      super(new JComboBox());
      this.model = (DefaultComboBoxModel)((JComboBox)getComponent()).getModel();
  }

  @Override
  public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
      // Add the elements which you want to the model.
      // Here I am adding elements from the orderList(say) which you can pass via constructor to this class.
      model.addElement(orderList.get(i));

      //finally return the component.
      return super.getTableCellEditorComponent(table, value, isSelected, row, column);
  } 
}
  

通过使用自定义类在JTable中创建组件,您可以拥有   更多地控制您正在展示的内容。