Error declaring JTextField vector in class

3

Well, I would like to store all my JTextField in an array, but when I define the array, 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 with ArrayList , but I wonder why the error was generated.

    
asked by anonymous 10.09.2017 / 16:38

2 answers

3

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 does not even exist. This error can also occur if you try to access a method from an undeclared object.

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

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

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

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

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

References:

10.09.2017 / 16:58
-1

You forgot to give a new one in the array:

JTextField campos[] = new JTextField[]{campoNome, campoUsuario};
    
10.09.2017 / 16:50