martedì 23 novembre 2010

Catch mouse clicks on text in writer

In the API docs is not so clear how to add a MouseClickHandler or a MouseClickListener to the text in a writer document (or, probably, I couldn't find this information easly). What I wanted to do was to get the click position in form of a XTextRange or XTextCursor.

1. To add a MouseClickHandler to the text, you have to call this code using a valide XTextDocument

XUserInputInterception xui = (
if (xUserInputInterception != null) {
      xUserInputInterception.addMouseClickHandler(new MCH());

where MCH have to be a class implementing XMouseClickHandler, as explained in the next point.

2. You have to implement the XMouseClickHandler interface adding the disposing, mouseReleased and mousePressed methods . In order to get useful informations from the click, you can implement the mouseReleased nethod as shown below.

public class MCH implements XMouseClickHandler {
  public boolean mouseReleased(MouseEvent arg0) {
    // get the current component (you need a valid XDesktop)
    XComponent xCurrentComponent = xDesktop.getCurrentComponent();
    // get the XModel interface from the component
    XModel xModel = (XModel) UnoRuntime.queryInterface(XModel.class,
    // the model knows its controller
    XController xController = xModel.getCurrentController();
    // get the visible cursor Supplier from the controller
    XTextViewCursorSupplier xViewCursorSupplier = (XTextViewCursorSupplier)
          UnoRuntime.queryInterface(XTextViewCursorSupplier.class, xController);
    //get the visible cursor
    XTextViewCursor xViewCursor = xViewCursorSupplier.getViewCursor();
    //create an XTextCursor based on the position of the visible cursor
    //you need a referenc to the XTextDocument on wich you're working
    XTextCursor xModelCursor = xTextDocument.getText()

    //TODO make something with the cursor
    //i.e., you can print the word surrounded by the cursor
    XWordCursor xwc = (XWordCursor) UnoRuntime.queryInterface(
  XWordCursor.class, xModelCursor);

    return false;

Nessun commento: