Question

I'm not sure what I'm doing wrong but I get data from MySQL db and populate the JTable with DefaultTableModel. Then I show it on screen. After data is added from textboxes into the db, JTable wont refresh. I've checked the db and inserted data is there. I've tried with table.repaint() or dTableModel.fireTableDataChanged() in event listener for add button and still nothing. Here is the code:

public class DbTable {

    private JLabel lFirstName, lLastName, lState, lBirthDate;
    private JTextField fFirstName, tLastName, tState, tBirthDate;
    private JButton btnAdd;
    private Object[][] databaseResults;
    private Object[] columns = { "Col 1", "Col 2", "Col 3", "Col 4",
            "Col 5", "ЈCol 6", "Col 7" };
    private ResultSet rows;
    private ResultSet rowsCb;

    private JComboBox combobox;


    private DefaultTableModel dTableModel = new DefaultTableModel(
            databaseResults, columns) {
        public Class getColumnClass(int column) {
            Class returnValue; 

            if ((column >= 0) && (column < getColumnCount())) {
                returnValue = getValueAt(0, column).getClass();
            } else { 
                returnValue = Object.class;
            }
            return returnValue;
        }
    };

    private JTable table = new JTable(dTableModel);
    Connection conn = null;
    public static void main(String[] args) {
        DbTable dbTable = new DbTable();

        dbTable.getTable();
    }

    public void getTable() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);



        try {
            Class.forName("com.mysql.jdbc.Driver");

            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost/database", "root", "");

            Statement sqlState = conn.createStatement(
                    ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_UPDATABLE);

            String selectStuff = "SELECT  `invoice`.`id` ,  `client`, `date`, `project`, `amount`,`unitPrice`, `total`"
                    + "FROM  `invoice` ,  `clients`"
                    + "WHERE  `invoice`.`clientID` =  `clients`.`id`"
                    + "ORDER BY  `invoice`.`id` ASC ";

            rows = sqlState.executeQuery(selectStuff);

            Object[] tempRow;

            while (rows.next()) {
                tempRow = new Object[] { rows.getInt(1), rows.getString(2),
                        rows.getString(3), rows.getString(4), rows.getInt(5),
                        rows.getInt(6), rows.getDouble(7) };
                dTableModel.addRow(tempRow);

            }

        } catch (SQLException e) {
            e.getMessage();
        } catch (ClassNotFoundException e) {
            e.getMessage();
        }

        table.setFont(new Font("Tahoma", Font.PLAIN, 14));
        table.setAutoCreateRowSorter(true);

        JScrollPane scrollPane = new JScrollPane(table);
        // frame.add(combobox, BorderLayout.NORTH);

        frame.add(scrollPane, BorderLayout.NORTH);
        // Define values for my labels
        lFirstName = new JLabel("Klijent ID: ");
        lLastName = new JLabel("Datum: ");
        lState = new JLabel("Projekat: ");
        lBirthDate = new JLabel("Ukupno"); // Define the size of text fields
        fFirstName = new JTextField(10);
        tLastName = new JTextField(10);
        tBirthDate = new JTextField(10);
        tState = new JTextField(10);
        btnAdd = new JButton("Add");

        btnAdd.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String sDatum = "", sProjekat = "";
                int sKlijenId;
                double sUkupno = 0.00;
                sKlijenId = Integer.parseInt(fFirstName.getText());
                sDatum = tLastName.getText();
                sProjekat = tState.getText();
                sUkupno = Double.parseDouble(tBirthDate.getText());

                try {
                    Class.forName("com.mysql.jdbc.Driver");

                    conn = DriverManager.getConnection(
                            "jdbc:mysql://localhost/sjajplusz", "root", "");

                    Statement sqlState = conn.createStatement(
                            ResultSet.TYPE_SCROLL_SENSITIVE,
                            ResultSet.CONCUR_UPDATABLE);

                    String selectStuff = "SELECT * FROM invoice";

                    rows = sqlState.executeQuery(selectStuff);

                    rows.moveToInsertRow();
                    rows.updateInt("clientID", sKlijenId);
                    rows.updateString("date", sDatum);
                    rows.updateString("project", sProjekat);
                    rows.updateDouble("total", sUkupno);

                    rows.insertRow();
                    rows.updateRow();

                } catch (SQLException e1) {
                    e1.getMessage();
                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                int invoiceId = 0;

                try {
                    rows.last();
                    invoiceId = rows.getInt(1);
                } catch (SQLException e) {
                    e.getMessage();
                }


//              Object[] invoice = {invoiceId, sKlijenId, sDatum, sProjekat, "", "", sUkupno};
//              
//              dTableModel.addRow(invoice);

                dTableModel.fireTableDataChanged();

            }
        });

        JPanel inputPanel = new JPanel(); // Put components in the panel
        inputPanel.add(lFirstName);
        inputPanel.add(fFirstName);
        inputPanel.add(lLastName);
        inputPanel.add(tLastName);
        inputPanel.add(lState);
        inputPanel.add(tState);
        inputPanel.add(lBirthDate);
        inputPanel.add(tBirthDate);
        inputPanel.add(btnAdd);

        frame.add(inputPanel, BorderLayout.SOUTH);

        // frame.add(scrollPane, BorderLayout.CENTER);
        frame.setSize(500, 400);
        frame.setVisible(true);

        try {
            conn.close();
        } catch (SQLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}

Basically this is follow up on this youtube series Java JTable 38

Was it helpful?

Solution

You are not reloading the data from the database. After you have added it to the database you have to reload the data, refresh your DefaultTableModel and then call fireTableDataChanged(). You are doing this only initially in your getTable() method. You have to extract that code which loads your data and call it in your action listener.

Btw. your code is not very well organized even the way you are inserting the data is a bit complicated. I would suggest to take some basic tutorials about this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top