Frage

There is a ContextMenu which has two options and when the second option (item2 in the code) is pressed with the right mousebutton I want it to print out some text so I know I did actually activate it. Up till now nothing happens when I click on the second mousebutton.

I haven't had much experience yet with Eventhandlers so my apologies if I made a noobish mistake.

private void maakContextMenu() {
    menu = new ContextMenu();
    MenuItem item = new MenuItem("Kleur Assen");
    MenuItem item2 = new MenuItem("tweede optie");
    final LissajousCanvas canvas = this;
    item.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            new KiesKleur(canvas).show();
        }
    });
    item2.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>(){

        @Override
        public void handle(MouseEvent t) {
            System.out.println("in the loop");
            if(t.getSource()==MouseButton.SECONDARY){
                System.out.println("in too deep");
            }
            new KiesKleur(canvas).show();
        }

    });
    menu.getItems().addAll(item, item2);
}
War es hilfreich?

Lösung

A MenuItem is not actually a Node, so it's not part of the scene graph in the way that Nodes are. So I'm not really sure if this is a bug or not; I think it probably only implements EventTarget so it can specifically generate ActionEvents. You'll have noticed there is no setOnMouseClicked(...) method available.

Here's a workaround. I'm not sure why it only works with MOUSE_PRESSED and not with MOUSE_CLICKED, but it's likely something to do with the default mouse event handling that generates the action events:

private void maakContextMenu() {
    menu = new ContextMenu();
    MenuItem item = new MenuItem("", new Label("Kleur Assen"));
    Label menuItem2Label = new Label("tweede optie");
    MenuItem item2 = new MenuItem("", menuItem2Label);
    final LissajousCanvas canvas = this;
    item.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            new KiesKleur(canvas).show();
        }
    });
    menuItem2Label.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>(){

        @Override
        public void handle(MouseEvent t) {
            System.out.println("in the loop");
            if(t.getButton()==MouseButton.SECONDARY){
                System.out.println("in too deep");
            }
            new KiesKleur(canvas).show();
        }

    });
    menu.getItems().addAll(item, item2);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top