0

我正在从 .txt 文件创建一个 Jtable。.txt 文件会在一段时间内不断更新。我需要知道是否有任何方法可以在运行时在我的 Jtable 中反映 .txt 文件中的这些更改!!!我知道在重新启动时,表会读取 .txt 文件,但有什么方法可以在运行时执行吗?

4

5 回答 5

3

我想可能看起来像这样......

public class BackgroundMonitor implements Runnable {

    public void run() {

        while (true) {
            // Check to see if the file has changed since the last update...
            // If it has you will want to store the metrics and return true...
            if (hasChanged()) {

                // Load the contents into what ever construct you need to use
                ... = loadContents();

                // Create a new model...
                TableModel model = ... // create a new table model

                // Apply the model to the table...
                applyModel(model);

            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
                Logger.getLogger(ThreadUpdates.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

    }

    protected void applyModel(final TableModel model) {

        // Apply the model to the table, making sure you update within the
        // EDT
        try {
            EventQueue.invokeAndWait(new Runnable() {

                @Override
                public void run() {
                    table.setModel(model);
                }
            });
        } catch (InterruptedException | InvocationTargetException exp) {
            // Handle the update exception....
        }

    }

}

这样做的问题是您每次都强制表完全更新,这可能会变得很慢(随着数据量的增加)并且会使当前选择无效。

如果您可以确定最后一行,您最好只添加那些已更改的行...

在这种情况下,“应用”方法可能看起来像

protected void applyModel(final List<?> rowsToBeAdded) {

    // Apply the model to the table, making sure you update within the
    // EDT
    try {
        EventQueue.invokeAndWait(new Runnable() {
            @Override
            public void run() {

                MyUpdatableModel model = (MyUpdatableModel) table.getModel();
                model.addNewRows(rowsToBeAdded);

                // You will need to call fireTableRowsInserted(int firstRow, int lastRow)
                // indiciate where the new rows have been added, but this is best
                // done in the model

            }
        });
    } catch (InterruptedException interruptedException) {
    } catch (InvocationTargetException invocationTargetException) {
    }

}

这是一种更好的方法,因为它只需要表来更新那些已经更新并且不应该影响选择的行......

于 2012-09-27T06:39:45.313 回答
3

您应该编写一个后台线程来不断检查文本文件的内容并不断更新表模型。

于 2012-09-27T06:23:19.683 回答
2

除了Dan写的内容,要在后台线程中实际查看您的文件,您可以查看WatchService API。这已被添加到Java 7的 SDK 中。它允许注册事件侦听器,当文件更改时通知这些侦听器。

于 2012-09-27T06:29:00.693 回答
0

这可以通过调用你TableModelfireTableDataChanged方法来实现。我假设您的表由AbstractTableModel. 如果是这样,您只需要fireTableDataChanged在读取文本文件的内容并更新表模型中的值后调用。你可以在这里找到一些细节:

Java API

编辑:在下面 Dan 的回复之后 - 您希望您的文本文件监控线程触发该fireTableDataChanged方法。

于 2012-09-27T06:27:15.267 回答
0

我也不能自动更新。我所做的是,我只是关闭窗口添加再次调用同一个窗口。

于 2013-10-24T08:54:02.593 回答