Issue
I have a question regarding JavaFX buttons. I have a set 4 buttons on my scene. The first three buttons are labelled "Home", "Account", "Map". The last button is called "Go".
I am using button.setOnAction(new EventHandler<ActionEvent>(){ })
for each button to control the event it will trigger. My issue is that I want to click on one of the first three buttons (account, home, map) , but not action that event until the "go" button has been clicked.
For example, I click on home, the button changes colour to show it has been clicked. I press go, and the action associated with the home button will be actioned. How do I do something like this?
Another question i had is how do I ensure only one of the first three buttons (Home, Account, and Map, is clicked at a time. If I had first clicked "Home", then "Map" then "Go" I want to action the Map event, so home would be released when map is pressed.
I appreciate any help :)
Solution
As noticed in the comments you can use ToggleButton
(or RadioButton
) for "Home", "Account" and "Map", and add them to a ToggleGroup
:
public class App extends Application {
@Override
public void start(Stage stage) {
ToggleButton buttonHome = new ToggleButton("Home");
ToggleButton buttonAccount = new ToggleButton("Account");
ToggleButton buttonMap = new ToggleButton("Map");
ToggleGroup group = new ToggleGroup();
group.getToggles().addAll(buttonHome, buttonAccount, buttonMap);
Button buttonGo = new Button("Go");
// Disable button "Go" when no other button is selected (remove this line if not needed)
buttonGo.disableProperty()
.bind(group.selectedToggleProperty().isNull());
buttonGo.setOnAction(e -> {
ToggleButton selected = (ToggleButton)group.getSelectedToggle();
if (selected != null) {
System.out.println(selected.getText());
}
});
HBox buttons = new HBox(5, buttonHome, buttonAccount, buttonMap);
VBox pane = new VBox(10, buttons, buttonGo);
pane.setAlignment(Pos.CENTER_RIGHT);
Scene scene = new Scene(pane);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
Output:
If you replace all ToggleButton
with RadioButton
:
Answered By - Oboe