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.
You have initialized an array of JTextField. But each element in the array is still not initialized.
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,
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
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.