0

I created a LoginFieldsController custom controller that inherits from the VBox class. Later in the programs I use this controller as an ordinary node like Button, TextFiled, etc. Please note that I only write pure Java code, I do not use FXML.

Question: is it better to declare LoginFieldsController nodes as the fields of the LoginFieldsController class, or inside the LoginFieldsController constructor? Outside the constructor I was doing nothing.

In other words, it would be better like this:

public class LoginFieldsController extends VBox {
    private TextField loginField;
    private TextField passwordField;

    public LoginFieldsController( ... ) {
        loginField = new TextFeild("Login");
        passwordField = new TextFeild("Password"); 
        this.addAll(loginField, passwordField);
        ...
}

Or that:

public class LoginFieldsController extends VBox {

    //no fields in that class

    public LoginFieldsController( ... ) { 
        TextField loginField = new TextFeild("Login");
        TextField passwordField = new TextFeild("Password"); 

        this.addAll(loginField, passwordField);
        ...
}
4

2 回答 2

0

我强烈建议在构造函数之外将它们声明为字段。这样,当您需要对它们执行某些操作时,您可以通过其他方法访问它们。如果您需要在对象实例化时注入这些字段,您可以使用构造函数注入这些字段,或者您可以让 setter 稍后注入它们。

考虑以下代码:

Class Example{

  public Example(...){
    TextField text1 = new TextField();
    //some other code
  }

  public boolean checkData(){
    //text1 is not visible here
  }

另一方面:

Class Example{

  TextField text1; 

  public Example(...){
    text1 = new TextField();
    //some other code
  }

  public boolean checkData(){
    //text1 is visible here
  }

在旁注中,我将仅将图形元素(例如您的示例中的 VBox)用于视图部分(猜测您使用 MVC,因为您正在使用控制器)并编写一个单独的控制器类。

于 2019-02-18T14:49:14.823 回答
0

最好将它们保留在构造函数之外,特别是如果您稍后需要访问它们(例如获取它们的当前值)

于 2019-02-18T14:43:36.500 回答