使用单独的线程更新JTable

时间:2012-07-08 18:55:28

标签: java multithreading swing jtable runnable

该应用程序的目的是查询表,并获取该信息并更新JTable。现在ThreadTask()能够查询表并获取信息。我的问题是如何使用从数据库获得的信息更新JTable GUI对象?

    public class AdminManager extends JFrame {

        public static void main(String[] args) throws InterruptedException {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        AdminManager frame = new AdminManager();
                        frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });

            // Setup connection pool

            ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
            exec.scheduleAtFixedRate(new ThreadTask(connection), 2000, 100, TimeUnit.MILLISECONDS);
    }
        /**
         * Create the frame.
         */
        public AdminManager() {
            // Setup GUI

            DefaultTableModel model = new DefaultTableModel();
            model.addColumn("#");


            tableQueue = new JTable(model);
            tableQueue.getColumnModel().getColumn(0).setPreferredWidth(3);
            scrollPane.setViewportView(tableQueue);

        }
    class updateTable extends SwingWorker<Void, String> {
        @Override
        protected Void doInBackground() throws Exception {
            model.addRow(new Object[]{order_num});
            return null;
        }

    }
}
class grabData implements Runnable {
    private Connection connection;
    private DefaultTableModel model;
    private String order_num;

    public grabData(Connection c, DefaultTableModel m) {
         connection = c;
         model = m;
    }

    @Override
    public void run() {
       System.out.println("Working ... ");
       String sql = "SELECT * FROM order_queue;";
       Statement st;
       try {
           st = connection.createStatement();
           ResultSet rs = st.executeQuery(sql);
            while(rs.next()) {
                order_num = rs.getString("order_num");
                System.out.println(order_num);
                updateTable.execute()
            }
       } catch (SQLException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }   
   }

1 个答案:

答案 0 :(得分:9)

如果要向可视化JTable持有的TableModel对象添加行,则必须在Swing事件线程EDT上执行此操作。如果你正在创建一个没有可视化的全新TableModel,那么我认为从EDT中填充它是安全的,然后将它设置为EDT上的JTable模型。 / p>

一个考虑因素,如果要在JTable可用时添加行,请考虑使用SwingWorker<Void, RowObject>,然后通过发布/处理方法对传递在while (rs.next()) {中获得的RowObject。 / p>

修改
你可以跳过SwingWorker,然后排队在EDT上添加表格的行:

while(rs.next()) {
    final String order_num = rs.getString("order_num");
    // System.out.println(order_num);
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        model.addRow(new Object[]{order_num});
      }      
    });
}