Orobo Lucky Ozoka
Orobo Lucky Ozoka

Reputation: 43

Creating an array of JTextField

I was trying to create an array of JTextField and then use a loop to add each one to a JPanel. Here is the code snippet, it doesn't seem to work.

public void courseCode(){
    JTextField[] courseCode = new JTextField[10];
    int y=30;
    for (int i=0;i<10;i++){
        courseCode[i].setBounds(280, y, 100, 25);
        y+=30;
        add(courseCode[i]);
    }

P.S: I did call the courseCode() method from the class constructor

Upvotes: 0

Views: 158

Answers (1)

Reimeus
Reimeus

Reputation: 159754

Elements of an Object array are null by default. Initialise the elements before attempting to invoke their methods

for (int i=0; i < 10; i++) {
  courseCode[i] = new JTextField();
  ...
}

Upvotes: 2

Related Questions