Read keyboard input for chat

I understand you can use the Scanner to read text from the console but is there a way to use some form of scanner to detect my keypresses in a JFrame? (i don’t really wanna use my player input manager for movements for this but i can if it comes down to it)

KeyListener?


	class KeyInput extends KeyAdapter {
		public void keyPressed(KeyEvent evt) {

			if (frame.isVisible()) {
				if (evt.getKeyCode() != KeyEvent.VK_CONTROL
						&& evt.getKeyCode() != KeyEvent.VK_RIGHT
						&& evt.getKeyCode() != KeyEvent.VK_LEFT
						&& evt.getKeyCode() != KeyEvent.VK_UP
						&& evt.getKeyCode() != KeyEvent.VK_DOWN) {

					if (evt.getKeyCode() != KeyEvent.VK_ENTER) {

						if (evt.getKeyCode() != KeyEvent.VK_BACK_SPACE) {
							if (evt.getKeyCode() != KeyEvent.VK_SHIFT) {
								line += evt.getKeyChar();// getKeyChar() returns char of key pressed
							}
						} else if (display.line.length() > 0) {
							line = display.line.substring(0,
									display.line.length() - 1);//backspace
						}
					}else{
                                             //do chat stuff here
                                        }
				}
			}
		}
	}

This is what I used in my shell program. Just add an instance of KeyInput to the jframe and display “line”

Thank you guys, both of your replys have helped my think of a solution :smiley:

[derail]
I like to create a variable for [icode]evt.getKeyCode()[/icode] so I don’t have to type it over and over again.


int keyCode = evt.getKeyCode();

All you need to do is use a stringbuilder and when the text box has focus, ie has been clicked ; append that stringbuilder.

You can check for backspace key a use the stringbuilder built in methods to change it.