user3307020
user3307020

Reputation: 15

how to make my JTable refresh after adding a new row

After I add a new row to a JTable. The information wrote goes to the txt file, but my JTable doesn't shows the last raw. But if I close the program, and run it again, the information it's in the table. So, is there a way to refresh the data in the JTable without closing the application and running it again?

String[] columns = {"nume", "compozitie", "indicatii", "contraindicatii", "administrare", "pret", "compensabil", "stoc"};

Object[][] data = null;
try {
    File file = new File("medicamente.txt");
    FileReader fileReader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    data = new Object[100][];
    String line;
    int numLines = 0;
    while ((line = bufferedReader.readLine()) != null) {
        data[numLines] = line.split(",");
        numLines++;
    }

    fileReader.close();

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

TableModel model = new DefaultTableModel(data, columns) {
    @Override
    public Class getColumnClass(int column) {
        Class returnValue;
        if ((column >= 0) && (column < getColumnCount())) {
            returnValue = getValueAt(0, column).getClass();
        } else {
            returnValue = Object.class;
        }
        return returnValue;
    }
};

JTable table = new JTable(model) {
    public boolean isCellEditable(int row, int column) {
        return false;
    }
};

final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
table.setRowSorter(sorter);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(1000, 500));
mainPanel.add(scrollPane);
scrollPane.setBounds(0, 240, 995, 510);

final JTextField filterText = new JTextField(null);
mainPanel.add(filterText);
filterText.setBounds(0, 750, 850, 25);

JButton button = new JButton("Filter");
mainPanel.add(button);
button.setBounds(850, 750, 150, 25);
button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        String text = filterText.getText();
        if (text.length() == 0) {
            sorter.setRowFilter(null);
            //   model.fireTableDataChanged();                       

        } else {
            sorter.setRowFilter(RowFilter.regexFilter(text));
        }
    }
});

Upvotes: 1

Views: 3111

Answers (5)

Adrian Niculescu
Adrian Niculescu

Reputation: 1

I recently had the same problem and the solution was to call

model.fireTableDataChanged();

right after adding the new row to the model.

My issue was the following: I had a table on which I allowed sorting. Without clicking the column headers so that the rows would sort accordingly, I was able to add data to the model and see the changes in the table by calling table.revalidate(); However, if, at any time, I clicked the column headers, any row added afterwards wouldn't be shown, although the model data was updating properly. By only calling model.fireTableDataChanged(); after adding the data to the model, it works as a charm.

Upvotes: 0

Karim Massi
Karim Massi

Reputation: 77

by the way why you're using TableRowSorter in your code , why you don't use just the jtable and defaultmodel directly

Upvotes: 0

Paul Samsotha
Paul Samsotha

Reputation: 209112

It looks like what you think is that when the file updates, so should the JTable. It doesn't work like that. What you need to do is add a row to the TableModel. A disadvantage in your case is this

TableModel model = new DefaultTableModel(   data, columns)

You're using the TableModel interface, which has very limited methods you can use. Instead do this

DefaultTableModel model = new DefaultTableModel(   data, columns)

Then you can use one of these methods from DefaultTableModel

  • public void addRow(Object[] rowData) - Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.

  • public void addRow(Vector rowData) - Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.

So when you want to add a row, you can gather your data into an array, addRow(..) then the table will get automatically update for you.

Object[] row = { data1, data2, data2, data4, data5 };
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.addRow(row);

Also it looks to me like your JTable is locally scoped. You may want to give it a global, class member scope, so you can access it from where ever you need to.

Upvotes: 3

Java Man
Java Man

Reputation: 1860

Use this code.

private void resetListData() throws ClassNotFoundException, SQLException 
{
 Connection cne = null;
  try {


    // create connection in this line as per your database like I used sqlite. so my connection string is as follow
    Class.forName("org.sqlite.JDBC");
    cne = DriverManager.getConnection("jdbc:sqlite:table.sqlite");
    cne.setAutoCommit(false);

    PreparedStatement psd = (PreparedStatement) cne.prepareStatement("Select * from table");                
    psd.execute();
    ResultSet r = psd.getResultSet();
    ResultSetMetaData rsmd = r.getMetaData();
    int count = rsmd.getColumnCount();
    String[] meta = new String[count];
    for (int i = 0; i < count; i++) 
    {
        String name = rsmd.getColumnName(i + 1);
        meta[i] = name;
        //System.out.println(name);
    }
    model = new DefaultTableModel(new Object[][]{}, new String[]{"name", "address"});
    jTable1.setModel(model);
    while (r.next()) 
    {
        Object[] row = new Object[count];
        for (int i = 1; i <= count; ++i) 
        {
            row[i - 1] = r.getString(i);  // Or even rs.getObject() 
        }
        model.addRow(row);
    }
    cne.close();
} catch (ClassNotFoundException | SQLException e) {
}
}

create connection and query as per your need.. my code add one row at the end of Jtable. My code directly working with your database..

Thanks..

Upvotes: 0

Karim Massi
Karim Massi

Reputation: 77

you must add your data to the model of jtable and then add the model to jtable and it will be refreshed , but before that you have to define a model .

Upvotes: 1

Related Questions