01: package isql;
02:
03: import java.awt.*;
04: import java.awt.event.*;
05: import javax.swing.text.*;
06: import javax.swing.*;
07:
08: // only listens for Control N. needs to be replaced with keymap
09: public class TabKeyListener implements KeyListener {
10: private JTextArea jt;
11:
12: public TabKeyListener(JTextArea jta) {
13: jt = jta;
14: }
15:
16: public void keyTyped(KeyEvent e) {
17: }
18:
19: public void keyPressed(KeyEvent e) {
20: if (e.isControlDown()) {
21: switch (e.getKeyCode()) {
22: //case e.VK_N:
23: case java.awt.event.KeyEvent.VK_N:
24: int pos = jt.getCaretPosition();
25: if (pos == 0)
26: return;
27: String s = getLastWord(pos);
28: if (s == null)
29: return;
30: // check if there is a match
31: String m = getLastMatchingWord(pos - s.length(), s);
32: if (m == null)
33: return; // no match found
34: jt.replaceRange(m, pos - s.length(), pos);
35: break;
36: }
37: }
38:
39: }
40:
41: public void keyReleased(KeyEvent e) {
42: }
43:
44: private String getLastWord(int offset) {
45: String lastline;
46: int spos = 0;
47: try {
48: lastline = jt.getText(0, offset);
49:
50: int i = offset - 1;
51: while (i-- > spos) {
52: if (Character.isWhitespace(lastline.charAt(i)))
53: break;
54: }
55: // i contains the last space
56: i++;
57: if (i < 0)
58: i = 0; // added since space in beg throws SOB ex
59: return lastline.substring(i);
60: } catch (BadLocationException e) {
61: return null;
62: }
63: }
64:
65: private String getLastMatchingWord(int offset, String patt) {
66: try {
67: String line = jt.getText(0, offset);
68: int where = line.lastIndexOf(patt);
69: if (where < 0)
70: return null;
71:
72: int i = where;
73: //String line = jt.getText(where, offset);
74: while (i++ < offset) {
75: if (Character.isWhitespace(line.charAt(i)))
76: break;
77: }
78: return line.substring(where, i);
79: } catch (BadLocationException e) {
80: return null;
81: }
82: // for cases where user may send a space of whitespace. we dont
83: // want to have lotsof validations for such freak cases
84: catch (StringIndexOutOfBoundsException e) {
85: return null;
86: }
87: }
88:
89: }
|