0

我是java的菜鸟。这是我第一次在 java 中使用 timer 和 timerTask 类。

我的应用程序的目的:

它是用 MySQL 实现的多客户端应用程序。我的应用程序是重复读取我的数据库数据。如果数据库更新,那么我希望每个客户的面板也更新。所以我假设我需要一个计时器类,它可以自动执行读取我的数据库的重复查询,然后对客户端的组件进行一些更改。

问题:

我看起来想了一些教程,我发现了这种方法。由于 this.updateTableStatus() 方法在我的 Table 类中,我如何在 MyTimer(timerTask) 类中使用该方法。

public class Table extends javax.swing.JFrame {

    public Table() {
        initComponents();
        MyTimer myTime = new MyTimer();

    }
    public void updateTableStatus(){
        // this is where I refresh my table status which is reading database data and make some change.
    }

    class MyTimer extends TimerTask{
        public MyTimer() {
            Timer timer = new Timer();
            timer.scheduleAtFixedRate(this, new java.util.Date(), 1000);
        }
        public void run(){

            this.updateTableStatus();   // this is not working!!!, because they r not in the same class.  I need help to solve this problem.
        }
    }
}

帮帮我,伙计们。太感谢了。

4

2 回答 2

1

最好使用Swing Worker,然后在数据更改时发布结果。这样您就不会在进行数据库查询时阻止 EDT。

如果要使用 TimerTask,则需要将 TableModel 的任何更新包装在 SwingUtilities.invokeLater() 中。

于 2013-05-18T20:44:42.333 回答
0

this.updateTableStatus();试图引用 MyTimer 的updateTableStatus()方法(但没有这样的方法)。要引用 Table 的updateTableStatus()方法,您可以将其更改为

Table.this.updateTableStatus();

注意
说真的,我认为每秒检查每个客户端的数据库以查看是否有任何更改是非常糟糕的应用程序设计。我建议您发布一个新问题,解释您当前的架构和要求,并就如何有效地监视数据库更改提出建议。

于 2013-05-18T20:43:59.730 回答