2

My current project is some kind of a database system that has a gui for maintenance. Before my major code rewrite, I used to serialize and de-serialize the TableModel to save and load data to the gui. Because this was not a good solution for obvious reasons I did some research and ended up using an H2 (local) database to save and load my data from.

The code used to save the data into my database can be found in my other question.

The save process itself is not the biggest problem but I can't find any good way to load the data back into my JTable (TableModel).

Is there any way to directly wire JTable (TableModel) together with any kind of SQL database? Currently using JTable with a database seems to be a really big hassle with Java.

Community
  • 1
  • 1
Flatron
  • 1,375
  • 2
  • 12
  • 33
  • You're looking for a bindings API of some kind. This will depend on a lot of factors – MadProgrammer Sep 14 '15 at 06:40
  • This might be, I would appreciate anything to make the connection easier while I am no full fledged programmer as an electrical engineer. – Flatron Sep 14 '15 at 06:42
  • 1
    @Flatron look at [this question](http://stackoverflow.com/questions/10620448/most-simple-code-to-populate-jtable-from-resultset) and the solutions therein – hd1 Sep 14 '15 at 06:54

1 Answers1

4

Okay, so this is a simple example, which creates a in-memory database, with a single table and some values.

It uses a simple custom TableModel which can be "refreshed" if the underlying data is changed.

Have a closer look at JDBC Database Access for some more details

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;

public class TestTable {

    private Connection con;

    public static void main(String[] args) {
        new TestTable();
    }

    public TestTable() {
        try {
            Class.forName("org.h2.Driver");
            String url = "jdbc:h2:mem:InMemoryTest";
            con = DriverManager.getConnection(url);

            createShoppingListTable();
            fillShoppingListTable();

            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        } catch (ClassNotFoundException | SQLException exp) {
            exp.printStackTrace();
        }
    }

    protected void createShoppingListTable() throws SQLException {
        String query = "create table shoppingList (id bigint identity, item varchar(255), quantity int)";
        try (Statement stmt = con.createStatement()) {
            stmt.execute(query);
        }
    }

    protected void fillShoppingListTable() throws SQLException {

        String[] items = {"Bananas", "Apples", "Grapes", "Pears", "Oranges"};
        Random rnd = new Random();
        try (PreparedStatement ps = con.prepareStatement("insert into shoppingList (item, quantity) values (?, ?)")) {
            for (String item : items) {
                ps.setString(1, item);
                ps.setInt(2, rnd.nextInt(100));
                ps.addBatch();
            }

            ps.executeBatch();
        }

    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new BorderLayout());
            TestTableModel model = new TestTableModel();
            JTable table = new JTable(model);
            add(new JScrollPane(table));

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        model.refresh();
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    }
                }
            });
        }

    }

    public class TestTableModel extends AbstractTableModel {

        private List<ShoppingList> shoppingList = new ArrayList<>(25);
        private List<String> columnNames = new ArrayList<>(25);

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

        @Override
        public int getColumnCount() {
            return columnNames.size();
        }

        @Override
        public String getColumnName(int column) {
            return columnNames.get(column);
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            ShoppingList rowValue = shoppingList.get(rowIndex);
            Object value = null;
            switch (columnIndex) {
                case 0:
                    value = rowValue.getId();
                    break;
                case 1:
                    value = rowValue.getItem();
                    break;
                case 2:
                    value = rowValue.getQuanity();
                    break;
            }
            return value;
        }

        public void refresh() throws SQLException {

            List<String> values = new ArrayList<>(25);
            try (PreparedStatement ps = con.prepareStatement("select * from shoppingList")) {
                try (ResultSet rs = ps.executeQuery()) {
                    ResultSetMetaData md = rs.getMetaData();
                    for (int col = 0; col < md.getColumnCount(); col++) {
                        values.add(md.getColumnName(col + 1));
                    }
                    while (rs.next()) {
                        ShoppingList list = new ShoppingList(rs.getLong(1), rs.getString(2), rs.getInt(3));
                        shoppingList.add(list);
                    }
                }
            } finally {
                if (columnNames.size() != values.size()) {
                    columnNames = values;
                    fireTableStructureChanged();
                } else {
                    fireTableDataChanged();
                }
            }

        }

        public class ShoppingList {

            private long id;
            private String item;
            private int quanity;

            public ShoppingList(long id, String item, int quanity) {
                this.id = id;
                this.item = item;
                this.quanity = quanity;
            }

            public long getId() {
                return id;
            }

            public String getItem() {
                return item;
            }

            public int getQuanity() {
                return quanity;
            }

        }

    }

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