Java:不能引用非final变量

时间:2016-03-31 13:54:41

标签: java eclipse javafx

我写了一些代码,一切正常,但当我在另一台计算机上打开相同的代码时,我收到以下错误:

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

出现此错误的代码:

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;
}

我已经为我的问题寻找解决方案,并找到了许多相似的解决方案,但是给定的解决方案永远无法解决我的问题。

编辑:使用Java8

EDIT2:我很欣赏答案,但这些是我通过Google搜索问题找到的答案。他们并没有真正解决问题。我在这里粘贴的代码在我运行它的每台计算机上以及我项目合作伙伴的计算机上运行正常,但不在我的计算机上。将对象更改为最终作品,但并非我真正想要的。

2 个答案:

答案 0 :(得分:3)

可能你正在使用java 8而另一台计算机正在使用java 7.Java要求从内部类中引用变量作为最终变量。如果不重新分配,Java 8将使它们成为最终版本。

将final添加到:

final GridPane root = new GridPane();
final TextField usernameTextField = new TextField();
final TextField portTextField = new TextField();
final Button button = new Button("Login!");

答案 1 :(得分:1)

您无法使用匿名类(new EventHandler(){...})中的变量,这些变量未标记为最终类或封闭类中的字段。因此,在您的情况下,最简单的解决方案是创建变量final

...
final TextField usernameTextField = new TextField();
final TextField portTextField = new TextField();
...
相关问题