[英]JavaFX static/non static with Controllers
I've tried to make a little math program with JavaFX.我试图用 JavaFX 制作一个小数学程序。 I have a
Button
action in Controller 1:我在控制器 1 中有一个
Button
操作:
@FXML
public void showCalc(ActionEvent event2) {
layout.parabel_nullstelle_showCalc.setVariables(a, b, c, x1, x2, ze1, ze2, ze3, ze4, ze5, ze6, ze7);
Parent root3 = main.Main.getParent();
Scene showCalc = new Scene(root3, 500, 1000);
Stage paranullCalc = new Stage();
paranullCalc.setTitle("Rechung");
paranullCalc.setScene(showCalc);
paranullCalc.show();
}
It opens a new Stage
with Scene
which contains a calculation.它会打开一个带有
Scene
的新Stage
,其中包含一个计算。 In the Controller for the showCalc
I have the set variables method.在
showCalc
的控制器中,我有设置变量方法。
public static void setVariables(double a1, double b1, double c1,double x11, double x22, double ze11, double ze22, double ze33, double ze44, double ze55, double ze66, double ze77){
a = (float) a1;
b = (float) b1;
c = (float) c1;
x1 = (float) x11;
x2 = (float) x22;
ze1 = (float) ze11;
ze2 = (float) ze22;
ze3 = (float) ze33;
ze4 = (float) ze44;
ze5 = (float) ze55;
ze6 = (float) ze66;
ze7 = (float) ze77;
}
I needed to make it static because I can't do an object of a controller and with import I get the static/non static error.我需要使它静态,因为我不能做一个控制器的对象,并且通过导入我得到静态/非静态错误。 But now I want to change the text of a
TextArea
in the same Scene
as the setVariables
, so I can show the calculation.但是现在我想在与
setVariables
相同的Scene
更改TextArea
的文本,以便我可以显示计算。 I can't make the TextArea
static, because then it crashes.我无法将
TextArea
静态,因为它会崩溃。 I also can't access it without static and creating an object of itself also isn't a solution.如果没有静态,我也无法访问它,并且创建自己的对象也不是解决方案。 So how do I solve this?
那么我该如何解决这个问题呢?
Don't make variables or methods in your controller static
solely for the purpose of being able to access them from elsewhere.不要仅仅为了能够从其他地方访问它们而将控制器中的变量或方法设为
static
。 It rarely, if ever, makes sense to have static
members in a controller.在控制器中拥有
static
成员很少(如果有的话)有意义。
To access a method in a controller, just retrieve the controller instance from the FXMLLoader
.要访问控制器中的方法,只需从
FXMLLoader
检索控制器实例。 You haven't really posted enough code to provide a complete answer, but you need to do something like:您还没有真正发布足够的代码来提供完整的答案,但您需要执行以下操作:
FXMLLoader loader = new FXMLLoader(getClass().getResource("calc.fxml"));
Parent calcRoot = loader.load();
CalcController controller = loader.getController();
controller.setVariables(...);
Scene showCalc = new Scene(calcRoot, 500, 1000);
// ...
and remove static
from the setVariables
method declaration in the controller class.并从控制器类中的
setVariables
方法声明中删除static
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.