What is instead of an action in JavaFX?

2020-05-01 09:35发布

Suppose I want to have my program to react same way, say, navigate to next record, in response to different events, including pressing a key, clicking GUI button, selecting menu item and so on.

This was done with "actions" in Swing.

Can I materialize this concept in some program object in JavaFX?

Or I should make a porridge of interacting objects?

标签: java javafx
2条回答
放荡不羁爱自由
2楼-- · 2020-05-01 10:24

Action is still there in JavaFX. Example belows how to create an action, bind it to a keyboard shortcut and share between two different elements.

Button go = new Button("Go");

EventHandler<ActionEvent> goAction = new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent arg0) {
        browser.load(location.getText(), new Runnable() {
            @Override
            public void run() {
                System.out.println("---------------");
                System.out.println(browser.getHTML());
            }
        });
    }
};

...

MenuItem menuItem = new MenuItem("Go!");
menuItem.setAccelerator(new KeyCodeCombination(KeyCode.G, KeyCombination.CONTROL_DOWN));

go.setOnAction(goAction);
menuItem.setOnAction(goAction);
查看更多
我命由我不由天
3楼-- · 2020-05-01 10:24

JavaFX provides many events. You also do this with setOn() method:

button.setOnKeyPressed(new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent t) {
       // code here
    }
});
查看更多
登录 后发表回答