user824276
user824276

Reputation: 637

Multiple default buttons in JavaFX

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

Hypothesis: Oracle documentation states:

A default Button is the button that receives a keyboard VK_ENTER press, if no other node in the scene consumes it.

Hence, I guess the problem is that both buttons are in a single scene. Do you know how to get 2 tabs in JavaFX, each with a working default button?

Upvotes: 4

Views: 790

Answers (1)

James_D
James_D

Reputation: 209714

There can only be one default button: you want the button in the currently selected tab to be the default button. Simply add a listener to the selected property of each tab and make the corresponding button the default button, or use a 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);
    }
}

Upvotes: 5

Related Questions