I want my JavaFX program to be able to dynamically change the accelerator for menu items. However, I can't seem to get it to work in JavaFX 2.2. In the code below, the first menu item has an accelerator "Ctrl+M" and it works fine. "Ctrl+M" is printed every time the menu item is selected using a mouse or with the keyboard accelerator Ctrl+M. The second menu item attempts to change the first men item's accelerator to "Ctrl+L". After choosing the second menu item, I can click on the first menu item again and it shows that its new accelerator is "Ctrl+L", but I cannot use the keyboard accelerator Ctrl+L to activate the first menu item. Instead, I still need to use Ctrl+M to activate the first menu item. Any suggestions on what is going wrong here?
/*
* from code at <http://java-buddy.blogspot.com/2012/02/javafx-20-set-accelerator.html>
*/
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.KeyCombination;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class AcceleratorExample extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Accelerator example");
Group root = new Group();
Scene scene = new Scene(root, 400, 300, Color.WHITE);
MenuBar menuBar = new MenuBar();
Menu FileMenu = new Menu("File");
final MenuItem item1 = new MenuItem("Select me");
item1.setAccelerator(KeyCombination.keyCombination("Ctrl+M"));
item1.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
System.out.println(item1.getAccelerator());
}
});
final MenuItem item2 = new MenuItem("New accel");
item2.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
item1.setAccelerator(KeyCombination.keyCombination("Ctrl+L"));
}
});
FileMenu.getItems().add(item1);
FileMenu.getItems().add(item2);
menuBar.getMenus().add(FileMenu);
menuBar.prefWidthProperty().bind(primaryStage.widthProperty());
root.getChildren().add(menuBar);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Dynamically changing the accelerator has iffy behaviour at present, but this is a bug which has been fixed for 8u20:
https://javafx-jira.kenai.com/browse/RT-35182
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With