0
    JLabel[] labels=new JLabel[10];
    ImageIcon[] image = new ImageIcon[10];
    
    labels[0].setForeground(Color.BLACK);
    image[0] = new ImageIcon(this.getClass().getResource("/White.jpg"));
    labels[0].setIcon(image[0]);
    labels[0].setBounds(12, 124, 31, 18);
    frame.getContentPane().add(labels[0]);

I'm trying to create a simple array of JLabels and print an array of ImageIcons on it. But I get this weird error which says it is null:

java.lang.NullPointerException: Cannot invoke "javax.swing.JLabel.setForeground(java.awt.Color)" because "labels[0]" is null

How can labels[0] be null? Does someone have any idea why may this be happening?

Thank you so much in advance!

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    You create an array of `JLabel`s. This does not mean, that this array already contains actual `JLabel` objects. The array is more like a placeholder waiting to store `JLabel` objects. When you try to access the first element of the array like `labels[0]`, this element is `null` because you didn't fill the array with `JLabel`s. You then try to `setForeground()` on `null`, hence the `NullPointerException`. – maloomeister May 12 '21 at 10:50

1 Answers1

1

The jLabel on position 0 hasn't been initilaised. You need to add something on first place in labels array.

    JLabel[] labels=new JLabel[10];
    ImageIcon[] image = new ImageIcon[10];
    labels[0] = new JLabel();
    labels[0].setForeground(Color.BLACK);
mihajlo
  • 71
  • 5