JTable不会刷新..我得到一个java.lang NullPointerException

时间:2013-05-03 13:27:18

标签: java swing nullpointerexception jtable

我有两个JFrame个实例。主框架具有将数据从DB填充到表格的代码,另一个是jFrame2,而用户从主框架添加或更新记录表将自动刷新

这是我的主框架代码:

public void fillTable(){

String sql = "SELECT ID, UniqueCode, Name, Age, Gender, Cell FROM info";
try{

    pst = conn.prepareStatement(sql);
    rs = pst.executeQuery();
    jTable1.setModel(DbUtils.resultSetToTableModel(rs));

    jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    jTable1.getColumnModel().getColumn(0).setPreferredWidth(60);
    jTable1.getColumnModel().getColumn(1).setPreferredWidth(250);
    jTable1.getColumnModel().getColumn(2).setPreferredWidth(100);
    jTable1.getColumnModel().getColumn(3).setPreferredWidth(60);
    jTable1.getColumnModel().getColumn(4).setPreferredWidth(60);
    jTable1.getColumnModel().getColumn(5).setPreferredWidth(92);

}
catch (Exception e){
    JOptionPane.showMessageDialog(null, e);
}
}

这是我的第2帧代码

private void save(){
    try{
        if(name.getText().isEmpty() || age.getText().isEmpty() || cell.getText().isEmpty()){
            JOptionPane.showMessageDialog(null, "Empty Fields Are Not Allowed", "System Message", JOptionPane.WARNING_MESSAGE);
        }
        else if(" ".equals(cmbGender.getSelectedItem())){
            JOptionPane.showMessageDialog(null, "Empty Fields Are Not Allowed", "System Message", JOptionPane.WARNING_MESSAGE);
        }
        else{
            connect = mysqlconnect.DBConnect(); 
            stmt = connect.createStatement();
            rs = stmt.executeQuery("SELECT Name FROM info WHERE Name='" + name.getText() + "'");

            if(rs.first()){
              JOptionPane.showMessageDialog(null, "Name already Exist, Duplicate info is not allowed", "System Message", JOptionPane.WARNING_MESSAGE);

            }else{
              sql = "INSERT INTO info(UniqueCode, Name, Age, Gender, Cell) values ('" + uniqueID.getText()+ "', '" + name.getText() + "', '" + age.getText() + "', " +
                    " '" + cmbGender.getSelectedItem() + "', '" + cell.getText() + "') ";

              Statement st = connect.createStatement();
              st.executeUpdate(sql);

              JOptionPane.showMessageDialog(null, "Successfully Saved", "System        Message", JOptionPane.INFORMATION_MESSAGE);

             this.dispose();
             frame.jTable1.repaint(); <====== Error comes here because i want to              refresh my table
            } 
        }
    }
    catch(Exception ex){
        System.out.println(ex);
    }

1 个答案:

答案 0 :(得分:0)

您声明此行会导致您的NPE:

frame.jTable1.repaint(); 

然后frame或frame.jTable1为null。将上面的行更改为:

System.out.println("frame == null: " + (frame == null)); 
System.out.println("frame.jTable1 == null: " + (frame.jTable1 == null));     
frame.jTable1.repaint(); 

然后在找到哪个变量为null后,在代码中追溯以查看未初始化它的位置。

请注意,您永远不必在JTable上调用repaint(),这不会“刷新”数据或执行任何此类操作。相反,您需要更改JTable模型所保存的数据,这是我在您发布的代码中看不到的。