0

Im getting this strange NullpointerException whilst adding a JLabel to a JPanel:

    loadoutAdvWeaponPanels = new JPanel[4][4];
    loadoutAdvWeaponButtons = new JButton[4];
    loadoutAdvPistolLabels = new JLabel[4][8];

    //Init loadoutAdvPanels[0]

    loadoutAdvWeaponButtons[0] = new JButton("Pistols");

    loadoutAdvPistolLabels[0][0] = new JLabel("USP-S");
    loadoutAdvPistolLabels[0][1] = new JLabel("P2000");
    loadoutAdvPistolLabels[0][2] = new JLabel("Dual Berettas");
    loadoutAdvPistolLabels[0][3] = new JLabel("P250");
    loadoutAdvPistolLabels[0][4] = new JLabel("Five-SeveN");
    loadoutAdvPistolLabels[0][5] = new JLabel("CZ75-Auto");
    loadoutAdvPistolLabels[0][6] = new JLabel("Desert Eagle");
    loadoutAdvPistolLabels[0][7] = new JLabel("R8 Revolver");

    loadoutAdvWeaponPanels[0][0].add(loadoutAdvPistolLabels[0][0]);

The error occurs in the last line, but i dont know why.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Tom_There
  • 1
  • 1

2 Answers2

0

you should initialize the array loadoutAdvWeaponPanels

    loadoutAdvWeaponPanels = new JPanel[4][4];
    for(int i = 0; i < loadoutAdvWeaponPanels.length; i++)
        for(int j = 0; j < loadoutAdvWeaponPanels[i].length; j++)
            loadoutAdvWeaponPanels[i][j] = new JPanel();

or just initialize what you need

    loadoutAdvWeaponPanels[0][0] = new JPanel();
    loadoutAdvWeaponPanels[0][0].add(loadoutAdvPistolLabels[0][0]);
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
Ali Faris
  • 17,754
  • 10
  • 45
  • 70
0

Simple as I see!

You do not initialisized loadoutAdvWeaponPanels[0][0]

I prefer to use this:

for(int i = 0; i < loadoutAdvWeaponPanels.length; i++) {
    for(int j = 0; loadoutAdvWeaponPanels[i].length; j++) {
    {
         loadoutAdvWeaponPanels[i][j] = new JPanel();
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Niton
  • 189
  • 4
  • 16