从数据库值更改标签名称java.lang.NullPointerException

时间:2012-12-30 13:55:44

标签: java mysql database swing user-interface

我有一个数据库表如下:

CREATE TABLE "AcademicInfo" ("academicid" INTEGER PRIMARY KEY  NOT NULL  UNIQUE , "Title" 
CHAR NOT NULL , "Forename" CHAR NOT NULL , "Surname" CHAR NOT NULL , "Role" CHAR NOT NULL,
"Room" CHAR NOT NULL , "Page" CHAR NOT NULL , "Hours" CHAR NOT NULL , "Phone" CHAR NOT NULL,     
"Mobile" CHAR NOT NULL , "Email" CHAR NOT NULL , "Image" BLOB, "Password" CHAR NOT NULL )

以下课程:

public class MainMenu extends JFrame
{
    Academic ac = new Academic();
    Connection conn = JavaConnect.ConnectDB();
    PreparedStatement pst = null;
    String sql; 
    ResultSet rs = null;

    /**
     * Creates new form MainMenu
     */
    public MainMenu() {
        initComponents();
    }

    public void Update_table()
    {
        try {
            String sqlStatement = "SELECT Title, Forename, Surname, Role FROM AcademicInfo ";
            pst = conn.prepareStatement(sqlStatement);
            rs = pst.executeQuery();
            table_academic.setModel(DbUtils.resultSetToTableModel(rs));
        }
        catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
        finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (pst != null) {
                    pst.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(MainMenu.class.getName());
                lgr.log(Level.WARNING, ex.getMessage(), ex);
            }
        }
    }

    private void table_academicMouseClicked(MouseEvent evt)
    {
        try {
            int row = table_academic.getSelectedRow();
            String table_click = (table_academic.getModel().getValueAt(row, 2).toString());
            String sqlSt = "SELECT * FROM AcademicInfo WHERE Surname='"+table_click+"'";
            pst = conn.prepareStatement(sqlSt);
            rs = pst.executeQuery();

            if(rs.next()) {
                label_name.setText(""+rs.getString("Surname"));
            }
        }
        catch(Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    }
}

我在'table_academicMouseClicked'遇到问题。我的目标是当一个记录被点击在一个表上时,它从数据库中获取确切的姓氏设置'label_name',但我在那个阶段得到一个java.lang.NullPointerException。我只有事件处理程序方法的问题,没有别的。我在academicMouseClicked()做错了什么?

1 个答案:

答案 0 :(得分:1)

检查您是否在initialize方法中初始化了label_name

label_name = new JLabel();