DefaultTableModel update BUG, How can I resolve it?

62 Views Asked by At

I hope you can help me!!! I have a JComboBox, when I click the button "search" a JTable appears. When I change the selection of the JComboBox and click "search" again, the table changes its model and shows me the new datas, but if I click in there, the old model appears again. The data are from a database by a query.

I try to use dtm.setRowCount(0) but didn't works. I have only one JTable and I use the same dtm (DefaultTableModel) for every query.


public class store extends JPanel{
    
    int WIDTH = 1000;
    int HEIGHT = 600;
    String[] columnnames = new String[] {"id", "type", "cost"};
    JComboBox jcb;
    JButton button;
    DataBaseConnection dbc = new DataBaseConnection();
    
    public store() {
        super();
        this.setVisible(true);
        this.setPreferredSize(new Dimension(WIDTH, HEIGHT));
        this.setBackground(new Color(224, 224, 224));
        
        
        GroupLayout gLayout = new GroupLayout(this);
        gLayout.setAutoCreateGaps(true);
        gLayout.setAutoCreateContainerGaps(true);
        this.setLayout(gLayout);
        
         this.jcb = new JComboBox();
         
         
         this.button=new JButton("Search");
         button.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent evt) {
                 showTable();
             }
         });
         
         try { 
                Connection conn;
                try {
                    Class.forName("org.postgresql.Driver");
                
                conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/Try", "postgres",
                        "******");
                String sql = "select distinct type from try";
                PreparedStatement ps = conn.prepareStatement(sql);
                ResultSet rs2 = ps.executeQuery();
                while (rs2.next()) {

                    String aS = rs2.getString(1);
                    jcb.addItem(aS);
                }

                conn.close();

            } catch (SQLException e) {
                // TODO Auto-generated catch block

                e.printStackTrace();
            }
         } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
         
         
         gLayout.setHorizontalGroup(gLayout.createSequentialGroup()
                 .addGap(400)
                 .addComponent(jcb).addGroup(
                    gLayout.createParallelGroup(GroupLayout.Alignment.CENTER).addComponent(button)

            )


            );
            gLayout.setVerticalGroup(gLayout.createSequentialGroup()
                    .addGap(250)
                    .addGroup(gLayout.createParallelGroup(GroupLayout.Alignment.CENTER).addComponent(jcb)
                            .addComponent(button)
                            )
                    .addGap(250)
                    

            );
        
        
    }
    
    public void showTable() {

        DefaultTableModel dtm = new DefaultTableModel();
        
        JTable t = new JTable();
        
        
        dtm.setColumnIdentifiers(columnnames);
        
        JScrollPane pane = new JScrollPane(t);
        pane.setBounds(25, 120, 850, 150);
        
        String ta = jcb.getSelectedItem().toString();

        try { 
            
            Class.forName("org.postgresql.Driver");
            Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/Try",
                    "postgres", "*****");
            PreparedStatement pstm = conn.prepareStatement(
                    "SELECT try.* FROM try WHERE type=?");
            pstm.setString(1, ta);
            ResultSet Rs = pstm.executeQuery();
            
            
            
            while (Rs.next()) {
                dtm.addRow(new Object[] { Rs.getString(1), Rs.getString(2), Rs.getString(3) });
            }

            conn.close();
            
            
            t.setModel(dtm);
            add(pane);      
                    
               
            
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        
        
        
        
    }
}
1

There are 1 best solutions below

2
g00se On

This is an example of how I treated an on-the-fly table model fill with lottery results some years ago. You can easily adapt the TableFiller class to get your results from the database:

import java.awt.EventQueue;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

import java.net.URL;

import java.util.List;
import java.util.Vector;
import java.util.Arrays;

import javax.swing.SwingWorker;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class LotteryResults extends JFrame {
    private static final String RESULTS_FILE = "https://www.national-lottery.co.uk/results/lotto/draw-history/csv";
    private static int NUM_SIGNIFICANT_FIELDS = 10;
    private JTable table;
    private DefaultTableModel tableModel;

    public void setGui() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        tableModel = new DefaultTableModel(new Vector<>(), makeColumnHeaders());
        table = new JTable(tableModel);

        JScrollPane sp = new JScrollPane(table);
        getContentPane().add(sp);
    }

    private Vector<String> makeColumnHeaders() {
        String headers = "Draw Date, Ball 1, Ball 2, Ball 3, Ball 4, Ball 5, Ball 6,  Bonus Ball, Ball Set, Machine";

        return new Vector<>(Arrays.asList(headers.split("\\s*,\\s*")));
    }

    public void start() {
        new TableFiller().execute();
    }

    public static void main(String[] args) {
        try {
            EventQueue.invokeAndWait(() -> {

                LotteryResults reader = new LotteryResults();
                reader.setGui();
                reader.setSize(600, 300);
                reader.setVisible(true);
                reader.start();
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private class TableFiller extends SwingWorker<Vector<Vector<String>>, Vector<String>> {
        @Override
        public Vector<Vector<String>> doInBackground() {
            Vector<Vector<String>> allRows = new Vector<>();
            String line = null;
            int rowCount = 0;
            try (BufferedReader in = new BufferedReader(new InputStreamReader(new URL(RESULTS_FILE).openStream()))) {

                while ((line = in.readLine()) != null) {
                    String[] tokens = line.split("\\s*,\\s*");
                    rowCount++;

                    if (tokens.length >= NUM_SIGNIFICANT_FIELDS) {
                        Vector<String> row = new Vector<>();
                        for (int i = 0; i < NUM_SIGNIFICANT_FIELDS; i++) {
                            row.add(tokens[i]);
                        }
                        // Ignore header
                        if (rowCount > 1) {
                            publish(row);
                        }
                    }
                }
                System.out.printf("%d row(s) found%n", rowCount);

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

            return allRows;
        }

        @Override
        protected void process(List<Vector<String>> x) {
            for (int i = 0; i < x.size(); i++) {
                tableModel.addRow(x.get(i));
            }
        }
    }
}