0

I am trying to create a checkout simulation for my coursework. So every time I search for an item I can retrieve it from the database and display it on the JTable. However, once I add an item to the list and try to add another item the old item get replaced by the new item.

I am trying to list all the item in the JTable, this is my code:

DBConnection db = new  DBConnection();
    try {

        ResultSet rs =  DBConnection.stmt.executeQuery("SELECT ID, MESSAGE FROM STOCK WHERE ID = '"+ id + "'"); 

        jTable1.setModel(DbUtils.resultSetToTableModel(rs));




    }
    catch (Exception e){
        System.out.println(e);

    }`
1ac0
  • 2,875
  • 3
  • 33
  • 47
Shah123
  • 23
  • 8
  • What list? What table? Consider providing a [runnable example](https://stackoverflow.com/help/mcve) which demonstrates your problem. This will result in less confusion and better responses – MadProgrammer Nov 05 '14 at 21:22
  • Don't use `DbUtils`, it's not doing you any favours. Instead, build a `TableModel`, which remain constant and add the new rows to from the `ResultSet`. See [How to Use Tables](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html) and [JDBC Database Access](http://docs.oracle.com/javase/tutorial/jdbc/) for more details – MadProgrammer Nov 05 '14 at 21:51

3 Answers3

1

The main problem is DbUtils.resultSetToTableModel(rs), which is creating a brand new TableModel, filled with the contents of the ResultSet, this, when applied to the JTable is replacing the view with the contents of the TableModel.

In order to be able to update the table, you need to update the existing TableModel...

There are a few ways this might be achieved, by the simplest might be to use a DefaultTableModel...

Start by creating a class instance field of a DefaultTableModel...

public class ... {
    //...
    private DefaultTableModel stockTableModel;
    //...

Then, when you want to load the stock items, you will need to initialise the model, if it's not already initialised, and then add the new results to it...

DBConnection db = new DBConnection();
try (ResultSet rs = DBConnection.stmt.executeQuery("SELECT ID, MESSAGE FROM STOCK WHERE ID = '" + id + "'")) {

    if (stockTableModel == null) {
        stockTableModel = new DefaultTableModel();
        for (int col = 0; col < metaData.getColumnCount(); col++) {
            stockTableModel.addColumn(metaData.getColumnName(col + 1));
        }
        jTable.setModel(model);
    }

    while (rs.next()) {
        Vector rowData = new Vector(metaData.getColumnCount());
        for (int col = 0; col < metaData.getColumnCount(); col++) {
            rowData.add(rs.getObject(col + 1));
        }
        stockTableModel.addRow(rowData);
    }

} catch (SQLException exp) {
    exp.printStackTrace();
}

Take a look at How to Use Tables and JDBC Database Access for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

You can create a custom data model that allows you to insert new rows to table.

lets say that you have class, that can hold your query result fields.

public class Item implements Comparable<Item> {

    private Long id;
    private String message;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String value) {
        this.message= value;
    }

    @Override
    public int compareTo(Item o) {
        return id.compareTo(o.id);
    }

}

and it needs to go to table, which has been defined somewhere like:

JTable table =new JTable();

this is a data model to your table

public class Model extends AbstractTableModel {

    private List<Item> items;

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

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

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

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        if (rowIndex > items.size() - 1 || rowIndex < 0) {
            return "";
        }
        final Item get = items.get(rowIndex);
        switch (columnIndex) {
            case 0:
                return get.getId();
            case 1:
                return get.getMessage();
        }
        return "";
    }

    @Override
    public String getColumnName(int column) {
        switch (column) {
            case 0:
                return "id";
            case 1:
                return "message";
        }
        return "";
    }

    public void addItem(Item i) {
        items.add(i);
        fireTableDataChanged();
    }

    public void addItem(ResultSet rs) {
        try {
            Item item = new Item();
            item.setId(rs.getLong("ID"));
            item.setMessage(rs.getString("MESSAGE"));
            items.add(item);
            fireTableDataChanged();
        } catch (SQLException ex) {
            Logger.getLogger(Model.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

now create field

Model myModel=new Model();

and set it as a table model

table.setModel(myModel);

now every time you need to add something to table, just use our table model (i created two methods to insert data public void addItem(Item i) and public void addItem(ResultSet rs).

this should work. If you need to clear table sometimes, just add pubic method public void clear() to your model, in which you will clear items list and call fireTableDataChanged();. It is necessary, otherwise GUI will not refresh.

EDIT

Your code should be like

    DBConnection db = new DBConnection();
    try {

        ResultSet rs = DBConnection.stmt.executeQuery("SELECT ID, MESSAGE FROM STOCK WHERE ID = '" + id + "'");

        myModel.add(rs);

    } catch (Exception e) {
        System.out.println(e);

    }
T.G
  • 1,913
  • 1
  • 16
  • 29
  • *"You have to create a custom data model "* - No you don't, you could use a `DefaultTableModel` - also your last example snippet doesn't meet up with your `TableModel` contract – MadProgrammer Nov 05 '14 at 23:02
  • @MadProgrammer well as it is just example, i didnt bother to work completely assuming, that intentions are clear. `DefaultTableModel` is also solution, but in my opinion custom model is much better. `DefaultTableModel` i consider as a fast prototype solution. But i will make adjustments, so it will be more suitable answer – T.G Nov 06 '14 at 01:39
  • Don't get me wrong, I normally prefer to start with `AbstractTableModel`...just saying it's not a *"have to"* situation and given the OPs apparent lack of knowledge, might be a little over there head...but what better time to learn to swing, then while you're drowning ;) – MadProgrammer Nov 06 '14 at 01:41
-1

Just add a row to your JTable Model every time you have your result...

refer to this SO question

 DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
        model.addRow(new Object[]{"Column 1", "Column 2", "Column 3"});

or in your case

DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
            model.addRow(new Object[]{searchResultData});
Community
  • 1
  • 1
phenom
  • 61
  • 4
  • its a specific, what i am trying to do is get the data from the database and add it to the JTable List but at the moment every time i search for an item from a text field it gets added to the JTable. however when i try to add another item to the JTable list it replaces the old one and shows the new one. but i want both of the items to be listed to the JTable. – Shah123 Nov 05 '14 at 21:26
  • how to display multiple data to a JTable instead of only one . if you look at my code you can see that i am using WHERE clause in my SQL statement. so every time i try to add a product it adds but it gets replaced when i try to add another one. – Shah123 Nov 05 '14 at 21:42
  • i have tried it already and keep getting this result in to one of the field of the table "org.apache.derby.client.net.NetResultSet42@7b06a956" – Shah123 Nov 05 '14 at 21:57
  • don't just put your resultSet in the table directly...try rs.getString("id") or something depending on your table specs. – phenom Nov 05 '14 at 22:41
  • Thank you so much for your help guys I have managed to sort it out – Shah123 Nov 06 '14 at 08:59