Вопрос

else if(e.getSource()==button3){
         JButton[] addSong = new JButton[50];
         JLabel[] label = new JLabel[50];
         JPanel[] smallPanel = new JPanel[50];
         JPanel panel = new JPanel(new GridLayout(1,50));
         for(int i=0;i<50;i++){
            addSong[i].setText("+");
            label[i].setText("Name of song");
            smallPanel[i].add(addSong[i]);
            smallPanel[i].add(label[i]);
            panel.add(smallPanel[i]);
         }
         tabs.addTab("All Songs",panel);
      }

All of the statements in the for loop give me a NullPointerException. I'm new to Java =/

Это было полезно?

Решение

Elements in an Object array are null by default. Initialise the elements of all arrays prior to attempting to invoke any operations on them

for (int i=0; i < 50; i++){
   addSong[i] = new JButton();
   label[i] = new JLabel();
   smallPanel[i] = new JPanel();
   ...
}

Другие советы

When creating an array of objects, the elements in the array are all initialized to null. You must create the object and assign it to an element in the array before accessing it and calling a method on it.

// Before calling a method on the array position...
label[i] = new JLabel();
// Then you can do this...
label[i].setText("Name of song");

The other arrays will need their elements initialized to actual objects similarly.

else if(e.getSource()==button3){
     JButton[] addSong = new JButton[50];
     JLabel[] label = new JLabel[50];
     JPanel[] smallPanel = new JPanel[50];
     JPanel panel = new JPanel(new GridLayout(1,50));
     for(int i=0;i<50;i++){
        addSong[i] = new JButton("+"); // creates a new button with text "+"
        label[i] = new JLabel("Name of song"); // creates a new JLabel with text "Name of song"
        smallPanel[i] = new JPanel();
        smallPanel[i].add(addSong[i]);
        smallPanel[i].add(label[i]);
        panel.add(smallPanel[i]);
     }
     tabs.addTab("All Songs",panel);
  }

the reason of this behavior is because by default in an Array of Object (that you created with Type[], where Type is one of JPanel, JButton and JLabel) all records are indeed Objects, but null.

That means that you are telling java "hey, in this array go only this Object", Java knows that only "Object" type can go inside its "spaces" but don't know what kind of objects.

This is the reason why for each "space" in the array (looped with the for cycle) you have to tell Java "here go a new JButton" (or JPanel, or JLabel). And this is the way:

arrayName[index] = new Type();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top