【发布时间】:2011-03-08 11:47:28
【问题描述】:
以下是我编写的用于帮助执行以下操作的代码:
从要添加到 jTable 的 jComboBox 中进行选择,然后检查它满足以下三个条件中的哪一个:如果 table 为空,则添加它。如果从组合框中选择的项目存在于表中,则现有行的数量值增加一。或者,如果它还没有在桌子上,它就会被添加。
但我得到的是如下非常奇怪的行为:
第一行被添加到表中,值为“200”(应为“100”,因为在此选择之前表为空)。
从组合框中选择了第二个项目,第一行(上面)的值更改为“100”(这应该在第一次选择时发生)。此外,从组合框中选择的第二项被添加到表中两次(两个相同的行),值为“300”,值正确但应该只有一行。
combo 中的第三个选择和上面的 2 一样,所以值是正确的,但应该只有一行
选择组合框中的第四个选项,这次是为了匹配表中的现有行,而不是更新现有行中的值,它还添加了两个值为“300”的行。 .
我想也许我的循环错了,但我现在在试图解决这个问题的项目上远远落后,所以任何帮助都会得到很大的帮助......
提前致谢
final DefaultTableModel model = (DefaultTableModel)main.tillPanel.tblTillSale.getModel();
//populate the combo box
for (int d = 0; d < roundStockObj.length ; d++) {
main.tillPanel.cmbTillProdSelect.addItem(roundStockObj[d].getDescription());
}
//add selection listener to combo
main.tillPanel.cmbTillProdSelect.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
String[] addSelectedItem = new String[4];
selectedItem = main.tillPanel.cmbTillProdSelect.getSelectedItem();
for (int d = 0; d < roundStockObj.length; d++) {
//when selction form combo is matched, an array is created to hold the row data
if (roundStockObj[d].getDescription().equals(selectedItem)) {
addSelectedItem[0] = roundStockObj[d].getDescription();
addSelectedItem[2] = Double.toString(roundStockObj[d].getPrice()).trim();
addSelectedItem[3] = Double.toString(roundStockObj[d].getPrice()).trim();
}
}
main.tillPanel.tblTillSale.removeRowSelectionInterval(0, model.getRowCount());
//if table is empty
for (int rowCount = 0 ; rowCount <= model.getRowCount(); rowCount++) {
if (model.getRowCount() == 0 ) {
addSelectedItem[1] = "100";
model.addRow(new String[]{addSelectedItem[0], addSelectedItem[1], addSelectedItem[2], addSelectedItem[3]});
//main.tillPanel.tblTillSale.getModel().setValueAt(selectedItem, tillSelectedRow, tillSelectedRow);
main.tillPanel.lblTotPrice.setText("100");
break;
}
// look for duplicate row and if found increase total column of existing row, and not add this selection
if(addSelectedItem[0].equals(main.tillPanel.tblTillSale.getValueAt(rowCount, 0))) {
main.tillPanel.lblTotPrice.setText("200");
int currentValue = Integer.parseInt(addSelectedItem[1].trim());
addSelectedItem[1] = "200";
model.setValueAt(addSelectedItem[1], rowCount, 1);
break;
}
//if no duplicate found add this row to the table
else {
addSelectedItem[1] = "300";
model.addRow(new String[]{addSelectedItem[0], addSelectedItem[1], addSelectedItem[2], addSelectedItem[3]});
main.tillPanel.lblTotPrice.setText("300");
break;
}
}
//clear the current selection array of row data
for (int index = 0; index < 4; index++) {
ddSelectedItem[index] = null;
}
}
});
【问题讨论】:
标签: java swing jtable jcombobox