2014-12-04 96 views
0

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

这是我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); 
}` 

这个我怎么称呼loadData方法关闭的JDialog时。

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没有刷新。

回答

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

谢谢dic19。这对我有用。我在构造函数方法中添加了'table = new JTable(model)',然后在构造函数方法中添加了'loadData()'方法。我的桌子需要一些时间来加载。所以现在我要做和你的例子一样的改变。 – 2014-12-05 03:56:51

0

这是一个在黑暗中拍摄,但也许这将工作?:

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

如果我明白是怎么回事,底层数据库得到更新,但JTable组件没有显示更新。我的猜测是你只需要调用repaint()方法,以便JTable也得到更新。

+0

谢谢nihilon。这对我不起作用。但是我将更多地了解'repaint()'方法。 – 2014-12-05 03:59:10

+0

不用担心@broken_code,我的猜测是错误的。方式错了。但这就是我们来这里的原因,对吧?学习! – nihilon 2014-12-08 02:30:06

0

这为我工作:

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

setTablevalue(); 

我删除了所有来自JTable行,并再次叫setTableValue方法重新填充表。

相关问题