简体   繁体   English

使用KeyboardFocusManager按下键时获得插入符的位置

[英]Get caret position when key pressed using KeyboardFocusManager

I'm trying to get the current caret position when the "<" character is typed, using a KeyboardFocusManager. 我正在尝试使用KeyboardFocusManager键入“ <”字符时获得当前插入符号的位置。 Code below. 下面的代码。 If the text field is empty when they character is typed I would expect the caret position to be 0. However, the result I actually get is this: 0 0 1. Could anyone explain why this is happening? 如果在键入字符时文本字段为空,则我希望插入符号的位置为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);
            }
        });
    }
}

You are using a general Key Event dispatcher. 您正在使用常规的Key Event调度程序。 The possible events are KEY_PRESSED , KEY_TYPED and KEY_RELEASED . 可能的事件是KEY_PRESSEDKEY_TYPEDKEY_RELEASED Based on what you say, you need KEY_TYPED . 根据您的发言,您需要KEY_TYPED So filter for that: 因此过滤:

KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
        public boolean dispatchKeyEvent(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.KEY_TYPED) {
                return ((TextClass) textArea).checkKeyTyped(e);
            }
        }
    });

It is not how you are supposed to do it, you are supposed to implement a KeyListener and add it to your JTextArea using addKeyListener(KeyListener) , as next: 并不是应该这样做,而是应该实现一个KeyListener ,然后使用addKeyListener(KeyListener)将其添加到JTextArea ,如下所示:

final JTextArea textArea = new TextClass();
...
textArea.addKeyListener(new KeyListener() {
    @Override
    public void keyTyped(final KeyEvent e) {
        char key = e.getKeyChar();
        switch (key) {
            case '<':
                System.out.print("   " + textArea.getSelectionStart());
        }
    }

    @Override
    public void keyPressed(final KeyEvent e) {
    }

    @Override
    public void keyReleased(final KeyEvent e) {
    }
});

Up to now, you get it printed 3 times because your method is called for each type of KeyEvent that is triggered whenever you type on a key: 到目前为止,您将它打印了3次,因为每次键入键时都会触发每种KeyEvent类型调用您的方法:

KEY_TYPED

The " key typed " event. key typed ”事件。 This event is generated when a character is entered. 输入字符时会生成此事件。 In the simplest case, it is produced by a single key press. 在最简单的情况下,它是通过一次按键来产生的。 Often, however, characters are produced by series of key presses, and the mapping from key pressed events to key typed events may be many-to-one or many-to-many. 但是,字符通常是通过一系列按键产生的,并且从按键事件到按键类型事件的映射可能是多对一或多对多的。

KEY_PRESSED

The " key pressed " event. key pressed ”事件。 This event is generated when a key is pushed down. 按下键时会生成此事件。

KEY_RELEASED

The " key released " event. key released ”事件。 This event is generated when a key is let up. 释放键时会生成此事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM