简体   繁体   English

使用来自另一个 JavaFX 类 Java 的方法

[英]Use a method from another JavaFX class Java

So if you are familiar with JavaFX, Buttons objects can be modified with the following Node methods所以如果你熟悉JavaFX,可以使用以下Node方法修改Buttons对象

myButton.setTranslateX(10);
myButton.setTranslateY(-10);

Those methods works inside这些方法在里面起作用

public void start(Stage primaryStage) throws Exception {}

For which I understand, start is a method in Application to run JavaFX purpose.据我了解, startApplication中运行 JavaFX 目的的一种方法。 Since all myButton objects will have the same structure, i tried to make the following method in Main.java file由于所有myButton对象都具有相同的结构,因此我尝试在Main.java文件中创建以下方法

public void createMyButton(double X, double Y, String label, String image_path) throws Exception {
    this.setTranslateX(X);
    this.setTranslateY(Y);
    this.setText(label);
    //TO DO this.setButtonImage(src=image_path);
 }

However I understand that the methods inside createMyButton are from another class (from Node I think).但是我知道createMyButton中的方法来自另一个类(我认为来自Node )。 And (of course) i get the error而且(当然)我得到了错误

Cannot resolve method 'setTranslateX' in 'Main' s

since the compiler is looking those methods in my program, not in JavaFX SDK.因为编译器正在我的程序中查看这些方法,而不是在 JavaFX SDK 中。 How can I call other class methods in my own methods?如何在自己的方法中调用其他类方法? I tried with我试过

public void createMyButton(bla bla) throws Exception extends Node
public void createMyButton(bla bla) throws Exception extends Application

but i think Iam completely outside the diamond.但我认为我完全在钻石之外。 I also trying to make my own class which inherits methods from other class but it's a little bit outside of my current knowledge and i was wondering if there is a easier/ straighter way to do it我还尝试创建自己的classclass继承其他class方法,但这有点超出我目前的知识范围,我想知道是否有更简单/更直接的方法来做到这一点

I'm not a JavaFX person but I think the issue is that you're calling this.setTranslateX(X);我不是 JavaFX 人,但我认为问题在于您正在调用this.setTranslateX(X); in a method where this is not a button (I think it's a Main object perhaps, need to see more code to be sure).this不是按钮的方法中(我认为它可能是一个 Main 对象,需要查看更多代码才能确定)。

Try this:尝试这个:

public Button createMyButton(double X, double Y, String label, String image_path) throws Exception {
    Button button = new Button(...) // not sure how you're initialising your buttons normally
    button.setTranslateX(X);
    button.setTranslateY(Y);
    button.setText(label);
    button.setButtonImage(src=image_path);
    return button
}

Then, elsewhere when you want to create a button, you'd call the method instead:然后,当您想在其他地方创建按钮时,您可以调用该方法:

Button button = createMyButton(10, 20, "My Button", "images/button.png")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM