I am using a keylistener and I need to know when the backspace and delete keys are used. Does anyone know how this is done? I have not found anything online.

Recommended Answers

All 3 Replies

Try this in your key listener methods. I tested it with keyTyped method

public void keyTyped(KeyEvent ke)
{
	switch(ke.getKeyChar())
	{
		case '\u0008':
		System.out.println("Backspace");
		break;

		case '\u007F':
		System.out.println("Delete");
		break;

		default:
		System.out.println(":)");
		break;
	}
}

That's the right approach, but you should not use hex constants as in Niuranga's code. The JavaDoc for KeyEvent has the following warning:

WARNING: Aside from those keys that are defined by the Java language (VK_ENTER, VK_BACK_SPACE, and VK_TAB), do not rely on the values of the VK_ constants. Sun reserves the right to change these values as needed to accomodate a wider range of keyboards in the future.

KeyEvent includes public constants for all the virtual keys, eg VK_BACK_SPACE, VK_DELETE , etc and these are what you should use.

Hi JamesCherrill,

I almost forgot about those constants. Thanks a lot for the guidance.

Cheers...!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.