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?
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.
The other way is to redefine action for JTextArea component associated with TAB key. Take look at ActionMap.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With