简体   繁体   English

如何在JFrame刷新数据库查询?

[英]How to refresh a database query at JFrame?

good day! 美好的一天!

I am having a problem on showing the updated version of my database to a JTable frame... 我在将数据库的更新版本显示到JTable框架时遇到问题...

Everything inside my JFrame were just Generated, I just follow the instruction in this link: Binding JTable with MySQL JFrame内的所有内容均已生成,我只需按照此链接中的说明进行操作:将JTable与MySQL绑定

It works properly until, I added a new JFrame for the UPDATES of the Database, when I hit the button VIEW INVENTORY (JFrame that consist the JTable showing the data at MySQL), it doesn't show the updated version of the database. 直到我为数据库的更新添加了新的JFrame,然后单击“ 查看库存” (由JTable组成的JFrame,该JTable在MySQL上显示数据)后,它才能正常工作,它不会显示数据库的更新版本。

But, after closing the Application and run the ViewInventory JFrame.. it was already Updated. 但是,在关闭应用程序并运行ViewInventory JFrame之后,它已经更新了。

Please Help... this is the generated Code: 请帮助...这是生成的代码:

public class ViewInventory extends javax.swing.JFrame {

    public ViewInventory() {
        initComponents();
        setLocation(300, 120);
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        inventoryPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("inventoryPU").createEntityManager();
        itemsQuery = java.beans.Beans.isDesignTime() ? null : inventoryPUEntityManager.createQuery("SELECT i FROM Items i");
        itemsList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : itemsQuery.getResultList();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setAlignmentX(1.0F);
        jTable1.setAlignmentY(2.0F);
        jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        jTable1.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, itemsList, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${id}"));
        columnBinding.setColumnName("Id");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${itemName}"));
        columnBinding.setColumnName("Item Name");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${category}"));
        columnBinding.setColumnName("Category");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${QBox}"));
        columnBinding.setColumnName("QBox");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${unitPriceBox}"));
        columnBinding.setColumnName("Unit Price Box");
        columnBinding.setColumnClass(Double.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${subTotalBox}"));
        columnBinding.setColumnName("Sub Total Box");
        columnBinding.setColumnClass(Double.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${QPc}"));
        columnBinding.setColumnName("QPc");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${unitPricePc}"));
        columnBinding.setColumnName("Unit Price Pc");
        columnBinding.setColumnClass(Double.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${subTotalPc}"));
        columnBinding.setColumnName("Sub Total Pc");
        columnBinding.setColumnClass(Double.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${grandTotal}"));
        columnBinding.setColumnName("Grand Total");
        columnBinding.setColumnClass(Double.class);
        bindingGroup.addBinding(jTableBinding);

        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("Main Menu");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 514, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 329, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(14, 14, 14)
                .addComponent(jButton1)
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        new Menu().setVisible(true);
        setVisible(false);
    }                                        

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ViewInventory().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.persistence.EntityManager inventoryPUEntityManager;
    private java.util.List<inventory.Items> itemsList;
    private javax.persistence.Query itemsQuery;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration                   
}

I am sorry if I displayed everything at the generated code. 很抱歉,如果我在生成的代码中显示了所有内容。

and here's my EditItemDetails code: 这是我的EditItemDetails代码:

try {
            Class.forName(Connect.DRIVER);
            Connection con = DriverManager.getConnection(Connect.CONNECTION_STRING,
                    Connect.USERNAME, Connect.PASSWORD);

            Statement stat = con.createStatement();

            ResultSet rs = stat.executeQuery("SELECT id, category,"
                    + "q_box, unit_price_box, sub_total_box, q_pc, "
                    + "unit_price_pc, sub_total_pc, grand_total from items WHERE "
                    + "item_name = '" + item_name_combobox.getSelectedItem() + "';");

            String category;
            int q_box, q_pc;
            double unit_price_box, sub_total_box, unit_price_pc, sub_total_pc,
                    grand_total;

            if (rs.next()) {
                q_box = rs.getInt("q_box");
                category = rs.getString("category");
                unit_price_box = rs.getDouble("unit_price_box");
                sub_total_box = rs.getDouble("sub_total_box");
                q_pc = rs.getInt("q_pc");
                unit_price_pc = rs.getDouble("unit_price_pc");
                sub_total_pc = rs.getDouble("sub_total_pc");
                grand_total = rs.getDouble("grand_total");

                double new_sub_total_box = q_box * Integer.parseInt(new_unit_price_box_txtfld.getText());
                double new_sub_total_pc = q_pc * Integer.parseInt(new_unit_price_pc_txtfld.getText());
                grand_total = new_sub_total_box + new_sub_total_pc;

            stat.executeUpdate("UPDATE items SET unit_price_box = " + new_unit_price_box_txtfld.getText()
                    + ", unit_price_pc = " + new_unit_price_pc_txtfld.getText()
                    + ", sub_total_box = " + new_sub_total_box
                    + ", sub_total_pc = "+ new_sub_total_pc
                    + ", grand_total = "+ grand_total
                    + " WHERE item_name = '"
                    + item_name_combobox.getSelectedItem() + "';");

                sub_total_box_txtfld.setText(Double.toString(new_sub_total_box));
                sub_total_pc_txtfld.setText(Double.toString(new_sub_total_pc));
                grand_total_txtfld.setText(Double.toString(grand_total));

                lblmsg.setText("Record Saved!");

                con.close();
            }
        } catch (Exception e) {
            lblmsg.setText("Error: "+ e.getMessage());
            System.out.println("Error: "+ e.getMessage());
        }

Personally I dislike the Netbeans gui designer for a lot of reasons. 我个人出于很多原因不喜欢Netbeans gui设计器。 It's great for prototyping and small projects, terrible for big projects and going back in and doing maintenance. 这对原型和小型项目非常有用,对于大型项目以及重新进行维护很糟糕。 But that's a rant for another time. 但这是另一回事。

What's going wrong is that you're getting back a static List from the JPA query. 出问题的是,您正在从JPA查询中获取静态列表。 You need to have your GUI re-run the query after your edit event to get the updated list. 编辑事件后,需要让GUI重新运行查询以获取更新的列表。 The way I got this kind of thing working in the gui designer was to change the collection to an ObservableList in the "Custom Creation Code": 我在gui设计器中进行这种工作的方式是将集合更改为“自定义创建代码”中的ObservableList:

someList = Beans.isDesignTime() ? java.util.Collections.emptyList() : ObservableCollections.observableList(new ArrayList<Something>());

Then when I had a gui event that updated the JTable contents, I do something like: 然后,当我有一个可更新JTable内容的gui事件时,我将执行以下操作:

someList.clear();
someList.add(query.getResultList());

I'm doing it this way because I get the list via EJB remote session bean, and I did it a long time ago in about netbeans 6.5 or 7 (the last time I used the GUI designer to create a new form). 我这样做是因为我是通过EJB远程会话bean获得列表的,而我很久以前是在netbeans 6.5或7中做到的(上一次我使用GUI设计器创建新表单)。 Apparently now there is a " modifiableWrapper " and " observable " you can set on the query results. 显然,现在可以在查询结果上设置“ modifiableWrapper ”和“ observable ”。 That might do what you need, otherwise do it the manual way as above. 那可能会满足您的需求,否则请按照上面的手动方法进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM