Java,如何从一帧中刷新另一帧中的JTable

标签 java swing jtable jframe actionlistener

所以我有一个 MainFrame 类,其中有一个 JTable,列出了存储在数据库中的所有产品。 JButton 在监听器的帮助下将打开 AddProduct(另一个类和另一个窗口/框架),我可以在其中在数据库中添加产品。不幸的是,我不太确定在 AddProduct 添加新产品并自动关闭后如何更新/重新验证 MainFrame 中的 JTable。 有人可以给我一些想法,我怎样才能轻松解决这个问题?

由于程序相当大,以下是其相关部分: 来自MainFrame.java

public JPanel tabProducts() {
    JPanel panel = new JPanel(new MigLayout("","20 [grow, fill] 10 [grow, fill] 20", "20 [] 10 [] 20"));

    /** Labels **/
    JLabel label = new JLabel("List of all available products");

    /** Buttons **/
    JButton add = new JButton("Add product");
    add.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            new AddProduct();
        }
    });
    JButton update = new JButton("Update product");
    update.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            new UpdateProduct(ps.getProductByID(15));
        }
    });

    /** TABLE: Products **/
    String[] tableTitle = new String[] {"ID", "Name", "Type", "Price", "In stock"};
    String[][] tableData = null;
    DefaultTableModel model = new DefaultTableModel(tableData, tableTitle);
    JTable table = null;
    /** Disable editing of the cell **/
    table = new JTable(model){
        public boolean isCellEditable(int r, int c) {
            return false;
        }
    };
    /** Load the products from DB **/
    List<Product> listInv = ps.getProductsByAtt(new ArrayList<String>());
    for (int i = 0; i < listInv.size(); i++) {
        model.insertRow(i, new Object[] {
                listInv.get(i).getID(),
                listInv.get(i).getName(),
                listInv.get(i).getType(),
                listInv.get(i).getPrice(),
                listInv.get(i).getQuantity()
        });
    }
    /** Add scroll pane **/
    JScrollPane scrollpane = new JScrollPane(table);

    /** Add everything to the panel **/
    panel.add(label, "wrap, span");
    panel.add(scrollpane, "wrap, span");
    panel.add(add);
    panel.add(update);

    return panel;
}

和AddProduct.java

public class AddProduct {

    private JFrame frame;
    private JButton add, cancel;
    private JRadioButton food, beverage;
    private JTextField name, price, quantity;
    private IProductService ps = new ProductService();
    private ButtonGroup group = new ButtonGroup();
    private Product p;
    private String type = "";

    public AddProduct() {
        /** Frame options **/
        frame = new JFrame("Add new product");
        frame.setSize(400, 280);
        frame.setMinimumSize(new Dimension(400, 280));
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

        /** Default panel **/
        final JPanel panel = new JPanel(new MigLayout("","20 [grow, fill] 10 [grow, fill] 20", "20 [] 10 [] 20"));

        /** Radio Buttons to choose between the food and the beverages **/
        food = new JRadioButton("Food");
        beverage = new JRadioButton("Beverage");
        group.add(food);
        group.add(beverage);
        food.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                type = "Food";
                frame.validate();
            }
        });
        beverage.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                type = "Beverage";
                frame.validate();
            }
        });

        /** Add everything to the panel **/
        panel.add(new JLabel("Product ID"));
        panel.add(new JLabel(Integer.toString(ps.getProductNr()+1)), "wrap, span 2");
        panel.add(new JLabel("Name"));
        panel.add(name = new JTextField(""), "wrap, span 2");
        panel.add(new JLabel("Type"));
        panel.add(food);
        panel.add(beverage, "wrap");
        panel.add(new JLabel("Price"));
        panel.add(price = new JTextField(""), "wrap, span 2");
        panel.add(new JLabel("Quantity"));
        panel.add(quantity = new JTextField(""), "wrap, span 2");


        /** Button: ADD **/
        add = new JButton("Add product");
        add.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                if ( !type.equals("Food") && !type.equals("Beverage")) {
                    JOptionPane.showMessageDialog(panel, "Please choose the type of this product.");
                } else if (name.getText().equals("")) {
                    JOptionPane.showMessageDialog(panel, "Please type a name for this product.");
                } else if (price.getText().equals("")) {
                    JOptionPane.showMessageDialog(panel, "Please enter the price for this product.");
                } else if (quantity.getText().equals("")) {
                    JOptionPane.showMessageDialog(panel, "Please enter the available amount of this product in stock.");
                } else {
                    try {
                        p = new Product(ps.getProductNr()+1, name.getText(), type, Double.parseDouble(price.getText()), Integer.parseInt(quantity.getText()));
                        if (ps.addProduct(p)) {
                            JOptionPane.showMessageDialog(panel, "Product successfully added!");
                            frame.validate();
                            frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
                        }
                    } catch (Exception ex) {
                        addFinalError();
                    }
                }
            }
        });

        /** Button: CANCEL **/
        cancel = new JButton("Cancel");
        cancel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
            }
        });

        /** Add buttons to the panel **/
        panel.add(cancel);
        panel.add(add, "span 2");

        /** Add panel to frame and make it visible **/
        frame.add(panel);
        frame.setVisible(true);

    }

    /**
     * In case more then one error is encountered
     */
    private void addFinalError(){
        JOptionPane.showMessageDialog(frame, "An error occured while adding the product. Please make sure the following is correct:\n\n" +
                " Name  : Can contain letters and numbers\n" +
                " Price  : Must be a number\n" +
                " Quantity  : Must be a whole number\n");
    }
}

最佳答案

您需要处理 JTable 模型部分,然后刷新、重新验证即可。 只需尝试一些 JTable 动态更新的示例,例如 create TableModel and populate jTable dynamically

关于Java,如何从一帧中刷新另一帧中的JTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9785560/

相关文章:

java - 如何在java swing中在屏幕上显示球

java - 有一个表模型。需要同时根据两个不同的列进行排序

java - 获取排序的 TableModel

java - 通过正则表达式进行 JTable 单元格验证

java - 如何将 Internet mime 消息的所有内容复制到 Notes 中的正文项?

java - 正则表达式要求一种字母和一种非字母并且没有空格

java - 当 Scanner 等待用户输入时 GUI 卡住

Java 表系统不工作

java - 如何在我自己的插件中访问常规 Eclipse 首选项

java - 将 ArrayList 制作成 JTable