java – Error declaring JTextField vector in class

Question:

Well, I would like to store all my JTextField in an array, however when I define the vector I get the following error: llegal forward reference . Below is the code where I define the array.

private JTextField campos[] = {campoNome, campoUsuario};

I know I could replace it with ArrayList , however I would like to know why the error was generated.

Answer:

llegal forward reference occurs when you try to use a variable before it has been declared or initialized. That is, you are trying to use a variable that doesn't even exist yet. This error can also occur if you try to access a method of an undeclared object.

Possible cause of this error in your code could be due to this line mentioned in the question being before the initialization and declaration of the two variables you are adding to the array. Something that might be like this in your code:

private JTextField campos[] = {campoNome, campoUsuario};
private JTextField campoNome, campoUsuario;

Note that you declare the fields after creating the array, this operation is not possible because in that context they do not exist yet. The problem is solved by correcting the context, in this case declaring the variables before adding to the array:

private JTextField campoNome, campoUsuario;
private JTextField[] campos = {campoNome, campoUsuario};

Remembering that in this case the llegal forward reference error will no longer occur because the fields were declared before being added to the array, so they already exist in that context, even though they have not been initialized yet.


References:

Scroll to Top