- Point Netscape at the PHY307 homepage and look under the
Labs section. You should see a link to the code Hwa3.java.
Download this to your SUnix account by selecting Save As from
the file menu and choosing to save it to directory/folder public_html/PHY307
on the I: drive of your PC.
- Open a Telnet session to SUnix as before and go to the
directory public_html/PHY307 (by typing cd public_html/PHY307).
- Start up an editing session of this new file by typing
pico Hwa3.java. You will see that the code is
pretty much the same as that in Hwa2.java. We will start to
edit it now to add a button which controls what is drawn to
the screen.
- After the line private Font newfont;, add the lines
private Button mybutton;
private boolean onbutton=false;
By doing this you have defined two new objects in your code -- the object
mybutton which is of type Button and a logical variable
onbutton which is either true or false depending on whether
mybutton has been clicked. It is initially set to
false.
- Inside the init() method (that is between the curly
braces defining the content of the method) and directly
after the line newfont = new Font ... add the lines
mybutton= new Button("Press Me");
add(mybutton);
This creates the Button mybutton (with the special new command) and
labels it Press Me. It then adds it to the applet
page with the add command.
- Finally, notice that a new method action() has been
added to the applet code. This method watches for clicks of
mybutton and responds by flipping the logical variable
onbutton alternately from true to false.
The words Hello World are only displayed when onbutton is
true.
- The code to do this is listed below. Add these lines between
the beginning and ending brace of the action() method.
if(evt.target instanceof Button){
onbutton=!onbutton;
repaint();
return true;
}
return false;
- Recompile the code by executing the command javac Hwa3.java
at the SUnix prompt.
- Change the file permissions as usual by typing chmod 644
Hwa3.class.
- Now use pico to create a page - called say Hwa3.html
which will load this new
Java applet Hwa3.class. Remember to set its permissions
correctly.
- Fire up Netscape and point it at this new page.
IMPORTANT- Sometimes Netscape
caches copies of Web pages and Java applets on disk so that hitting
reload by itself does not always get the most recent
version of the applet off the network. Try holding down the shift key
at the
same time as hitting reload - this (sometimes!) forces a reloading of Java code
for sure. If this doesn't work try explicitly flushing the cache - look
under the Preferences/Advanced menu in Netscape. If all else fails close
and reopen Netscape or fire up Explorer instead.