javaarraysswingjmenuitem

JAVA declaring uninitialized JMenuItem() items inside JMenuItem[] constructor


I have this code:

JMenuItem itemA;
JMenuItem itemB;
JMenuItem itemC;
JMenuItem[] items = {itemA, itemB, itemC};

What I would like to do is declaring those JMenuItems inside the JMenuItem array constructor so I would spare several lines of else unnecessary code (that is get rid of that initial declaring of those separate items first). I would expect something in line of this fictional code:

JMenuItem[] items = {JMenuItem itemA, JMenuItem itemB, JMenuItem itemC};

...but that does not work, of course. Can anyone enlighten me how to do it, please? BTW those items are initialized later in code.


Solution

  • Replace this

    JMenuItem[] items = {JMenuItem itemA, JMenuItem itemB, JMenuItem itemC};
    

    with this

    JMenuItem[] items = {null, null, null}; //option 1
    JMenuItem[] items = new JMenuItem[3]; //option 2