@FXML public static vars in javafx? [duplicate]

2019-07-25 17:09发布

This question already has an answer here:

I'm introducing in javafx and i found it very interesting. But I have got a problem that i can't solve. In the simplest case of a Hello World I can't put a @FXML public static var like this:

public class FXMLDocumentController implements Initializable 
{

    @FXML
    public static Label label;

    @FXML
    private void handleButtonAction(ActionEvent event) 
    {
        System.out.println("You clicked me!");
        label.setText("Hello World!");
    }  
}

If I change it to private it works. The cause of that I want to made this vars publics is because I'm using diferents controllers for diferents views (in my real app) and i want to communicate between theirs.

PS: Sorry for my bad english

2条回答
爷的心禁止访问
2楼-- · 2019-07-25 17:56

You should not use a static field here. Your controller belongs to one view and every time the view is created by the FXML Loader new instances of all nodes in the view will be created. SO by calling the FXML Loader 2 times you will receive 2 instances of the view. In addition a new instance of your controller class will be created whenever you load the view by using the FXML viewer. By using a static field you will override values of old controller instances and this will end in horrible bugs. Here is a short introduction to the static keyword: What does the 'static' keyword do in a class?

If you just remove "static" it will work. Instead of using public fields you should add getter and setter methods to your controller class and mark the field as private: Why use getters and setters?

查看更多
啃猪蹄的小仙女
3楼-- · 2019-07-25 18:07

I want to do something similar like this: I'm working with tabs and i have this two controllers:

FXML_Tab1Controller.java:

public class FXML_Tab1Controller implements Initializable {

FXML_Tab2Controller tab2controller;

@FXML public Label Label1;
@FXML public TextField TextField1;
@FXML public Button Button1;
/**
 * Initializes the controller class.
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    // TODO
} 

@FXML private void actionButton1(ActionEvent event)
{
    Label1.setText(tab2controller.TextField2.getText());
}

}

FXML_Tab2Controller.java:

public class FXML_Tab2Controller implements Initializable {

FXML_Tab1Controller tab1controller;
@FXML public Label Label2;
@FXML public TextField TextField2;
@FXML public Button Button2;
/**
 * Initializes the controller class.
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    // TODO
} 

@FXML private void actionButton2(ActionEvent event){
        Label2.setText(tab1controller.TextField1.getText());
}

}

something similar like that video: https://www.youtube.com/watch?v=XLVx46ycxco

查看更多
登录 后发表回答