简体   繁体   English

自动更新JTable

[英]Automatic update JTable

I am creating a Jtable from .txt file. 我正在从.txt文件创建一个Jtable。 The .txt file keeps on updating over a certain period of time. .txt文件会在一段时间内不断更新。 I need to know if there are any ways to reflect those changes in .txt file in my Jtable AT RUN-TIME!!! 我需要知道是否有任何方法可以在运行时在Jtable中将.txt文件中的更改反映出来! I know on restarting, the table reads .txt file but is there any way to do it on run time?? 我知道重新启动时,该表读取.txt文件,但是有什么方法可以在运行时执行此操作吗?

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

I'd imagine to might look something like this... 我想可能看起来像这样...

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....
        }

    }

}

The problem with this is you're forcing the table to be fully update every time, this could become slow in time (as the quantity of data increases) and will invalidate the current selection. 这样做的问题是您迫使表每次都进行完全更新,这可能会导致时间变慢(随着数据量的增加)并使当前选择无效。

If you can determine the last line you were up-to, you'd be better only adding those rows that have changed... 如果您可以确定要到达的最后一行,最好只添加那些已更改的行...

In that case the "apply" method could look like 在这种情况下,“应用”方法可能看起来像

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

}

This is a much nicer approach as it will only require the table to update those rows that have been updated and shouldn't effect the selection... 这是一种更好的方法,因为它只要求表更新那些已更新的行,并且不影响选择。

Besides what Dan wrote, to actually watch your file within the background thread, you could have a look at the WatchService API . 除了Dan编写的内容之外,要在后台线程中实际监视文件,还可以查看WatchService API This has been added to the SDK in Java 7 . 这已添加到Java 7的SDK中。 It allows to register event listeners which are notified when a file has been changed. 它允许注册事件侦听器,当文件已更改时通知该事件。

This can be achieved by calling your TableModel 's fireTableDataChanged method. 这可以通过调用TableModelfireTableDataChanged方法来实现。 I am assuming that your table is backed by an implemention of an AbstractTableModel . 我假设您的表由AbstractTableModel的实现支持。 If so, you just need to call fireTableDataChanged after reading the contents of your text file and updating the values in your table model. 如果是这样,您只需要在读取文本文件的内容并更新表模型中的值之后调用fireTableDataChanged You can find some details here: 您可以在此处找到一些详细信息:

Java API Java API

Edit: Following Dan's reply below - You would want your text file monitoring thread to trigger the fireTableDataChanged method. 编辑:在下面丹的答复-您希望您的文本文件监视线程触发fireTableDataChanged方法。

I can't also auto-update. 我也不能自动更新。 What I did was, I'm just closing the window add call the same window again. 我所做的是,我只是关闭窗口,然后再次调用同一窗口。

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

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