javaswttext-editore4listeners

how to implement ctrl+backspace and ctrl+delete for a text edior in swt


I have created an SWT text editor and also have implemented the cut, copy and paste features but now I need to implement CTRL + BACKSPACE, to delete the preceding word, and CTRL + DEL, to delete the proceeding word.

The code which copied text

private class Copy implements SelectionListener{
    public void widgetSelected(SelectionEvent event) {  
        Display.getDefault().asyncExec(new Runnable() {
            @Override
            public void run() {     
                copySelectedMessages();
            }

            private void copySelectedMessages(){
                //StringBuffer stringCopied =new StringBuffer();

                String textData = editor.getSelectionText();
                //TextTransfer textTransfer = TextTransfer.getInstance();

                System.out.println("you hv selected"+textData);

                //Clipboard clipboard = new Clipboard(Display.getDefault());
                TextTransfer transfer = TextTransfer.getInstance();      
                clipboard.setContents(new Object[] { textData }, new TextTransfer[] { transfer });
            }
        });
    }
}

The code for the editor

editor = new StyledText( this, SWT.MULTI | SWT.V_SCROLL );
editor.setLayoutData( new GridData(GridData.FILL_BOTH) );
editor.setFont( new Font(Display.getDefault(),"Cambria", 10, SWT.NORMAL) );

The listener

proceeding.addSelectionListener(new proceed());

private class proceed implements SelectionListener{
    public void widgetSelected(SelectionEvent event) {      
        Display.getDefault().asyncExec(new Runnable() {
            @Override
            public void run() {      
                // Code to check for CTRL + backspace and CTRL + delete
            }
    });
}

So now how can CTRL+BACKSPACE and CTRL+ DELETEfunctionality can be implemented in SWT.


Solution

  • addSelectionListener() is the wrong method to use here; use addKeyListener() and then a KeyAdapter to process the events.

    java2s has an example: http://www.java2s.com/Code/JavaAPI/org.eclipse.swt.custom/StyledTextaddKeyListenerKeyListenerkey.htm

    or here for a more complete one: http://www.java2s.com/Tutorial/Java/0280__SWT/Asimpleeditor.htm

    Your code to implement "copy to clipboard" is not necessary since StyledText already implements this. Just call the copy() method. The second example shows how to install a global listener for Ctrl+C via a menu item.

    As for how to delete the next or previous word, call st.invokeAction() with ST.DELETE_WORD_NEXT or ST.DELETE_WORD_PREVIOUS (org.eclipse.swt.custom.ST).

    By default, those actions are bound to Ctrl+BackSpace and Ctrl+Delete. But again, those keys only trigger the action when the widget has the focus. If you want to enable them no matter which widget in the window has the focus, then create a menu item.