简体   繁体   English

如何在添加新行后进行JTable刷新

[英]how to make my JTable refresh after adding a new row

After I add a new row to a JTable . 在我向JTable添加新行之后。 The information wrote goes to the txt file, but my JTable doesn't shows the last raw. 写入的信息转到txt文件,但我的JTable没有显示最后一个原始文件。 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? 那么,有没有办法刷新JTable的数据而不关闭应用程序并再次运行它?

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));
        }
    }
});

It looks like what you think is that when the file updates, so should the JTable . 看起来你认为当文件更新时, JTable It doesn't work like that. 它不像那样工作。 What you need to do is add a row to the TableModel . 您需要做的是向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. 您正在使用TableModel接口,它可以使用非常有限的方法。 Instead do this 而是这样做

DefaultTableModel model = new DefaultTableModel(   data, columns)

Then you can use one of these methods from DefaultTableModel 然后,您可以使用DefaultTableModel的这些方法之一

  • public void addRow(Object[] rowData) - Adds a row to the end of the model. public void addRow(Object[] rowData) - 在模型末尾添加一行。 The new row will contain null values unless rowData is specified. 除非指定了rowData,否则新行将包含空值。 Notification of the row being added will be generated. 将生成要添加的行的通知。

  • public void addRow(Vector rowData) - Adds a row to the end of the model. public void addRow(Vector rowData) - 在模型末尾添加一行。 The new row will contain null values unless rowData is specified. 除非指定了rowData,否则新行将包含空值。 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. 因此,当您想要添加一行时,您可以将数据收集到一个数组中, addRow(..)然后表将自动为您更新。

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. 它也让我觉得你的JTable是本地范围的。 You may want to give it a global, class member scope, so you can access it from where ever you need to. 您可能希望为其提供全局的类成员范围,以便您可以从任何需要的位置访问它。

您必须将您的数据添加到jtable模型,然后将模型添加到jtable,它将被刷新,但在此之前您必须定义模型。

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. 根据您的需要创建连接和查询..我的代码在Jtable的末尾添加一行。 My code directly working with your database.. 我的代码直接使用你的数据库..

Thanks.. 谢谢..

顺便说一句,为什么你在代码中使用TableRowSorter,为什么你不直接使用jtable和defaultmodel

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(); 在没有单击列标题以便行相应排序的情况下,我能够通过调用table.revalidate();向模型添加数据并查看表中的更改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(); 只调用model.fireTableDataChanged(); after adding the data to the model, it works as a charm. 将数据添加到模型后,它可以作为一个魅力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM