2016-12-07 89 views

回答

1

您可以使用inputMethodRequests屬性檢索位置。您可以指定一個與選擇開始相關的索引來獲取char的屏幕座標。

private static ContextMenu createMenu(String... text) { 
    ContextMenu menu = new ContextMenu(); 
    EventHandler<ActionEvent> handler = evt -> { 
     TextInputControl control = (TextInputControl) menu.getUserData(); 
     String t = ((MenuItem) evt.getSource()).getText(); 
     control.replaceSelection(t); 
    }; 
    for (String s : text) { 
     MenuItem item = new MenuItem(s); 
     item.setOnAction(handler); 
     menu.getItems().add(item); 
    } 
    return menu; 
} 

@Override 
public void start(Stage primaryStage) { 
    ContextMenu menu = createMenu("Hello World", "42", "foo", "bar"); 
    TextArea textArea = new TextArea(); 

    TextField textField = new TextField(); 

    VBox root = new VBox(textArea, textField); 
    root.setPadding(new Insets(10)); 

    EventHandler<KeyEvent> handler = evt -> { 
     if (evt.isControlDown() && evt.getCode() == KeyCode.SPACE) { 
      evt.consume(); 
      TextInputControl control = (TextInputControl) evt.getSource(); 
      Point2D pos = control.getInputMethodRequests().getTextLocation(0); 
      menu.setUserData(control); 
      menu.show(control, pos.getX(), pos.getY()); 
      menu.requestFocus(); 
     } 
    }; 

    textArea.addEventFilter(KeyEvent.KEY_PRESSED, handler); 
    textField.addEventFilter(KeyEvent.KEY_PRESSED, handler); 

    Scene scene = new Scene(root); 

    primaryStage.setScene(scene); 
    primaryStage.show(); 
} 
相關問題