Java - 单击按钮时将项目从 arraylist 添加到 JTable

Java - Adding items from arraylist to JTable when button clicked

我正在尝试为我的程序编写 GUI。我有一个 Product class,我在其中将产品的价格和名称存储在数组列表中。我还有一个 Order 数组列表,其中包含给每个 waiter.I 的订单,将我的所有产品放入 JComboBox 中,并为每个产品添加一个动作侦听器,以在通过更新 JLable 的文本单击时显示每个产品的价格。然后有一个 JSpinner 来获取产品的数量 selected。最后有一个“添加”按钮,我想用它来更新 Jtable 的产品名称及其数量和总价,同时将该产品添加到订单数组列表中。我不知道如何填充 JTable 并且无法从其他答案中理解太多,因为他们使用的是 netbeans。我想只使用一个简单的 JLabe,但我也无法理解如何更新文本并在我 select 并添加每个产品后向标签添加新行。你能解释一下我如何才能做到这一点吗?我的部分代码如下所示

box1.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        Product prod = (Product) box1.getSelectedItem();
        price.setText(String.valueOf(prod.getSellingPrice()));

        add.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int numbs = (Integer) spinner.getValue();
                for (int i = 0; i <= numbs; i++) {
                    order.addProduct(prod);
                }
                JLabel label = new JLabel();
                lists.add(label);
                label.setText(prod.getName() + " " + numbs + " " + numbs * prod.getSellingPrice());
            }
        });
    }
});

如果我对你的问题的理解正确,你需要在你的 gui 中有一个 JTable,它会在单击按钮时显示订单(或其他可能的数据)。

先table,我建议你去看看

https://docs.oracle.com/javase/tutorial/uiswing/components/table.html

因为他们很好地解释了 JTable 的使用。

无论如何,回答你的问题:

首先table,你必须创建一个table并将它添加到你的gui:

//creating a new JTable without any data and one column 'Orders'
//you might wanna declare the JTable before that, since it will be referred to in the refresh() method
JTable table = new JTable(new String[][]{{""}}, new String[]{"Orders"});
//creating a scrollpane to put the table in, in case the table data exeeds the table
JScrollPane scrollPane = new JScrollPane();
//here you would e.g. set the bounds of the scrollpane etc
scrollPane.setBounds(x,y,w,h)
//setting the table in the scrollpane
scrollPane.setViewportView(table);
//adding the scrollpane to your contentPane
contentPane.add(scrollPane);

现在你想刷新table,如果按下一个按钮,所以我会在按钮的actionlistener中引用以下方法:

//the method to refresh the table containing the orders (or possibly other data)
void refresh(List<String> orders) {
    //creating a new TableModel for the table
    DefaultTableModel model = new DefaultTableModel();
    //set the data in the model to the data that was given, new Object[]{0} points to the 1st column
    model.setDataVector(getDataVector(data), new Object[]{"Orders});
    //set the model of the table to the model we just created
    table.setModel(model);
}

由于model.setDataVecor()的第一个参数是行而不是列,所以必须将数据拟合列表作为数据向量,例如用下面的方法:

Object[][] getDataVector(List<String> data){
    Object[][] vector = new Object[data.size()][1];
    for(int i=0; i<data.size(); i++){
        vector[i][0] = data.get(i);
    }
    return vector;
 }