当我尝试使用.getText()时,JTextField希望成为最终版本 [英] JTextField wants to be a final when i try to use .getText()

查看:82
本文介绍了当我尝试使用.getText()时,JTextField希望成为最终版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为学校开发这款多人游戏,目前正在尝试从JTextField中获取用户名.

这是有问题的代码:

JTextField textField = new JTextField();

new Statistics(textField.getText());

统计信息使用字符串,但是当我尝试使用此字符串时,eclipse告诉我我需要将JTextField强制转换为final.

代码可以正常工作,因为统计信息目前不做任何事情,但是我认为这不会发生,并且在以后开始实现统计信息时会破坏我的代码.有任何解释和解决方法吗?

解决方案

此调用:new Statistics(textField.getText());可能发生在内部匿名类内部,也许在ActionListener内部,并且textField是局部变量.问题在于匿名内部类会使用它们所使用的本地字段进行拷贝,如果这些字段不是最终字段,则该副本可能与原始副本不同步,从而导致各种问题.

我建议您在类中而不是在方法或构造函数内部声明textField,从而使其成为类字段.如果您这样做,那么您将不必将其声明为final.

否则,如果您不能或不应该这样做,那么请确定并声明它(您不能广播")为最终结果.

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?

解决方案

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.

这篇关于当我尝试使用.getText()时,JTextField希望成为最终版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆