在JTable中链接多个JComboBox一次有问题

时间:2013-08-19 02:41:20

标签: java swing jtable jcombobox

当我在JTable上执行一些代码时,我遇到了一个非常棘手的问题

当我点击“添加”按钮时,我需要在JTable中添加一行,并且我想要其中一个列进行渲染 作为JComboBox

问题是,当我只添加一行时,它可以正常工作。 但是当我一次添加多行时,无论我从哪个组合框中选择项目,它总会触发最后一个comboBox的事件(因为我在MyComboxActionListener类中打印了jComboBox的哈希码,因此总是相同的组合框。它是一样的。)< / p>

为什么会发生这种情况,我无法弄明白。因为当我添加一行时,它完全是一个新的comboBox和一个新的监听器。

以下是代码。

提前致谢。

private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {                                    
    ProducedProcedure_new addedProducedProcedure = new ProducedProcedure_new();    // the new item 
    componentProcedureTableModel.getWorks().add(addedProducedProcedure);        //add one line to the table
    componentProcedureTableModel.fireTableRowsInserted(componentProcedureTableModel.getRowCount()-1, componentProcedureTableModel.getRowCount()-1);   

    jTable1.changeSelection(componentProcedureTableModel.getRowCount()-1,0, false, false);

    List<String> procedureNames = produceCardManager.getProcedureNames(componentIdTextField.getText().trim(),false);    //get the items added to combobox
    renderColumnAsCombox(1,procedureNames,addedProducedProcedure);   //-------------------------------------------
}        

 void renderColumnAsCombox(int columnIndex , List<String> items,ProducedProcedure_new producedProcedure) {
    TableColumn col = jTable1.getColumnModel().getColumn(columnIndex);
    JComboBox comboBox = new JComboBox();

    for(String item : items) {
       comboBox.addItem(item);
    }
    MyComboxActionListener myComboxActionListener = new MyComboxActionListener(columnIndex,comboBox,producedProcedure);
    comboBox.addActionListener(myComboxActionListener);
    col.setCellEditor(new DefaultCellEditor(comboBox));
}     

class MyComboxActionListener implements ActionListener {  // listen for the select event of the combobox
    private JComboBox jComboBox;
    private ProducedProcedure_new producedProcedure;
    private int columnIndex;

    public MyComboxActionListener(int columnIndex,JComboBox jComboBox,ProducedProcedure_new producedProcedure) {
        this.columnIndex = columnIndex;
        this.jComboBox = jComboBox;
        this.producedProcedure = producedProcedure;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
          String selectedItem = (String)jComboBox.getSelectedItem();
          producedProcedure.getProcedure().setProcedureName(selectedItem);
          producedProcedure.getProcedure().setProcedureId(String.valueOf(produceCardManager.getProcedureId(selectedItem)));
          producedProcedure.getProcedure().setFactor(produceCardManager.getProcedureFactor(selectedItem));   //automately update the factor
          ((ComponentProcedureTableModel_new)jTable1.getModel()).fireTableDataChanged();
    }
}                              

0 个答案:

没有答案