I wrote some code and everything worked fine, but when I open the same code on another computer, I get the following errors:
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
The code that gives this error:
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;
}
I've looked for a solution for my problem and have found many of them that are alike, but the given solutions never solve my problem.
EDIT: using Java8
EDIT2: I appreciate the answers, but those were the answers I found by googling the problem. They don't really solve the problem. The code I pasted here works fine on every computer I ran it on and on the computer of my project partner, but not on mine. Changing the objects to final works, but isn't really what I'm looking for.