Skip to content
Advertisement

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

I have a JEditorPane with text/html type. When an enter key is pressed with the editor focused, I want to do some checks about the state of the document and then override the enter key default functionality if conditions are met.

I believe this can be done with a KeyListener listening for a key, then consume the event if conditions are met to cancel the key making any change to the input. Testing this idea I’m just trying to consume the key event when any key is pressed. The key listener below is printing output when i press any key, but the characters are still getting inserted into the editor pane.

How can I stop the characters getting inserted altogether?

Thanks for your help.

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();
    }
});

EDIT———-

Removed key listener, and added instead

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);
    

Ok I got rid of the KeyListener and added this, which prevents the default enter-key functionality which is great. But how would i insert a break (the default enter key behaviour) if my if clause is true?

Advertisement

Answer

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

You are over thinking it.

We save the Action because we want to invoke the actionPerformed(...) method of the Action.

Assuming the original Action is stored in the variable “original” the code would be:

if (condition == true)    
    original.actionPerformed( e );
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement