简体   繁体   中英

Java Resultset and AbstractTableModel to update JTable

I'm a beginner, I have JTable that I want to fill with a Resultset that should change everytime a user enters a Search keyword in a TextField and then click the Search Button. I searched for a week now and I still don't know how to use the AbstratTableModel with my Resultset to show and refresh the JTable after every Search Button click.

here is the entire code :

view.CatalogueSWING.java

public class CatalogueSWING extends JFrame{


 JLabel jLabelMC = new JLabel("Key Word"); 
 JTextField jTextFieldMC = new JTextField(20); // The textfield that contains the search keyword
 JButton jButtonSearch = new JButton("Search");
 CatalogueBusiness ca; // the business class which contains the "SearchByKeyWord method"
 JTable table;
 JPanel pCenter;
 //---

 public CatalogueSWING() {
     ca = new CatalogueBusiness();

     JPanel pNorth = new JPanel();
     pNorth.setLayout(new FlowLayout());

     pNorth.add(jLabelMC);
     pNorth.add(jTextFieldMC);
     pNorth.add(jButtonSearch);

     pCenter = new JPanel();
     pCenter.setLayout(new BorderLayout());

     pCenter.add(table);

     this.setLayout(new BorderLayout());
     this.add(pCenter, BorderLayout.CENTER);
     this.setSize(900, 500);
     pCenter.add(new JScrollPane(table));
     this.add(pNorth, BorderLayout.NORTH);

     this.setDefaultCloseOperation(EXIT_ON_CLOSE);
     this.setVisible(true);

     jButtonSearch.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e)
            {
                String kw = jTextFieldMC.getText();
                table = new JTable(ca.SearchByKeyWord(kw)); // SearchByKeyWord(String kw) is the method in my CatalogueBusiness class in another package.
                pCenter.add(table);

                System.out.println("You clicked the button");
            }
        });  
 }

Here is the Business Class :

business.CatalogueBusiness.java :

@Override
    public List<Product> SearchByKeyWord(String kw) {
        List<Product> listProducts = new ArrayList<Product>();

    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB_TPJDBC","root","password");

        PreparedStatement ps = conn.prepareStatement("select * from PRODUCTS where NAME_PROD like ?");
        ps.setString(1, "%"+kw+"%");
        ResultSet rs = ps.executeQuery();

        while (rs.next()) {
            Productp = new Produit();
            p.setIdProduct(rs.getInt("ID_PROD"));
            p.setNomProduct(rs.getString("NAME_PROD"));
            p.setPrice(rs.getDouble("PRICE"));
            p.setQuantite(rs.getInt("QUANTITY"));

            listProducts.add(p);    
        } 

        //ps.close();
        //conn.close();

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

    return listProducts;
}

and here is the Product Class :

business.Product.java :

import java.io.Serializable;

public class Product implements Serializable {

    private int idProduct;
    private String nomProduct;
    private double price;
    private int quantity;


    public Produit(String nomProduct, double price, int quantity) {
        super();
        this.nomProduct = nomProduct;
        this.price = price;
        this.quantity = quantity;
    }
    public Product() {
        super();
    }
    // getters & setter ...
    // ...

and finally the AbsractTableModel

business.ProductModel.java

public class ProduitModel extends AbstractTableModel{

    @Override
    public int getColumnCount() {
    //....
}
@Override
public int getRowCount() {
    //...
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    //...
}
@Override
public String getColumnName(int column) {
//...
}

I stopped here, I don't know how to use the AbstractTableModel in my case, I searched a lot and I still have no idea how use it with my Resultset to keep updating the JTable everytime I click the "Search Button" with some Keyword in the Search TextField.

Thank you in advance.

Start by having a look at How to use tables for more details.

The TableModel provides a number of methods required by the JTable to make decisions about how best to display your data.

  • getRowCount , tells the table how many rows it has to display
  • getColumnCount , tells the table how many columns it has to display
  • getColumnName , tells the table what name a specific column has, this is displayed by the table header
  • getColumnClass , is used by the table to make decisions about which cell renderer/editor it should use in the case where a custom renderer is not supplied for the column
  • getValueAt , returns the value for a given cell (row/column)
  • setValueAt , requests that the model update the value for the given cell
  • isCellEditable , determines if the given cell can be edited or not

So, armed with that basic information, we can generate a simple TableModel which wraps a List of Product s, for example...

public static class ProductTableModel extends AbstractTableModel {

    protected static final String[] COLUMN_NAMES = {"id", "Name", "Price", "Quantity"};
    protected static final Class[] COLUMN_TYPES = {Integer.class, String.class, Double.class, Integer.class};
    private List<Product> products;

    public ProductTableModel(List<Product> products) {
        this.products = new ArrayList<>(products);
    }

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

    @Override
    public int getColumnCount() {
        return COLUMN_NAMES.length;
    }

    @Override
    public String getColumnName(int column) {
        return COLUMN_NAMES[column];
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        return COLUMN_TYPES[columnIndex];
    }

    protected Product getProductForRow(int row) {
        return products.get(row);
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Product product = getProductForRow(rowIndex);
        Object value = null;
        switch (columnIndex) {
            case 0:
                value = product.getIdProduct();
                break;
            case 1:
                value = product.getNomProduct();
                break;
            case 2:
                value = product.getPrice();
                break;
            case 3:
                value = product.getQuantity();
                break;
        }
        return value;
    }

}

Now, this is a pretty simple, non-editable example.

To use it, you would simply create a new ProductTableModel with the results from your SearchByKeyWord method and apply it to your already existing JTable ...

jButtonSearch.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)
    {
        String kw = jTextFieldMC.getText();
        table.setModel(new ProductTableModel(ca.SearchByKeyWord(kw)));
    }
});  

The table API is probably the third most complex API in the Swing library (with underlying text component and JTree API be more complex), but its bar far one of the most common things you will do. If you can get your head around it, you will find the rest of the API relatively simple (including coming to grips with the tree API ;))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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