Because we are using a using Java, which is an object-oriented programming language, we can take any class, extend it with our own functionality or replace some of its functionality or behaviour. We have already met the
java.awt.TextField class, which allows you to enter a string in a text field container.
Say we wanted to develop our own TextField (
java.awt.TextField) component that only allows you to enter in numeric values (i.e. no letters), but also allow us to press the BACK SPACE key or the DELETE key on the keyboard, how can we do this?
Figure - The Custom Component Application
Well the first step is to extend the
java.awt.TextField component and add our custom behaviour in a new class called
IntegerTextField that is defined below:
- We extend the
TextField class so that the "IntegerTextField is a TextField".
KeyListener allows us to capture key press events and requires us to implement the three methods:
keyPressed(KeyEvent), keyReleased(KeyEvent) and
- We can find out which key was pressed within the
keyTyped() method by using the
- We then need to find out if the char is numeric (0-9) or one of the special keys, which are defined as static constants
- If it is one of these keys then we will (temporarily) display the message "Numeric key pressed" if not then it must be a non-numeric key.
- If it is a non-numeric key we print the message "Non numeric key pressed" and then we will consume the event using
e.consume(), which will stop the event from being passed on for further processing - like cancelling the event.
And then to use this, we build an application as usual:
You can see in this example that the new
IntegerTextField behaves exactly like a regular
TextField, except in the application you cannot press keys other than 0 to 9 and the BACKSPACE and DELETE keys.