简体   繁体   中英

Updating a JTable with database query

The program I am working on contains two classes, GUI & DatabaseHelper. The table model used is DefaultTableModel.

The GUI contains consists of a simple JTable. It is initialised with data from the DatabaseHelper on startup. This works.

However, when trying to load new data into the table, it is not quite so straight forward.

My approach thus far has been:

model = DatabaseHelper.LoadData() // returns a default table model with new data.
tabel = new JTable();
tabel.setModel();

What happens now is that the loaded data is appended onto the already existing JTable.

If it is possible I would like to implement a solution using only the default table model. Thank you for any suggestions!

EDIT:

public void initGUI(){

        setJMenuBar(makeMenuBar()); 
        container   = new JPanel(new BorderLayout());

        model = db.initialiseTable();       // Load initialisation data from the database

        table = new JTable();
        table.setModel(model);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);
        scrollPane  = new JScrollPane(table);

        container.add(scrollPane, BorderLayout.CENTER); 
        add(container);
    }

Returning a new model from database:

public DefaultTableModel loadData(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/version1", "root", "root");
            System.out.println("\nDatabase Connection Established.\n");

            String query = "SELECT * FROM table WHERE test_number = 2";

            stmt        = con.createStatement();
            rs          = stmt.executeQuery( query );

            md          = rs.getMetaData();
            columns     = md.getColumnCount();  

            while (rs.next()) {
                Vector row = new Vector(columns);

                for (int i = 1; i <=columns-1; i++){
                row.addElement( rs.getObject(i+1) );
                }
                data.addElement( row );
            }
        }catch(SQLException e){
            e.printStackTrace();
        }catch(ClassNotFoundException e){
            e.printStackTrace();
        }

        columnNames.add(" ");
        columnNames.add("Column 1");
        columnNames.add("Column 2");

        DefaultTableModel model = new DefaultTableModel(data, columnNames);

        return model;
    }

ActionPerformed, code handles new model returned from the DatabaseHelper

            model = new DefaultTableModel();
            model = db.loadData();

            table = new JTable();
            table.setModel(model);

There is probably a bug in DatabaseHelper.LoadData() . For some reason, it doesn't create a new model but always returns the same model.

Create a new model in DatabaseHelper.LoadData() and it should work.

model = DatabaseHelper.LoadData() // returns a default table model with new data.
tabel = new JTable();
tabel.setModel();
  • there could be most important issue issue that you re_create TableModel and JTable , and this new JTable instance with TableModel isn't added to the GUI , don't do that, there no real reason to ...

  • search of ResulsetTableModel (there you pass only SQL Query ) or to use excelent code Table from Database by @camickr

First, it looks like you've got extra instantiations in the action handler:

        model = new DefaultTableModel();
        model = db.loadData();

        table = new JTable();
        table.setModel(model);

The loadData method instantiates a DefaultTableModel for you so you can skip the new DefaultTableModel and you already have a JTable from your initGui method so you should just reference that existing Component .

Now, it looks like you are only adding to the columnNames object. Perhaps you need to clear it or re-instantiate it each time through? If loadData will be called more than once it would be cleaner to create columnNames outside of the loadData method. Add " ", "Column 1" and "Column 2" there and only reference it inside loadData .

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