在运行时刷新java程序

时间:2012-09-01 01:04:19

标签: java swing jtable runtime defaulttablemodel

我有java程序这样做: 从数据库中获取数据并将它们附加到JTable中。

当我将数据添加到数据库中时,我无法刷新JTable来查看新数据 我应该关闭程序并再次运行它。

如何刷新/重新加载程序以查看数据

2 个答案:

答案 0 :(得分:2)

好的,我会给你一个快速解决方案:

package stack;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;


public class Test {
    JTable table = new JTable();

    public void selectFrom(){
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        DefaultTableModel model=(DefaultTableModel)table.getModel();
        int rc= model.getRowCount();
        for(int i = 0;i<rc;i++){
            model.removeRow(0);
        }
        try{
            Class.forName("org.postgresql.Driver");
            conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mydb","postgres","123");
            st = conn.createStatement();
            rs = st.executeQuery("select * from mytable");
            while(rs.next()){
                //Populate table
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private void insertInto(){
        Connection conn = null;
        PreparedStatement pst = null;
            try{
                Class.forName("org.postgresql.Driver");
                conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mydb","postgres","123");
                pst = conn.prepareStatement("INSERT INTO mytable(id,first_column) VALUES(?,?)");
                //Insert into table using pst
                pst.execute();

                selectFrom();
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                try {
                    pst.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
        }
    }
}

答案 1 :(得分:2)

如果使用DefaultTableModel,请参阅addRow methods。否则只需创建一个新模型并调用JTable.setModel(TableModel)