Search code examples
javajtextfield

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


Solution

  • 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();
      ...
    }