Multiple default buttons in JavaFX

I have a JavaFX application with two tabs in tabPane. And I would like for each tab to have a default button (button with defaultButton = "true"). However, only the button on the first tab responds to Enter key presses. The button on the second tab ignores Enter key presses.

Hypothesis : Oracle documentation :

The default button is the button that receives the VK_ENTER keyboard; click if no other node in the scene uses it.

Therefore, I think the problem is that both buttons are in the same scene. Do you know how to get 2 tabs in JavaFX, each with a default work button?

+4
source share
1 answer

There can only be one default button: you want the button on the currently selected tab to be the default button. Just add a listener to the selected property of each tab and make the corresponding button the default button or use the binding to achieve the same:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class MultipleDefaultButtons extends Application {

    @Override
    public void start(Stage primaryStage) {
        TabPane tabPane = new TabPane();
        tabPane.getTabs().addAll(createTab("Tab 1"), createTab("Tab 2"));
        primaryStage.setScene(new Scene(tabPane, 400, 400));
        primaryStage.show();
    }

    private Tab createTab(String text) {
        Tab tab = new Tab(text);
        Label label = new Label("This is "+text);
        Button ok = new Button("OK");

        ok.setOnAction(e -> System.out.println("OK pressed in "+text));

        VBox content = new VBox(5, label, ok);
        tab.setContent(content);

        ok.defaultButtonProperty().bind(tab.selectedProperty());

        return tab ;
    }

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

Source: https://habr.com/ru/post/1663655/


All Articles