Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override default behavior of TAB in JTextPane

Tags:

java

swing

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?

like image 628
Itay Maman Avatar asked Feb 05 '09 13:02

Itay Maman


2 Answers

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.

like image 195
VonC Avatar answered Sep 19 '22 17:09

VonC


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

like image 21
Rastislav Komara Avatar answered Sep 20 '22 17:09

Rastislav Komara