Search code examples
javareferenceinstantiationjcomponent

Adding various type of components into a JComponent reference array


I have a JComponent reference like JComponent allComp[]; Now I want to every element of this array holds different type of component like below,

allComp[0] = new JComboBox();

allComp[1] = new JButton();

allComp[2] = new JMonthChooser();

I am trying and getting Null Pointer exception. Is this possible?? If possible how?? Please help me in this issue. Thanks advance


Solution

  • You probably have not initialized allComp and it's null.

    JComponent allComp[] = new JComponent[MAX_COMPONENTS];
    

    Anyway, it is advisable to use a List instead of an array if you don't know beforehand the number of components.

    List<JComponent> allComp = new ArrayList<>();
    allComp.add(new JComboBox());
    allComp.add(new JButton());
    allComp.add(new JMonthChooser());