tags:

views:

278

answers:

2

I am implementing a JTextPane-based text editor. Currently, when I have a piece of selected text, pressing the TAB key deletes the selected text. I would like to change this behavior such that TAB will indent the selected text.

How to go about it?

+4  A: 

Something along the line of:

public void keyPressed ( KeyEvent event ) {
     switch ( event.getKeyCode ()) {
      case KeyEvent.VK_TAB :
       insertTabChar ( event.isShiftDown ());
       event.consume ();
       break;
      case KeyEvent.VK_ENTER :
       snapshot ();
       insertNewLine ();
       event.consume ();
       break;
     }
    }

You have some classes out there which do just that, like this one.

In particular, the function

    /**
     * manage keyboard tabbing, implementing blockindent.
     * @param isUnindent
     */
    private void insertTabChar ( boolean isUnindent ) {

     snapshot (); // snapshot current setup

     if ( isSelection ) { // blockindent

might do just what you need.

VonC
I had to do that before, it looks right from here.
geowa4
+1  A: 

The other way is to redefine action for JTextArea component associated with TAB key. Take look at ActionMap.

Rastislav Komara