Question

I have the following code which uses one of the JTextAreas from an array of such Objects to assign the Insets of a JTextArea for my program. The code is as follows:

import javax.swing.*;
import java.awt.*; 

public class MainComponents
{ 
     private final static JTextField[] Input = new JTextField[10];

     public MainComponents(final Container P, final JFrame frame)
     { 

         P.setLayout(null);
         final Insets insets = P.getInsets();
         final Dimension InputInsets = Input[0].getPreferredSize();  //?

         ...
      }
}

Where I have the //? is where I get an Exception that tells me java.lang.NullPointerException occurs at this line. I cannot find the reason that Input[0] would be null if I assigned them alll to be JTextAreas. Am I declaring something incorrectly in the array?

Thank you.

Was it helpful?

Solution

You have initialized an array of JTextField. But each element in the array is still not initialized.

private final static JTextField[] Input = new JTextField[10];

Input[0] = new JTextField(); //And then perform operation on 0th element

To throw more light on this,

Whenever you initialize any primitive array in java, it will allocate memory continuously based on the passed data type.

For example,

int[] intArray = new int[10]; // Assuming int is 4 bytes, 40 bytes allocated continuously
double[] doubleArray = new double[10]; // Assuming double is 8 bytes, 80 bytes allocated continuously.

And note that intArray or doubleArray is a reference that is going to point to the starting memory location of the allocated value. This is the reason arrays are faster while searching by index. when you do a intArray[5], all it does is go to initial address of intArray + (5 * sizeof(integer)) will give the value directly.

However, things are a bit differnt in case of Objects. When I do

Object[] objArray = new Object[10];

This will create again a continuous 10 references in memory. Assuming a reference is 2 bytes, it will need 20 bytes continously. And all these are just references that are pointing to no where, ie they are null. It is our duty to invoke them explicitly.

OTHER TIPS

all you did with this line:

 private final static JTextField[] Input = new JTextField[10];

is initialize the array. You didn't initialize any of the array members (they're all still null). You need to iterate over the array and place an object in each slot before you can use it.

This line JTextField[] Input = new JTextField[10] allocates array. But each element of this array is null. So, attempt to turn to the element and call its methods throws

NullPointerExcetption. You have to initialize the array, e.g. 
for (int i = 0;  i < input.length;  i++) {
    input[i] = new JTextArea();
}

now you can access input[0];

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top