如何在将数据插入数据库后刷新JTable?

时间:2014-12-04 19:32:29

标签: java swing ms-access jtable

我从访问数据库填充JTable。当第一次运行代码时,表完全加载。然后从JDialog向数据库添加新记录。我试图做的是在JDialog关闭时调用loadData()方法,但表没有更新。

这是我的loadData()方法:

private void loadData() {
    System.out.println("sssss");
    final String [] columnNames={"Seq", "First Name", "Last Name","Num1","Num2","Num3"};
    connectDb();

    data = new Object[rows][columns];
    int row = 0;
    try {
        while(rs.next()){
            for(int col = 0 ; col<columns; col++ ){
                if(col==0)
                    data[row][col]=rs.getString("contact_seq");
                if(col==1)
                    data[row][col]=rs.getString("contact_fname");
                if(col==2)
                    data[row][col]=rs.getString("contact_lname");
                if(col==3)
                    data[row][col]=rs.getString("contact_num1");
                if(col==4)
                    data[row][col]=rs.getString("contact_num2");
                if(col==5)
                    data[row][col]=rs.getString("contact_num3");


            }
            row++;
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    model = new DefaultTableModel(data, columnNames){

        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        public boolean isCellEditable(int row, int column)
        {
            return false;
        }



     };

     table = new JTable(model);
}`

这是关闭JDialog时如何调用loadData方法。

JMenuItem mntmNew = new JMenuItem("New Contact");
    mntmNew.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            addData gui = new addData(viewData.this,rs);
            gui.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
            gui.setVisible(true);
            gui.addWindowListener(new WindowAdapter() {
                public void windowClosed(WindowEvent e){
                    loadData();
                }
            });
        }
    });
    mnFile.add(mntmNew); 

我的数据库在添加记录时会更新,但Jtable不会刷新。

3 个答案:

答案 0 :(得分:4)

下面:

private void loadData() {
    ...
    table = new JTable(model); // don't re-create the table here
}

不要重新创建表格,而是通过设置新的表格模型或清除并重新填充当前的模型来更新其模型:

private void loadData() {
    ...
    table.setModel(model); 
    // Of course, table should have been initialized
    // and placed first, and only once!
}

参见示例here(包括SwingWorker以在后台线程中进行数据库调用),herehere。请查看这些答案,有解释说清楚。

答案 1 :(得分:0)

这是一个黑暗中的镜头,但也许这会起作用?:

public void windowClosed(WindowEvent e) {
    loadData();
    // Add this line:
    table.repaint();
}

如果我了解发生了什么,底层数据库会更新,但JTable组件没有显示更新。我的猜测是你只需调用repaint()方法,以便JTable也得到更新。

答案 2 :(得分:0)

这对我有用:

 if (model.getRowCount() > 0) {
     for (int i = model.getRowCount() - 1; i > -1; i--) {
         model.removeRow(i);
     }
 }

 setTablevalue();

我从JTable删除了所有行,并再次调用setTableValue方法重新填充表格。

相关问题