JTable单击JButton时不会填充 [英] JTable Won't populate when clicking JButton

查看:59
本文介绍了JTable单击JButton时不会填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发的系统是一个系统, JTable 充当 orderList 。我试过 Vector 我试过用 DefaultTableModel 但是我不知道如何制作按钮拉取数据并将其添加到表中。我知道这很难遵循,但任何人都可以告诉我如何为一个 JButton 做这个,然后其余的应该是类似的,我可以自己做吗?

The system I'm developing is a till system and the JTable acts as the orderList. I've tried Vector and I've tried to use DefaultTableModel but I'm not sure how to make the button pull the data and for it to add to the table. I know that this is quite hard to follow but could anyone maybe show me how I should do it for one JButton and then the rest should be similar, I can do those myself?

我需要 productID productName 价格将从数据库中提取并添加到表格中。

I need productID, productName and Price to be pulled from DB and added to table.

然后,我将汇总价格并为订单付款。

I will then total the price and take payment for the order.

//Order class for setting up and managing an order

package classes;

import java.sql.*;
import java.util.ArrayList;
import java.util.Vector;

public class Order 
{
    // Instance Variables
        private int productID;
        private String productName;
        private String productDescription;
        private String type;
        private String supplierName;
        private double quantity;
        private double price;

    // Connection To DB
    // JDBC Driver name and database URL
        final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        final String DB_URL = "jdbc:mysql://localhost/team_project?useSSL=false";
        final String USER_NAME = "root";
        final String PASSWORD = "password";

        // sql variables
        ResultSet resultSet = null;
        private String itemName;
        private double itemPrice;

    // Constructors
    public Order()
    {

    }

    public Order(int productID, String itemName, double itemPrice, double quantity)
    {
        this.itemName = itemName;
        this.itemPrice = itemPrice;
        this.quantity = quantity;
    }


    // Get the details of stock items and add them to the order
    public Vector getOrderItems()
    {
         ResultSet rs = null;

        Statement statement = null;
        try{

            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = (Connection) DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);
            Statement stmt = conn.createStatement();
            String sqlString= "select ProductID, ProductName, Price from product";
            stmt.executeUpdate(sqlString);  
            Vector vector = new Vector();
            Vector<String> orderItem = new Vector<String>();
            int i=0;
            while(rs.next())
            { 
                Vector<String> items = new Vector<String>();
                rs.getInt("ProductID");
                rs.getString("ProductName");
                rs.getDouble("Price");
            }
            return vector;
            }catch(Exception e)
            {
                e.printStackTrace();
            }
        return null;    
    }


         // Getter Methods
            public int getProductID()
            {
                return productID;
            }

            public String getProductName()                                  
            {
                return productName;
            }

            public String getProductDesc()
            {
                return productDescription;
            }

            public String getType()
            {
                return type;
            }

            public String getSupplierName()
            {
                return supplierName;
            }

            public double getQuantity()
            {
                return quantity;
            }

            public double getPrice()
            {
                return price;
            }
        }



股票



Stock

// Stock class
//Team Project
//Stock class for setting up and managing stock

package classes;

import java.sql.*;
import java.util.*;

public class Stock 
{
    // Instance Variables
    private int productID;
    private String productName;
    private String productDescription;
    private String type;
    private String supplierName;
    private double quantity;
    private double price;




    // JDBC Driver name and database URL
    final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    final String DB_URL = "jdbc:mysql://localhost/team_project?useSSL=false";
    final String USER_NAME = "root";
    final String PASSWORD = "password";


    // sql variables
    Statement statement = null;
    ResultSet resultSet = null;

    public Stock()
    {
        productID=0;
        productName=null;
        productDescription = null;
        type = null;
        supplierName=null;      
        quantity = 0;
        price=0;
    }

    // Initialisation Constructor that initializes everything in DB
    public Stock(int productID, String productName, String productDescription, String type, String supplierName,
                double quantity, double price)
    {
        this.productID = productID;
        this.productName = productName;
        this.productDescription = productDescription;
        this.type = type;
        this.supplierName = supplierName;
        this.quantity = quantity;
        this.price = price;
    }



    // Add a new product into the product table
    public void addProduct(int prodID, int amt) 
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = (Connection) DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);

            Statement stmt = conn.createStatement();
            String sqlString="insert into product " + "(ProductID, ProductName, ProductDescrp, type, SupplierName, Quantity, Price)"
            + " values(30, 'Marmalade', 'Homestead', 'Extras', 'Bakersworld', 20, 0.20)";
            stmt.executeUpdate(sqlString);
            conn.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    // Delete a product from the product table
    public void delete(int prodNumIn)
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = (Connection) DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);

            Statement stmt = conn.createStatement();
            String sqlString= "delete from team_Project.product where ProductID=" + prodNumIn;
            stmt.executeUpdate(sqlString);  
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    // Subtracts quantity in stock in the DB When a sale is made on an item
    public int deductStock(int prodID) 
    {
        int status =0;
          String sql = ("UPDATE product " + "SET Quantity = " + (getDBQuantity(prodID)-1) + " WHERE ProductID = " + prodID);
          status = databaseUpdate(sql);
          return status;
    }

    // Add quantity to particular product in the DB if required
    public int addToQuantity(int prodID, int amt) 
    {
        int status =0;
        String sql = ("UPDATE product " + "SET Quantity = " + (getDBQuantity(prodID)+ amt) + " WHERE ProductID = " + prodID);
        status = databaseUpdate(sql);
        return status;

    }

    // return quantity of a product in DB
    public int getDBQuantity(int prodID)
    {
        int quantity=0;
        try
        {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = (Connection) DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);

        statement = (Statement) conn.createStatement();
        resultSet = statement.executeQuery("select Quantity from team_project.product WHERE ProductID = " + prodID);

        while (resultSet.next())
        {       
            quantity = (resultSet.getInt("Quantity"));
        }
        conn.close();
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        return quantity;
        }


    // get price of a particular product 
    public int getItemPrice(int prodID)
    {
        int price = 0;      

        try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = (Connection) DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);

            statement = (Statement) conn.createStatement();
            resultSet = statement.executeQuery("select Price from team_project.product WHERE ProductID = " + prodID);

        while (resultSet.next())
        {       
            price = (resultSet.getInt("Price"));
        }
        conn.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        System.out.println("€"+price);
        return price;
        }



    // Method that returns all products in product table
    public ArrayList<Stock> getProducts()
    {
        ArrayList<Stock> allStock = new ArrayList<Stock>();

    try
    {
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = (Connection) DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);

    statement = (Statement) conn.createStatement();
    resultSet = statement.executeQuery("select * from team_project.product");

    while (resultSet.next())
    {       
        Stock  stock = new Stock(resultSet.getInt("ProductID"), resultSet.getString("ProductName"), 
                resultSet.getString("ProductDescrp"),resultSet.getString("Type"),resultSet.getString("SupplierName"), 
                resultSet.getInt("Quantity"), resultSet.getDouble("Price"));
        allStock.add(stock);
    }
    conn.close();

    }catch(Exception e)
    {
        e.printStackTrace();
    }
    return allStock;
    }

    // update method to call
    // database update method 
         private int databaseUpdate(String sqlUpdate)
         {
              int status = 0;

              try{
                 Class.forName("com.mysql.jdbc.Driver");
                 Connection conn = (Connection) DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);
                 statement = conn.createStatement();
                 status = statement.executeUpdate(sqlUpdate);
                 conn.close(); 
              }       

              catch (Exception e) {
                 e.printStackTrace();
              }   
              return status;
           }

         // toString method for stock items
         public String toString()
         {
             return productName + "";
         }



    // Getter Methods
    public int getProductID()
    {
        return productID;
    }

    public String getProductName()                                  
    {
        return productName;
    }

    public String getProductDesc()
    {
        return productDescription;
    }

    public String getType()
    {
        return type;
    }

    public String getSupplierName()
    {
        return supplierName;
    }

    public double getQuantity()
    {
        return quantity;
    }

    public double getPrice()
    {
        return price;
    }
}

// Small Americano Listener

// Small Americano Listener

americanoSmall.addActionListener(
        new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                try {
                    String query = "select ProductName, Price from product where ProductID = 24";
                    java.sql.PreparedStatement pst = connection.prepareStatement(query);
                    ResultSet rs = pst.executeQuery();
                    table.setModel(DbUtils.resultSetToTableModel(rs));

                    } catch (Exception e1) 
                    {
                        e1.printStackTrace();
                    }
                }
            });    


推荐答案

你的代码有点偏斜,你有一个股票对象,但该对象似乎也在管理数据库,作为一个更长期的解决方案,我建议将这些问题分开,但是现在我们将把它留给时间过了。

You code is a little skewed, you have a Stock object, but that object seems to be also managing the database, as a more long term solution, I would recommend separating those concerns, but for now we'll leave that for the time been.

我要做的第一件事是定义模型的期望,你期望它做什么,你期望它如何工作

The first thing I would do is define the expectations of the model, what do you expect it to do, how do you expect it to work

public interface MutableStockModel {
    public void add(Stock item) throws ModelException;
    public void remove(Stock item) throws ModelException;
}

所以这是一个简单的界面,定义了几个任何实现类的动作预计将提供。但你为什么这么问?这是一个很好的问题,我很快就会回答。

So this is a simple interface which defines a couple of actions which any implementing class is expected to provide. But why you ask? That's a good question I'll answer shortly.

你可以从 MutableStockModel > TableModel ,但这会将您锁定在某个特定的实施渠道中,这可能无法满足您的长期需求,此外,任何使用它的人都关心什么,他们只是希望能够添加和删除产品

You could extend the MutableStockModel from a TableModel, but that locks you into a particular implementation channel which may not meet your long term needs, besides, what does any one using it care, they just want to be able to add and remove products

示例实现...

public class DefaultStockTableModel extends AbstractTableModel implements MutableStockModel {

    private List<Stock> items;

    public DefaultStockTableModel() {
        items = new ArrayList<>(25);
    }

    public DefaultStockTableModel(List<Stock> items) {
        this.items = items;
    }

    @Override
    public int getRowCount() {
        return items.size();
    }

    @Override
    public int getColumnCount() {
        return 7;
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        switch (columnIndex) {
            case 1:
            case 2:
            case 3:
            case 4: return String.class;
            case 0:
            case 5:
            case 7: return int.class;
        }
        return Object.class;
    }

    @Override
    public String getColumnName(int column) {
        switch (column) {
            case 0: return "ID";
            case 1: return "Name";
            case 2: return "Description";
            case 3: return "Type";
            case 4: return "Supplier Name";
            case 5: return "Quanity";
            case 6: return "Price";
        }
        return null;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Stock item = items.get(rowIndex);
        switch (columnIndex) {
            case 0: return item.getProductID();
            case 1: return item.getProductName();
            case 2: return item.getProductDesc();
            case 3: return item.getType();
            case 4: return item.getSupplierName();
            case 5: return item.getQuantity();
            case 6: return item.getPrice();
        }
        return null;
    }

    @Override
    public void add(Stock item) throws ModelException {
        // Add the item to the database if required
        items.add(item);
        int row = items.indexOf(item);
        fireTableRowsInserted(row, row);
    }

    @Override
    public void remove(Stock item) throws ModelException {
        if (items.contains(item)) {
            // Delete theitem from the database if required
            int row = items.indexOf(item);
            items.remove(row);
            fireTableRowsDeleted(row, row);
        }
    }

}

所以这个是一个基本的例子,你的代码都不关心它是如何实际管理的,只是它符合合同要求。

So this is basic example, none of your code cares how it's actually managed, only that it meets the contractual requirements.

要添加或删除产品,只需调用特定方法即可。

To add or remove a product, simply call the specific methods.

现在,您可以扩展此概念,使其更易于使用,例如......

Now, you can expand this concept to make it easier to use, for example...

public interface MutableStockTableModel extends MutableStockModel, TableModel {
    public void removeAt(int row) throws ModelException;
}

这是一个特定的,有针对性的实现,它允许你删除一行一个特定的行。这扩展了 TableModel ,因为 TableModel 有一个行的概念,其中 MutableStockModel 没有。当然,你必须更新任何实现实现这个特定的接口;)

This is a specific, targeted implementation, which allows you to remove a row at a specific row. This extends TableModel, because a TableModel has a concept of "rows", which the MutableStockModel doesn't. Of course, you'd have to update any implementations implement this particular interface ;)

好的,但为什么?

根据数据库,简短的答案是 ResultSet 实际上可以直接变异,也就是说,你可以直接通过 ResultSet 添加/插入,删除和更新行,参见从结果集中检索和修改值以获取更多详细信息。

The short answer is, depending on the database, the ResultSet can actually be mutated directly, that is, you can add/insert, remove and update rows directly via the ResultSet, see Retrieving and Modifying Values from Result Sets for more details.

这意味着您可以创建一个 TableModel 的实现,它实现 MutableStockTableModel MutableStockModel 接口,但它引用了原始 ResultSet 作为内部结构。

This means you could create an implementation of a TableModel which implements the MutableStockTableModel or MutableStockModel interfaces but which took a reference to the original ResultSet as it's internal structure.

听起来很简单,但是当你意识到你可以改变 TableModel 的任何实例来满足任何实现在不影响任何代码的情况下实现需求,它开启了大量的可能性。

Sounds, simple, but when you realise you can change any instance of the TableModel for any implementation which meet the implementation requirements without affecting any of your code, it opens up a swagger of possibilities.

因此,例如,而不是使用 TableModel DefaultTableModel 在您的代码中,您可以使用

So, for example, instead of using TableModel or DefaultTableModel in your code, you might use

private MutableStockTableModel tableModel;

//...

tableModel = new ResultSetMutableStockTableModel(resultSet);
table.setModel(tableModel);

//...

tableModel.add(stockItem);

但您只需更改 tableModel 即可另一个实例...

But you could simply change the tableModel for a different instance...

tableModel = new DefaultStockTableModel(listOfItems);

并且没有其他任何需要改变的地方!

and nothing else needs to change!

所以,这是编码到接口,而不是实现的基本示例,我可以进一步解耦代码,但我不想压倒你;)

So, this is basic example of "coding to interface, not implementation" and I could decouple the code further, but I don't want to overwhelm you ;)

回到我的第一条评论,OO推广单一责任原则,这意味着任何对象应该只有一个责任(或工作)。

Going back to my first comment, OO promotes the Single Responsibility Principle, meaning that any object should have a single responsibility (or job).

这可能表明,例如,你应该分开你的股票的功能 class。

This might suggest that, for example, you should separate the functionality of your Stock class.

我的开头,惊喜,一个界面 .. 。

My, I'd start with, surprise, a interface...

public interface Stock {
    public int getProductID();
    public String getProductName();
    public String getProductDesc();
    public String getType();
    public String getSupplierName();
    public double getQuantity();
    public double getPrice();
}

然后你会有某种实现......

And then you'd have some kind of implementation...

public class DefaultStock implements Stock {
    // Instance Variables

    private int productID;
    private String productName;
    private String productDescription;
    private String type;
    private String supplierName;
    private double quantity;
    private double price;

    public DefaultStock() {
        productID = 0;
        productName = null;
        productDescription = null;
        type = null;
        supplierName = null;
        quantity = 0;
        price = 0;
    }

    // Initialisation Constructor that initializes everything in DB
    public DefaultStock(int productID, String productName, String productDescription, String type, String supplierName,
                             double quantity, double price) {
        this.productID = productID;
        this.productName = productName;
        this.productDescription = productDescription;
        this.type = type;
        this.supplierName = supplierName;
        this.quantity = quantity;
        this.price = price;
    }

    // toString method for stock items
    @Override
    public String toString() {
        return productName + "";
    }

    // Getter Methods
    @Override
    public int getProductID() {
        return productID;
    }

    @Override
    public String getProductName() {
        return productName;
    }

    @Override
    public String getProductDesc() {
        return productDescription;
    }

    @Override
    public String getType() {
        return type;
    }

    @Override
    public String getSupplierName() {
        return supplierName;
    }

    @Override
    public double getQuantity() {
        return quantity;
    }

    @Override
    public double getPrice() {
        return price;
    }
}

然后你可能有某种经理/控制器/ factory ...

And then you might have some kind of manager/controller/factory...

(是的,我很想通过某种界面来描述这个,但这已经很长了)

(And yes, I'd be tempted to describe this through some kind of interface, but this is already a long post)

public class StockManager {

    // JDBC Driver name and database URL
    final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    final String DB_URL = "jdbc:mysql://localhost/team_project?useSSL=false";
    final String USER_NAME = "root";
    final String PASSWORD = "password";

    // sql variables
    Statement statement = null;
    ResultSet resultSet = null;

    // Add a new product into the product table
    public void addProduct(int prodID, int amt) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = (Connection) DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);

            Statement stmt = conn.createStatement();
            String sqlString = "insert into product " + "(ProductID, ProductName, ProductDescrp, type, SupplierName, Quantity, Price)"
                    + " values(30, 'Marmalade', 'Homestead', 'Extras', 'Bakersworld', 20, 0.20)";
            stmt.executeUpdate(sqlString);
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Delete a product from the product table
    public void delete(int prodNumIn) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = (Connection) DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);

            Statement stmt = conn.createStatement();
            String sqlString = "delete from team_Project.product where ProductID=" + prodNumIn;
            stmt.executeUpdate(sqlString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Subtracts quantity in stock in the DB When a sale is made on an item
    public int deductStock(int prodID) {
        int status = 0;
        String sql = ("UPDATE product " + "SET Quantity = " + (getDBQuantity(prodID) - 1) + " WHERE ProductID = " + prodID);
        status = databaseUpdate(sql);
        return status;
    }

    // Add quantity to particular product in the DB if required
    public int addToQuantity(int prodID, int amt) {
        int status = 0;
        String sql = ("UPDATE product " + "SET Quantity = " + (getDBQuantity(prodID) + amt) + " WHERE ProductID = " + prodID);
        status = databaseUpdate(sql);
        return status;

    }

    // return quantity of a product in DB
    public int getDBQuantity(int prodID) {
        int quantity = 0;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = (Connection) DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);

            statement = (Statement) conn.createStatement();
            resultSet = statement.executeQuery("select Quantity from team_project.product WHERE ProductID = " + prodID);

            while (resultSet.next()) {
                quantity = (resultSet.getInt("Quantity"));
            }
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return quantity;
    }

    // get price of a particular product 
    public int getItemPrice(int prodID) {
        int price = 0;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = (Connection) DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);

            statement = (Statement) conn.createStatement();
            resultSet = statement.executeQuery("select Price from team_project.product WHERE ProductID = " + prodID);

            while (resultSet.next()) {
                price = (resultSet.getInt("Price"));
            }
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("€" + price);
        return price;
    }

    // Method that returns all products in product table
    public ArrayList<Stock> getProducts() {
        ArrayList<Stock> allStock = new ArrayList<Stock>();

        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = (Connection) DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);

            statement = (Statement) conn.createStatement();
            resultSet = statement.executeQuery("select * from team_project.product");

            while (resultSet.next()) {
                Stock stock = new DefaultStock(resultSet.getInt("ProductID"), resultSet.getString("ProductName"),
                                                                resultSet.getString("ProductDescrp"), resultSet.getString("Type"), resultSet.getString("SupplierName"),
                                                                resultSet.getInt("Quantity"), resultSet.getDouble("Price"));
                allStock.add(stock);
            }
            conn.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return allStock;
    }

    // update method to call
    // database update method 
    private int databaseUpdate(String sqlUpdate) {
        int status = 0;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = (Connection) DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);
            statement = conn.createStatement();
            status = statement.executeUpdate(sqlUpdate);
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return status;
    }

}

我也鼓励你看一下使用准备好的语句来改进整体代码

I'd also encourage you to have a look at Using Prepared Statements to improve the code overall

这篇关于JTable单击JButton时不会填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆