First Button in a ButtonBar is always focused?

490 views Asked by At

I am currently developing a JavaFX application and there I used a ButtonBar with some Buttons. When I run the program, the first Button is always focused. How can I disable that setting?

enter image description here

P.S.: I used some CSS code to change the default appearance and that brown box conveys that the button is focused.

1

There are 1 answers

0
anko On

You can take away the focus from the button with otherNode.requestFocus():

Requests that this Node get the input focus, and that this Node's top-level ancestor become the focused window. To be eligible to receive the focus, the node must be part of a scene, it and all of its ancestors must be visible, and it must not be disabled. If this node is eligible, this function will cause it to become this Scene's "focus owner". Each scene has at most one focus owner node. The focus owner will not actually have the input focus, however, unless the scene belongs to a Stage that is both visible and active (docs).

Like in this example:


import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.stage.Stage;

import java.util.stream.IntStream;

public class App extends Application {

    @Override
    public void start(Stage stage) {
        // Create controls:
        ButtonBar buttonBar = new ButtonBar();
        IntStream.range(0, 3).forEach(i -> buttonBar.getButtons().add(new Button("Button " + i)));
        
        // This takes away the focus from the button:
        Platform.runLater(buttonBar::requestFocus); // (Does not have to be the buttonBar itself)
        
        // Prepare and show stage:
        stage.setScene(new Scene(buttonBar));
        stage.show();
    }

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