4

该应用程序的目的是查询表,获取该信息并更新 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();
       }   
   }
4

1 回答 1

9

如果要将行添加到由可视化 JTable 保存的 TableModel 对象,则必须在 Swing 事件线程(EDT)上执行此操作。如果您正在创建一个未可视化的全新 TableModel,那么我认为从 EDT 中填充它是安全的,然后将其设置为EDT的 JTable 模型。

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

编辑:
您可以跳过 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});
      }      
    });
}
于 2012-07-08T18:58:06.990 回答