我想从数据库的一张表中读取一条记录,然后显示在JTextField中,例如表名为“menu”,其中一个列名是menuId,我现在想读取一个Id到JTextField中,用的如下语句:
JTextField txtfId = new JTextField(16);
this.txtfId.setText(menu.getmenuId().toString());
其中menu类是一个JAVA BEAN,里面是对menu表的各字段的get,set方法,其中get方法的返回值就是menuId。
这样写了以后,会报空指针异常(nullPointerException)
各位给我说说到底应该怎么写啊?

解决方案 »

  1.   

    你的两行代码是在一起的吗?
    不会是你把方法内部声明的txtfId初始化后,调用了没有初始化的this.txtfId的setText了吧?
      

  2.   

    代码很简单的~就是为了试试看怎么把数据库记录读取放到JTextField中package com.jz.sm.jiemian;import java.awt.Container;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;import com.jz.sm.framework.model.entity.Menu;public class DateBaseReturn extends JFrame{
    private JPanel pnlMain = null;
    private JTextField txtfId = null;

    public DateBaseReturn() {
    Container contentPane = this.getContentPane();
    this.pnlMain = new JPanel();
    contentPane.add(this.pnlMain);

    this.txtfId = new JTextField(16);
    Menu menu = new Menu();
    this.txtfId.setText(orgType.getMenuId().toString());
    this.pnlMain.add(this.txtfId);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.pack();
    this.setVisible(true);
    }

    public static void main(String[] args) {
    new DateBaseReturn();
    }
    }
    Menu就对应数据库中的一张表
    Menu的实体BEAN:
    package com.jz.sm.framework.model.entity;public class Menu {
    private String menuId = null;
    private String menuName = null;
    private String menuMemo = null;

    public Menu(){

    }

    public Menu(String menuId, String menuName, String menuMemo){
    this.menuId = menuId;
    this.menuName = menuName;
    this.menuMemo = menuMemo;
    } public String getMenuId() {
    return menuId;
    } public void setMenuId(String menuId) {
    this.menuId = menuId;
    } public String getMenuMemo() {
    return menuMemo;
    } public void setMenuMemo(String menuMemo) {
    this.menuMemo = menuMemo;
    } public String getMenuName() {
    return menuName;
    } public void setMenuName(String menuName) {
    this.menuName = menuName;
    }


    }