CNorlander CNorlander - 13 days ago 5
Java Question

Adding a Key Listener to a JtextArea

I have a JTextArea called input and I am trying to get the string inputValue loaded into it when I press the up arrow key. so far this code does not seem to work and I am unsure as to why. Please help.

input.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
System.out.println("test");
if(e.getKeyCode() == KeyEvent.VK_UP) {
input.setText(inputValue);
System.out.println("up is pressed");
}
}

@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}

@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
});

Answer

you should override void keypressed instead of keytyped

@Override
        public void keyPressed(KeyEvent e) {
            System.out.println("test");
            if(e.getKeyCode() == KeyEvent.VK_UP) {
                input.setText(inputValue);
                System.out.println("up is pressed");

        }

because it's not a caracter

Comments