Reputation: 890
I'm new to JavaFX and I'm making my first application a simple hangman game, as it is something I've done before in swing.
In the game, I have constructed a keyboard, but I can't figure out how to make all of my buttons 'not focused' when the game starts, so it looks like this
Notice how the 'Q' is darkened. I considered a jankey approach, like having a button outside the scene that does nothing but acts as default focus button, but I would really like to know the correct way to do this. All my research has only told how to make a specific button focused.
Thanks a ton to anyone willing to help.
Upvotes: 0
Views: 1570
Reputation: 9989
I think what @Sedrick mentioned is correct. You can just focus on any layout node by default.
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class DefaultFocusDemo extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
VBox root = new VBox();
root.setAlignment(Pos.CENTER);
root.setSpacing(20);
Scene sc = new Scene(root, 500, 500);
primaryStage.setScene(sc);
primaryStage.show();
ToggleButton btn1 = new ToggleButton("Button 1");
ToggleButton btn2 = new ToggleButton("Button 2");
ToggleButton btn3 = new ToggleButton("Button 3");
ToggleButton btn4 = new ToggleButton("Button 4");
HBox hb1 = new HBox();
hb1.setAlignment(Pos.CENTER);
hb1.getChildren().addAll(btn1, btn2);
HBox hb2 = new HBox();
hb2.setAlignment(Pos.CENTER);
hb2.getChildren().addAll(btn3, btn4);
root.getChildren().addAll(hb1, hb2);
hb1.requestFocus();
}
}
Upvotes: 1
Reputation: 108
You have the right idea. Create an off-screen button and make sure it has starting focus.
Upvotes: 1