首页 > 解决方案 > Swing context menu on JavaFX Chart

问题描述

I am working on an application primarily in swing, though the chart dialog uses JavaFX. (Chart in a GridPane in a JFXPanel to be exact.)

First, Chart does not implement a setContextMenu method to use a JFX ContextMenu. I have seen a workaround by attaching a handler to the right click of the chart, but the menu is not removed from the GUI when it loses focus, rather it persists until the user either 1) triggers it to open again or 2) clicks a MenuItem.

chart.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
    @Override
    public void handle(MouseEvent t) {
        if (t.getButton() == MouseButton.SECONDARY) {
            contextMenu.show(chart, t.getScreenX(), t.getScreenY());
        }
    }
});

That said, I would prefer to use a Swing JPopupMenu instead. How can I bind this to my Chart and maintain a natural behavior?

Thank you!

标签: javaswingjavafxchartsjava-7

解决方案


我确定不可能使用JPopupMenu.

ContextMenu添加到JLabel

Label contextMenuLabel = new Label();
grid.add(contextMenuLabel, 0, 0); // Add to the same grid after adding the chart
contextMenuLabel.setPrefSize(width, height);
contextMenuLabel.setMinSize(width, height);
contextMenuLabel.setMaxSize(width, height);

ContextMenu contextMenu = new ContextMenu();

contextMenuLabel.setContextMenu(contextMenu);

推荐阅读