Java is most well known for its use with network browsers such as Netscape or Internet Explorer. These Java programs are called applets. Applets are initiated from a tag in the web page (the html file).
Java applets are quite similar to Java applications but do have some important distinctions.
For this lab, you will complete an applet that implements a simple game that counts how many times the user clicks on a target. The target will be a picture of your lab insructor!
The code that is provided displays a picture of a famous person amd 'moves' the picture inside a panel.
When a mouse is clicked anywhere inside the panel, a count is updated and displayed.
You will replace the picture with a picture of your lab instructor, cause the picture to appear at random positions within the panel, and determine if a player clicks on the picture.
Your code should then update the count if the player clicked the picture (and only then).
You can shorten the amount of time that the picture stays in one place to challenge the player.
Applets are initiated from within a web page (or by an appletviewer). So, an html file must be provided. Below is the html file for an applet.
The APPLET tag provides the name of the Java class file containing the applet code.
< HTML > < HEAD > < TITLE > Applet </TITLE> < /HEAD > < BODY > < APPLET width=500 height=500 code="CatchTheTA.class" > < /APPLET > < /BODY > < /HTML >
To run this applet, we could use the Java appletviewer (assuming the html is stored in a file named Animation.html):
appletviewer Animation.htmlTry running the applet.
In terms of coding, there are other important differences. Two of these are
To create the necessary pause between displays, the Timer object is used to trigger an event at regular intervals. The length of an interval is specified as an integer quantity of milliseconds (1000 milliseconds per second).
Below is code from today's lab with some explanations:
...from CatchTheTA.java private final int DELAY =100; private Timer timer; timer = new Timer (DELAY, null); Create a timer object using .1 second interval ....new AnimationPanel (timer,totalHits) Give the timer object to the panel timer.start();Start the timer timer.stop(); Stop the timer
...from AnimationPanel.java timer.addActionListener(this); Add the panel object as a listener for timer public void actionPerformed (ActionEvent event) { Invoked each time timer interval expires ... }
GUI Intermission -- Mouse eventsThe GUI for this lab is provided for you. The AnimationPanel.java listens for mouse clicks. When a mouse click is detected, it updates a counter in a text field. We have shown you how a button can respond to an event with an action list ener. But now we want the JPanel to respond to a mouse click -- anywhere inside the panel, not just on a button. Here is how to make that happen:
|
Submit AnimationPanel.java and CatchTheTA.java. The assignment name is Lab_10.