我正在尝试使用 KeyboardFocusManager 在键入“<”字符时获取当前插入符号的位置。代码如下。如果在键入字符时文本字段为空,我希望插入符号的位置为 0。但是,我实际得到的结果是:0 0 1。谁能解释为什么会这样?
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class TextEditor {
@SuppressWarnings("serial")
public static class TextClass extends JTextArea {
static int startpos = 0;
public boolean checkKeyTyped (KeyEvent e) {
String keystr = Character.toString(e.getKeyChar());
switch (keystr) {
case "<":
startpos = getSelectionStart();
System.out.print(" " + startpos);
}
return false;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
final JTextArea textArea = new TextClass();
frame.add(textArea);
frame.setVisible(true);
// Add keyboard listener
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
return ((TextClass) textArea).checkKeyTyped(e);
}
});
}
}