k4sia
k4sia

Reputation: 416

JTable fireTableDataChanged() method doesn't refresh table

After adding a row I expected JTable to be refreshed. Unfortunately it is not.

My code is like that:

How I add a row:

JButton btnDodaj = new JButton("Dodaj");`

panel.add(btnDodaj);

btnDodaj.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        int selectedOption = JOptionPane.showConfirmDialog(null, "Na pewno chcesz dodac nowy rekord?",
                "wybieraj", JOptionPane.YES_NO_OPTION);
        if (selectedOption == JOptionPane.NO_OPTION) {
            return;
        }
        dbHelper.dodajOsoba(editPaneName.getText(), editPaneNazw.getText(), formattedDataUr.getText(),
                (Enum) comboBoxStCyw.getSelectedItem(), (String) comboBoxZaw.getSelectedItem(),
                (String) comboBoxMia.getSelectedItem(), textFieldPesel.getText());
        simpleTableDemo.model.fireTableDataChanged();

    }
});

How I add simpleTableDemo to JPanel:

simpleTableDemo = new ListaOsob();
sl_panel.putConstraint(SpringLayout.NORTH, simpleTableDemo, 100, SpringLayout.SOUTH, comboBoxMia);
sl_panel.putConstraint(SpringLayout.WEST, simpleTableDemo, 33, SpringLayout.WEST, panel);
sl_panel.putConstraint(SpringLayout.EAST, simpleTableDemo, 617, SpringLayout.WEST, panel);
panel.add(simpleTableDemo);

Definition of SimpleTableDemo:

Object[][] data2 = dbHelper.wyswietlOsoba();
model = new DefaultTableModel(data2, columnNames);
table = new JTable(model);

EDIT:

My dodajOsoba method:

try {
        sql = "INSERT INTO osoba1 (imie, nazwisko, dataUrodzenia, stanCywilny, zawod, miasto, pesel) VALUES ('" + imie
                + "', '" + nazwisko + "','" + dataUrodzenia + "','" + stanCywilny + "','" + zawod + "','" + miasto
                + "','" + pesel +"');";
        ListaOsob lista = new ListaOsob();
        lista.model.addRow(new Object[]{imie, nazwisko, dataUrodzenia, stanCywilny,zawod,miasto,pesel});

        stmt.execute(sql);

    }

Row is added correctly but the JTable is not refreshing.

What did i miss?

Upvotes: 0

Views: 693

Answers (1)

camickr
camickr

Reputation: 324137

We can't tell what is wrong based on the code provide. All we can do is guess:

  1. We have no idea what the dodajOsoba method does although it is almost certainly wrong. If you want to change the data being displayed in the table then you need to update the data in the TableModel directly. So your code should be using the addRow(...) method of the DefaultTableModel to add a new row of data.

  2. You should never invoke fireTableDataChanged() in your application code. It is the job of the TableModel to invoke that method. The addRow(...) method of the DefaultTableModel will invoke the appropriate method for you.

Upvotes: 5

Related Questions