JavaFX ContextMenu accelerator firing from wrong tab

我的未来我决定 提交于 2020-02-24 05:36:46

问题


I have a TabPane with two tabs, each with a TableView which has a context menu. The two context menus have duplicate accelerators, but I expect only the currently selected tab to respond. But what happens is only the last added Tab seems to get the event, even if it's not selected. Below is a complete sample code:

package sample;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.KeyCombination;
import javafx.stage.Stage;

public class Main extends Application {

@Override
public void start(Stage primaryStage) throws Exception{
    Tab t1 = new Tab("Tab 1");
    TableView<Void> tv1 = new TableView<>();
    t1.setContent(tv1);
    MenuItem mi1 = new MenuItem("Action 1");
    mi1.setAccelerator(KeyCombination.valueOf("F3"));
    mi1.setOnAction(event->System.out.println("Action 1!"));
    ContextMenu ctx1 = new ContextMenu(mi1);
    tv1.setContextMenu(ctx1);

    Tab t2 = new Tab("Tab 2");
    TableView<Void> tv2 = new TableView<>();
    t2.setContent(tv2);
    MenuItem mi2 = new MenuItem("Action 2");
    mi2.setAccelerator(KeyCombination.valueOf("F3"));
    mi2.setOnAction(event->System.out.println("Action 2!"));
    ContextMenu ctx2 = new ContextMenu(mi2);
    tv2.setContextMenu(ctx2);

    TabPane tabPane = new TabPane(t1, t2);
    tabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);
    primaryStage.setScene(new Scene(tabPane));
    primaryStage.show();
}


public static void main(String[] args) {
    launch(args);
}
}

I expect "Action 1!" to be printed when Tab 1 is selected, and "Action 2!" to be printed when Tab 2 is selected, but in reality "Action 2!" is printed regardless of which tab is selected. How do I solve this, so the correct action is performed depending on which tab (TableView) is currently visible?


回答1:


I guess you've come across https://bugs.openjdk.java.net/browse/JDK-8088068 (see there for a workaround). JavaFX ist not really prepared for the same accelerator to be installed in multiple MenuItems.



来源:https://stackoverflow.com/questions/34198022/javafx-contextmenu-accelerator-firing-from-wrong-tab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!