在没有FXML的情况下从另一个类访问Javafx元素

问题描述 投票:0回答:1

我正在使用Javafx8并且假设我创建了许多ui项目(如按钮等等)。我认为将这些按钮的所有EventHandler放入一个separate类是个好主意。我的问题是:如何从EventHandler访问任何按钮,例如以任何其他方式对其进行处理或操纵。

这是一个带有两个按钮和EventHandlers的单独类的最小示例

假设这是我的Start类:

public class App extends Application
{
    @Override
    public void start(Stage primaryStage) throws Exception {
        Button b1 = new Button();
        b1.setOnAction(ListenerClass.createB1Event());
        Button b2 = new Button();
        b2.setOnAction(ListenerClass.createB2Event());

        VBox vbox = new VBox(b1, b2);

        Scene scene = new Scene(vbox, 200, 200);

        primaryStage.setTitle("App");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main( String[] args )
    {
        Application.launch(args);
    }
}

我的(单独的)监听器类:

public class ListenerClass {

    public static EventHandler<ActionEvent> createB1Event() {
        return new EventHandler<ActionEvent>() {
            public void handle(ActionEvent t) {
                //Access here to b1 and b2...
                //Deactivate B1
                //Activate B2
            }
        };
    }

    public static EventHandler<ActionEvent> createB2Event() {
        return new EventHandler<ActionEvent>() {
            public void handle(ActionEvent t) {
                //Access here to b1 and b2...
                //Activate B1
                //Dectivate B2
            }
        };
    }
}

谢谢

java javafx eventhandler
1个回答
1
投票

所以基于你的校长。您希望禁用位于vbox中并按下的按钮,并启用该vbox中的所有其他按钮。而你的问题是如何找到被按下的按钮。

您需要使用ActionEvent.getSource()方法。

继承人我是如何编码的....

这是Start类:

public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
    VBox vbox = new VBox();
    Button b1 = addNewButton("Button1",vbox);
    Button b2 = addNewButton("Button2",vbox);
    Button b3 = addNewButton("Button3",vbox);


    Scene scene = new Scene(vbox, 200, 200);

    primaryStage.setTitle("App");
    primaryStage.setScene(scene);
    primaryStage.show();
}

public static Button addNewButton(String label, VBox ownerVBox){
    Button button = new Button(label);
    ownerVBox.getChildren().add(button);
    button.setOnAction(ListenerClass.createBEvent());
    return button;
}


public static void main(String[] args) {
    launch(args);
}
}

听众课程:

public class ListenerClass {

public static EventHandler<ActionEvent> createBEvent() {
    return new EventHandler<ActionEvent>() {
        public void handle(ActionEvent t) {
            Button b = (Button) t.getSource();
            VBox vbox =(VBox) b.getParent();
            vbox.getChildren().forEach(button-> {
                button.setDisable(false);
            });
            b.setDisable(true);
        }
    };
}

}
© www.soinside.com 2019 - 2024. All rights reserved.