我写了一些代码,一切正常,但是当我在另一台计算机上打开相同的代码时,出现以下错误:
Cannot refer to the non-final local variable usernameTextField defined in an enclosing scope
Cannot refer to the non-final local variable portTextField defined in an enclosing scope
Cannot refer to the non-final local variable usernameTextField defined in an enclosing scope
Cannot refer to the non-final local variable portTextField defined in an enclosing scope
Run Code Online (Sandbox Code Playgroud)
给出此错误的代码:
private static GridPane initGUI(){
GridPane root = new GridPane();
TextField usernameTextField = new TextField();
TextField portTextField = new TextField();
Button button = new Button("Login!");
root.add(new Label("Username:"),0,0);
root.add(new Label("Port:"),0,1);
root.add(usernameTextField,1,0);
root.add(portTextField,1,1);
root.add(button, 0, 2);
/* Button action */
button.setOnAction(new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent event) {
boolean portCorrect = true;
String username = usernameTextField.getText();
int port = 0;
/* Try casting to integer*/
try{
port = Integer.parseInt(portTextField.getText());
}catch(NumberFormatException e){
portCorrect = false;
}
/* Invalid username or port*/
if(username.length() < 1 && portCorrect){
usernameTextField.clear();
portTextField.clear();
}
}
});
return root;
}
Run Code Online (Sandbox Code Playgroud)
我已经为我的问题寻找了解决方案,并且发现了许多相似的解决方案,但是给定的解决方案从未解决我的问题。
编辑:使用 Java8
EDIT2:我很欣赏这些答案,但这些是我通过谷歌搜索问题找到的答案。他们并没有真正解决问题。我粘贴在这里的代码在我运行它的每台计算机和我的项目合作伙伴的计算机上都可以正常工作,但在我的计算机上却没有。将对象更改为最终作品,但这并不是我真正想要的。
可能您使用的是 java 8,而另一台计算机使用的是 java 7。Java 要求对来自内部类的变量的引用作为最终变量。如果您不重新分配,Java 8 将使它们有效地成为最终版本。
将最终添加到:
final GridPane root = new GridPane();
final TextField usernameTextField = new TextField();
final TextField portTextField = new TextField();
final Button button = new Button("Login!");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8784 次 |
| 最近记录: |