javafx中的@FXML公共静态变量? [英] @FXML public static vars in javafx?

查看:480
本文介绍了javafx中的@FXML公共静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用javafx进行介绍,我发现它非常有趣.但是我有一个我无法解决的问题. 在Hello World的最简单情况下,我不能像这样放置@FXML公共静态变量:

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!");
    }  
}

如果我将其更改为私有,则可以使用. 我之所以要将此vars公开,是因为我在我的真实应用程序中使用了针对不同视图的Differents控制器,并且希望在它们之间进行交流.

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:对不起,我的英语不好

PS: Sorry for my bad english

推荐答案

您不应在此处使用静态字段.您的控制器属于一个视图,并且每次由FXML Loader创建该视图时,都会创建该视图中所有节点的新实例.通过调用FXML Loader 2次,您将收到2个视图实例.此外,每当您使用FXML查看器加载视图时,都将创建控制器类的新实例.通过使用静态字段,您将覆盖旧控制器实例的值,这将以可怕的错误结束.以下是对static关键字的简短介绍:静态"关键字可以在课程中使用吗?

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?

如果仅删除静态",它将起作用. 而不是使用公共字段,您应该在控制器类中添加getter和setter方法,并将该字段标记为私有:为什么使用吸气剂和吸气剂?

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?

这篇关于javafx中的@FXML公共静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆