import java.awt.*;
import java.awt.event.*;

public class sample2 extends Frame
    {
    Button b[];
    public sample2()
        {
        super("trying");
        b=new Button[10];
        setLayout(new FlowLayout());
        for(int i=0;i<10;i++)
            add(b[i]);
        }
    public static void main(String args[])
        {
        sample2 obj=new sample2();
        obj.setSize(500,100);
        obj.setVisible(true);
        }
    }

Exception is as below

Exception in thread "main" java.lang.NullPointerException 
at java.awt.Container.addImpl(Container.java:1037) 
at java.awt.Container.add(Container.java:373) 
at sample2.<init>(sample2.java:13) 
at sample2.main(sample2.java:17) 
有帮助吗?

解决方案

Yes you create the Button array, but you never initialize the elements of the array before using. This means that you're adding null Buttons to your GUI. Create your Buttons first before using.

    for(int i=0;i<10;i++)
        b[i] = new Button();
        add(b[i]);
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top