我在一个类中定义了这样一个成员属性:JLabel[] labels ;
然后初始化这个类的init方法是这样写的:
public void init(String tem_floorcount, String tem_flatcount){

int floorcount = Integer.parseInt(tem_floorcount) ;
int flatcount = Integer.parseInt(tem_flatcount) ; labels = new JLabel[flatcount] ; for(int i = 0; i < flatcount; i++){
labels[i].setText("套间" + i) ;
}
}为什么运行的时候总提示这样一个错误呢(就是labels[i].setText("套间" + i)这一句):Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at yunan.dialog.Addflats_autoDialog.init(Addflats_autoDialog.java:43)
at yunan.main.Main$3.actionPerformed(Main.java:73)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)4 at java.awt.Component.processMouseEvent(Component.java:6041)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5806)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4413)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4243)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2440)
at java.awt.Component.dispatchEvent(Component.java:4243)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)望名位大侠指点指点~~~

解决方案 »

  1.   

    labels = new JLabel[flatcount] ;for(int i = 0; i < flatcount; i++){
    labels[i].setText("套间" + i) ;
    }
    } 你只声明的对象没有去new对象
    labels = new JLabel[flatcount] ;for(int i = 0; i < flatcount; i++){
    labels[i] = new JLabel();//创建对象
    labels[i].setText("套间" + i) ;
    }
      

  2.   

    for(int i = 0; i < flatcount; i++){ 
    labels[i] = new JLabel("套间" + i");
    //labels[i].setText("套间" + i) ; 

      

  3.   

    同意1#和3#的在java中数组的创建不光要使用labels = new JLabel[flatcount] 创建数组的引用,还要使用
    for(int i = 0; i < flatcount; i++){ 
    labels[i] = new JLabel("套间" + i"); 
    来逐个创建数组中元素,为每个元素分配内存。