在我的应用程序中,我想在系统菜单和上下文菜单中显示相同的菜单项。例如,“复制”菜单项。在上下文菜单中,我还想显示加速键(与系统菜单上的相同)。
出现问题的地方:如果在两个菜单上设置加速器,则两个菜单项都会被触发。当然,这不是我想要的......
有没有办法防止这种情况发生?我目前的解决方法是不显示上下文菜单的加速器,但这不是我想要的。
那么有什么方法可以在菜单中显示加速器而不是开火?
带有上下文菜单和系统菜单的示例代码。 如果按CMD / CTRL-C,它将触发两个处理程序: - (
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test_menu;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
*
* @author Hayo Baan
*/
public class Test_Menu extends Application {
@Override
public void start(Stage primaryStage) {
// Event handler
EventHandler<ActionEvent> eventHandler = (ActionEvent event) -> {
System.out.println("Got event from " + ((MenuItem) event.getSource()).getText());
event.consume();
};
// The system menubar
MenuBar menuBar = new MenuBar();
menuBar.setUseSystemMenuBar(true);
// Edit menu with Copy item
Menu editMenu = new Menu("Edit");
menuBar.getMenus().add(editMenu);
MenuItem editCopy = new MenuItem("Edit Copy");
editCopy.setAccelerator(KeyCombination.keyCombination("Shortcut+C"));
editMenu.getItems().add(editCopy);
editCopy.setOnAction(eventHandler);
// Context menu with copy item
ContextMenu contextMenu = new ContextMenu();
MenuItem contextCopy = new MenuItem("Context Copy");
contextCopy.setAccelerator(KeyCombination.keyCombination("Shortcut+C"));
contextMenu.getItems().add(contextCopy);
contextCopy.setOnAction(eventHandler);
Label label = new Label("Say 'Hello World'");
VBox root = new VBox();
root.getChildren().addAll(menuBar, label);
label.setContextMenu(contextMenu);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
答案 0 :(得分:0)
您拥有的是EventHandlers
的两个实例,它们对同一个组合键做出反应。您可以通过定义EventHandler
一次来解决问题,对两种菜单类型都使用if并使用事件:
EventHandler evtHandler = event -> {
System.out.println("Execute copy event");
event.consume();
};
...
editCopy.setOnAction(evtHandler);
...
contextCopy.setOnAction(evtHandler);