Skip to content
Advertisement

Have keyevent listener method constantly checking input

I wrote this method:

public void keyPressed(KeyEvent e){
        if (e.getKeyCode() == KeyEvent.VK_RIGHT){
            if (isEncryption){
                ctaTarget.setText(codModule.kodiere(this.getText()));
            } else {
                ctaTarget.setText(codModule.dekodiere(this.getText()));
            }
        } else {
            append(""+e.getKeyChar());
        }
    }

It is the method of a class extending JTextArea (yes, I know extending is suboptimal but I won’t need anything else for the intended application, at least not to my knowledge). It is supposed to check every character being entered into the JTextArea and send the message (the settext part) if the key being pressed is the right arrow. Now if I add an object of the class I created to my GUI nothing happens. Am I forgetting something I don’t know about?

Thanks in advance

Advertisement

Answer

It seems you have correctly implemented the KeyListener interface, though apparently you did not add it as such.

Your class still doesn’t know anything about your implementation until you added it using Component.addKeyListener(), i.e. in its constructor like this:

this.addKeyListener(this);

With this, we tell it to use its own implementation of KeyListener.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement