Saturday, February 18, 2012

JavaFX 2.0: Set Accelerator (KeyCombination) for menu items

Using setAccelerator(KeyCombination value) method, you can assign menu accelerator, a key combination that performs the same action as the menu item.

Example:
Set Accelerator for menu items
package javafx_exmenu;

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.control.*;
import javafx.scene.input.KeyCombination;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

/**
*
* @web http://java-buddy.blogspot.com/
*/
public class JavaFX_exMenu extends Application {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}

@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("java-buddy.blogspot.com");
Group root = new Group();
Scene scene = new Scene(root, 400, 300, Color.WHITE);

//Top Menu Bar
MenuBar menuBar = new MenuBar();

Menu menu1 = new Menu("Menu");

MenuItem menuItemA = new MenuItem("Item A");
menuItemA.setAccelerator(KeyCombination.keyCombination("Ctrl+A"));
menuItemA.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
System.out.println("Item A Clicked");
}
});

MenuItem menuItemB = new MenuItem("Item B");
menuItemB.setAccelerator(KeyCombination.keyCombination("Ctrl+B"));
menuItemB.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
System.out.println("Item B Clicked");
}
});

MenuItem menuItemC = new MenuItem("Item C");
menuItemC.setAccelerator(KeyCombination.keyCombination("Ctrl+C"));
menuItemC.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
System.out.println("Item C Clicked");
}
});

menu1.getItems().add(menuItemA);
menu1.getItems().add(menuItemB);
menu1.getItems().add(menuItemC);
menuBar.getMenus().add(menu1);

menuBar.prefWidthProperty().bind(primaryStage.widthProperty());
root.getChildren().add(menuBar);
primaryStage.setScene(scene);
primaryStage.show();
}
}


Related:
- JavaFX 2.0: Add menu

No comments:

Post a Comment