Error declaring Jtextfield vector in class

Asked

Viewed 46 times

3

Well, I’d like to store all my JTextField in an array, however, when I define the array, I get the following error: llegal forward reference. Follow 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.

  • Have you defined the fields of these variables? Add the rest of the code in the question.

  • The problem was exactly this, I ended up forgetting that within my class the Swing components are being declared only at the end of it.

2 answers

3


llegal forward reference occurs when you try to use a variable before it has been declared or initialized. That is, you’re trying to use a variable that doesn’t even exist yet. 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 before the initialization and declaration of the two variables you are adding in 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 yet exist. The problem is solved by correcting the context, in this case by declaring the variables before adding to the array:

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

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


References:

-1

You forgot to give a new in the array:

JTextField campos[] = new JTextField[]{campoNome, campoUsuario};
  • That’s not the reason for the mistake.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.