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
  • 166,747
  • 40
  • 210
  • 420
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
  • 18,291
  • 9
  • 17
  • 38
Ali Faris
  • 15,922
  • 10
  • 37
  • 64
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
  • 704,970
  • 168
  • 1,303
  • 1,425
Niton
  • 149
  • 6
  • 16