Search code examples
javastringswingjtextfieldfinal

JTextField wants to be a final when i try to use .getText()


I'm working on this multiplayer game for school and I'm currently trying to take a username from a JTextField.

Here's the code in question:

JTextField textField = new JTextField();

new Statistics(textField.getText());

Statistics takes a string, but when I try this, eclipse is telling me that I need to cast the JTextField as a final.

The code works, as Statistics isn't doing anything at the moment, but I don't think this should be happening, and will break my code later on when I do start implementing Statistics. Any explainations and a fix?


Solution

  • This call: new Statistics(textField.getText()); is likely occurring inside of an inner anonymous class, perhaps inside of an ActionListener, and your textField is a local variable. The problem is that anonymous inner classes make copies of local fields that they use, and if the fields are not final, then the copy may not be in sync with the original causing all sorts of problems.

    I suggest that you declare the textField in the class, not inside of a method or constructor, thus making it a class field. If you do htis, then you will will not have to declare it as final.

    Otherwise if you can't or shouldn't do this, then sure, go ahead and declare it (you can't "cast it") as final.