我制作了一个JComboBOx,其中展示了我销售的产品。当用户单击项目我在数组列表中搜索并返回一个Object时,我希望将信息放入二维数组中,之后我想将该二维数组添加到JTable的行中,但我是没有得到任何表格。 任何人可以帮助我从JComboBox中选择一个项目时如何在JTable中添加项目?
public void actionPerformed(ActionEvent arg0) {
String boughtThing = InventoryList.getSelectedItem().toString();
int NumberOfItems = Integer.parseInt(JOptionPane.showInputDialog("Enter the Number Item"));
ImplementInventoryServices service = new ImplementInventoryServices();
Inventory thing = service.searchInventory(boughtThing);
double price = thing.getPricePerUnit();
String nameOfProduct = thing.getInventoryName();
int stock = thing.getNumberOfInventory();
int IDofProduct = thing.getInventoryID();
subtotal = 0;
subtotal = price * NumberOfItems;
stock = stock - NumberOfItems;
data[0][0] = Double.toString(price);
data[0][1] = nameOfProduct;
data[0][2] = Integer.toString(NumberOfItems);
data[0][3] = Double.toString(subtotal);
info = new Information(price, nameOfProduct, IDofProduct, subtotal);
Inventory inventory = new Inventory(nameOfProduct, IDofProduct, price, stock);
ImplementInventoryServices updating = new ImplementInventoryServices();
updating.updateInventory(nameOfProduct, inventory);
subTotalList.add(subtotal);
DataHandlingForInventory.write();
}
});
String [] columns = {"ID","Name","Price Per Unit", "Sub Total"};
OrignalTable = new JTable(data,columns);
OrignalTable.setBounds(10, 119, 425, 219);
InvoiceMake.getContentPane().add(OrignalTable);
答案 0 :(得分:1)
试试这样:
创建一个DefaultTableModel
来保存您的数据并将其链接到表格:
Object [] columns = {"ID","Name","Price Per Unit", "Sub Total"};
tableModel = new DefaultTableModel(columns, 0);
OrignalTable = new JTable(tableModel);
现在您可以使用该模型(在您的类中定义为一个字段,以便您可以访问匿名ActionListener)来处理数据:
// before
// data[0][0] = Double.toString(price);
// data[0][1] = nameOfProduct;
// data[0][2] = Integer.toString(NumberOfItems);
// data[0][3] = Double.toString(subtotal);
// after
tableModel.addRow(new Object[]{Double.toString(price),
nameOfProduct,
Integer.toString(NumberOfItems),
Double.toString(subtotal)});
请务必阅读How to Use Tables
上的文件