文本编辑器:如果按下某个键想要取消键事件并提供新功能

Text editor: if certain key pressed want to cancel key event and give new functionality

我有一个 text/html 类型的 JEditorPane。当在编辑器聚焦的情况下按下回车键时,我想检查文档的状态,然后在满足条件时覆盖回车键默认功能。

我相信这可以通过 KeyListener 侦听键来完成,然后在满足条件时使用事件以取消键对输入进行任何更改。测试这个想法我只是想在按下任何键时使用键事件。当我按下任意键时,下面的关键侦听器正在打印输出,但字符仍然被插入到编辑器窗格中。

如何才能阻止字符被完全插入?

感谢您的帮助。

String content = "";
String type = "text/html";
editor = new JEditorPane(type, content);
editor.setEditorKit(new HTMLEditorKit());
editor.setEditable(true);
editor.setPreferredSize(new Dimension(500, 500));
panel.add(editor);

editor.addKeyListener(new KeyAdapter() {

    @Override
    public void keyPressed(KeyEvent e){
        System.out.println("huh?");
        e.consume();
    }
});

编辑------------

删除了关键侦听器,并改为添加

Action enter = new AbstractAction()
{
    public void actionPerformed(ActionEvent e)
    {
        System.out.println("enter!");
        if ( condition == true ){
             // default enter key behaviour
        }
    }
};
editor.getActionMap().put("insert-break", enter);
    

好的,我摆脱了 KeyListener 并添加了它,这阻止了很棒的默认输入键功能。但是,如果我的 if 子句为真,我将如何插入中断(默认输入键行为)?

I can't figure out how to trigger that on the editor programmatically.

你想多了。

我们保存Action是因为我们要调用ActionactionPerformed(...)方法。

假设原始 Action 存储在变量“原始”中,代码​​将是:

if (condition == true)    
    original.actionPerformed( e );