have problems in Linking multiple JComboBox in JTable one time
I got a quite tricky problem when I do some code on JTable
I need to add one line In JTable when I click "Add" button, and I want one
of the columns to render as a JComboBox
the problem is that when I only add one line, it works fine. but when I
add multiple lines a time, no matter which combobox I choose item from, It
will always trigger the last comboBox's event(seems always the same
combobox since I have printed the hashcode of jComboBox in
MyComboxActionListener class. it's the same).
why is that happens , I can't figure it out. Since It's totally a new
comboBox and a new listener when I add one line.
Following is the code.
Thanks in advance.
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();
}
}
No comments:
Post a Comment