User Input
The Echo Applet
Look over the code and try out the sample applet.
The only tricky part of this applet is in the init method. There you will
see what is known as an inner class. The inner class is everything inside
the following block of code:
this.addKeyListener(new KeyAdapter(){
});
Just before the beginning of this inner class you will notice a line that
looks like this:
requestFocus();
The inner class and the requestFocus() line enable the applet to take input
from the keyboard. You will notice that within the inner class (which
happens to be an instance of the KeyAdapter class), a single method is
defined called keyPressed. The code within keyPressed basically runs this
applet. It defines what to do when the ENTER key is pressed, when the DELETE
key is pressed, when the BACKSPACE key is pressed, and when any other key is
pressed. Here's the if-else block skeleton:
if(k.getKeyCode() == KeyEvent.VK_ENTER){
}
else if(k.getKeyCode() == KeyEvent.VK_DELETE){
}
else if(k.getKeyCode() == KeyEvent.VK_BACK_SPACE){
}
else{
}
Finally, at the end of this method the repaint() method is called which
allows the display to be updated.
------------------
HIGHEST PEAKS APPLET
Here's another example for you to inspect.
The important part of this code to take a close look at is the part where
the output is determined. This is done in a series of if and if-else
statements. Make sure you understand how this works and try out the applet
to make doubly sure that you understand why it behaves as it does.
NOTE: Alaska and Hawaii were intentionally left out of this applet.
------------------
Assignment:
Create an applet which provides a list of twelve foods for the user to
select from. The user selects foods by typing the name of a food. When a
food is selected the cost of that item is provided as output.