Applet One


Construct an applet that writes multiple and identical messages to the screen. Each message will be of random hue and random font (use at least 5 fonts). The background may be black or set with random hue. The message to be displayed should be read from an applet param.

Summary of Applet One

An applet that writes multiple and identical messages at random positions on the screen. The message is read from an applet param in the html page. No need for a default message in this class because there is no easy way for the user to change the message in the html document, therefore little chance of there being a null value, hence the design decision was taken to exclude the default message idea.

The applet generates a random number of messages between 10 and 40, to the screen. Each message uses randomly chosen, separate size, style and typeface variables combined to make one of 365 fonts, this is paired with a random hue for the message. The random hue is created by using the HSB system of hue, saturation and brightness, where hue is a randomly generated float, brightness and saturation are kept at maximum for vibrant colours. The font colour is ensured to be different to that of the background colour. The background colour is made in a similar way to the font, it uses the RGB system of colour to have more subtle shades, it separately generates random red, blue and green variables and combines these for the final result.

Features of Applet One

1) Creates arrays of the 4 guaranteed typefaces in Java; Serif, Sans Serif, Mono-spaced and dialogue, and the four possible styles, plain, bold, italic, and bold with italic.

// sets up arrays of possible fonts and styles
String[] faces = { "Serif", "Sans serif", "Monospaced", "Dialog" };
int[] styles = { Font.PLAIN, Font.BOLD, Font.ITALIC, Font.BOLD + Font.ITALIC };

An alternative method to the above would have been to use the code as it is in the example. The example uses 5 set fonts with an arrangement of size, style and already set for each font. The code then uses switch cases in deciding a random font. This method, I felt, was too rigid - I wanted to my code to be able to choose from a greater selection.

This method of using arrays is more efficient, especially for larger applets, since the fonts are calculated from the array when they are initialised, it is far easier to add or delete a font from the array without having to change any of the other code.

2) Upon refreshing the applet - the background changes to a random colour using separate random Red, Green and Blue variables.

// Sets up three variables; red, green and blue relating to random integers, RGB have to be integer values
int red = (int)(Math.random()*255);
int green = (int)(Math.random()*255);
int blue = (int)(Math.random()*255);
// Uses the random variables in the RGB format to set the background colour object as random.
backgroundColor = new Color(red, green, blue);

Possible alternative methods for this element of code could include calling the background colour from array of possible colours or just setting it with a constant colour for example, black. I am pleased with this design decision to make the fonts vibrant and bright and have a wider range of possible, subtler shades for the background, I believe this adds variety.

3) Chooses a random number of messages between 10 and 40 to display.

// Sets up a variable that is then used as a condition in the 'for' loop
int numMessages = (int)(40*Math.random()) + 10;
// Uses a for loop to draw each message
for (int i = 0; i < numMessages; i++) { 

This was tested by turning on the facility to ensure that background does not equal font and counting the instances of the message on the screen. Although this is a crude technique - if done between a large enough boundaries - e.g. 10 and 40, also if the page is refreshed a number of times, this is a relatively sound approach to show that this method works. An array would be one other way of achieving the same result - only it would be taking up unnecessary memory when it can be generated just as easily. This method is fast and efficient, it also uses less code than the alternative, for larger applets where memory is a problem, this is an ideal approach.

4) Generates a random integer and stores it in the variable "size" between 14 and 36.

int size = (int)(22*Math.random()) + 14;

The only way to test this easily is by observation, see if some of the fonts look size 14 and some size 36, and then compare to the others the see if there is an even spread between the two.

One way this could be improved in the future is to have an algorithm to work out numbers in the code from entering min and max sizes, possibly into a swing form.The same theory applies about this feature as did the last, An array would take up unnecessary memory when this can be generated just as easily.

5) Chooses and matches the typeface and style randomly, with the sizes to create the font.

// Finds the length of the aray and asigns the value of the random number found, to the respective variables
String face = faces[(int)(faces.length*Math.random());
int style = styles[(int)(styles.length*Math.random())];
// not needed to be re-used, so can declare a new font here.
g.setFont(new Font (face, style, size));

This chooses a random face and style randomly by finding the length of the array and multiplying it by a random number between 0 and 1, then as an integer, using this to assign the array to the relevant variables. The g.setFont() method can then declare a new which calls these variables.

Again, a good way to test if this method performs correctly after compiling is through observation over a few runs of the applet.

As I have previously mentioned, I felt that using the switch cases for this task was not as flexible as I would have liked it to be.

This way of coding the choice of font is very re-useable, and easily maintained, even for complex tasks as it is possible to change the contents of the arrays for style or typefaces, (e.g., delete a font) and not have to re-code any other areas of the program.

6) The font colour is chosen randomly from separately calculated random variables, and is never the same as the background colour. The applet uses a do-while loop until the font colour is different to that of the background colour.

// Sets up a variable 'hue', which is a random float,
float hue;
Color fontColor;
// Picks a random font colour
// uses a random hue with maximum brightness and saturation
// ensures that font colour is not the same as background colour
do {
        hue = (float)Math.random();
        fontColor = Color.getHSBColor(hue, 1.0F, 1.0F);
} while (fontColor.equals(backgroundColor));
// Sets the colour of the font

The program cycles through the loop changing the colour of the font until the font is different to that of the background using the fontColour.equals() method as opposed to == comparisons, because font Colour is an object not a primitive type.

I tested this by making sure that 3) numMessages (the random number of messages to be shown) was replaced temporarily with a small fixed number of messages. Then using as the message in the applet param "o" it was relatively trivial to count the messages on the screen. If there was less than the fixed number there was supposed to be, then one or more must be the same colour as the background colour. Although this is a crude method of testing, after repeating a number of times it could be assumed to be relatively accurate. After the test was performed the original value for the condition in the loop and the message in the parameter were returned. This code is efficient because it does not waste processing time on producing a message which is not going to be visible.

7) Prints multiple, identical messages at random positions of random fonts (out of 365 = 4styles * 4typefaces * 23sizes) and colours within a box.

// Sets up a random height and placement for the message
int x,y;
x = -50 + (int)(Math.random()*(width+40));
y = (int)(Math.random()*(height+20));
// Draws the message at placement



This aspect is easily tested - just by calling the applet in an html page and viewing it in a browser.

One way that I can see of improving this code would be if there were variables for the 'magic numbers' in the code, it would make it easier to maintain in the future - otherwise this could confuse the next programmer who tried to alter the code.

View Applet one

Applet Two


Repeat the above project to respond to a mouse event such that the applet re-draws itself in response to a mouse click.

Summery of Applet Two

this applet repeats the process of the previous applet however, it uses drop-shadows on the messages. The message to be displayed is primarily read from the user input, taken from a form written in Swing, this appears when the applet is first loaded, or when the page is refreshed.

The user can click within the applets boundaries and this will refresh the random positioning of words, using the previous value entered, by calling the repaint() method, it does not refresh the applet itself therefore the background colour remains the same. If the user enters either the values "date" or "time" into the form, the message string returned will be that of either today's date, or the current time respectively. When no message value is entered into the form, the default value used for the string is that of the applet param.

Features of Applet Two

1) I wanted to create drop-shadows in this second applet, however I needed to put them into the paint method, in order to do this I had to create a new class named coursework3. This class is identical to coursework1 in every way except for the following lines of code in the 'for' loop, within the paint() method (See the appendices).

// Sets the colour of the dropshadow to be black
// Draws the message dropshadow at 2 pixels away either side

This code sets the font colour to black and paints an identical message two pixels to the right and down from where it intends to put the actual message. The font colour is then set to the variable fontColor (which has already been set to a random hue) and paints the actual message. This creates the illusion of drop shadows, and makes the text stand out from the background.

This feature could be re-used in more complicated application for an efficient way of creating emphasis on words, titles for instance, that might not show up against their relative backgrounds.

2) The user is able to click within the boundaries of this applet which will result in the applet calling the paint() method which will refreshes the random placement of the words only, and not the background as this is called in the init() method.

// When the applet is created do the initialisation of the superclass coursework2. // Then set this applet to listen for mouse events on itself.
public void mousePressed(MouseEvent evt) {
// When user presses the mouse tell the system to call the applet's paint() method

This can be tested simply by running the applet and clicking once within its boundaries and watching for it to regenerate the placement of the message string.

An alternative way of producing the same effect would be to use a button which when de-pressed would call the same method. I feel that this particular feature would be improved if, upon one click the applet called the repaint() method and on a double click, it would re-draw the applet using the init() method. I chose it to use the boundaries for the mouse event because I liked the idea that it is an un-noticeable feature until the area is clicked on. The same principle of a click calling a re-paint method could be used in larger applets to do much the same thing - or with a random function of any sort e.g. a random tip of the day feature in a word processing application.

3) The most advanced feature of applet two is a pop up dialogue box, which asks the user for the message to be displayed. (This feature however, only works with browsers that support Swing)

// Obtain user input using swing
message = JOptionPane.showInputDialog("Enter the message to be displayed");

The above code generates the dialogue box with the text "Enter the message to be isplayed" the user can then enter a preferred message, or one of the two command words, "date" or "time" explained in the following feature descriptions.

The library that needs to be imported to allow the code to perform, is the following: javax.swing.*.

An alternative method which I started to use involved the use of a popular high level web server scripting language called PHP (PHP: Hypertext pre-processor - a recursive acronym) rather than Swing, to take input from the user.

This works using a short PHP script running on the web server, which accepts a string nputted by the user in an html form. The string is then passed to the applet through a dynamically generated html applet parameter. The applet then uses this string as the message to be displayed randomly.

This would be a good feature to for use in the future if condensed, for use as a text field in many, more complex applets.

4) )When no message is entered into the popup box the value retained is null, when this happens, the applet gets its default message from the html parameter. The following code covers all eventualities of the field being empty of a string.

// If no message is found it uses "java!" as a default message
if (message.equals("") || message == null || message.equals(" "))
// Gets the input from an applet parameter named message
message = getParameter("message");

This feature was tested by entering a variety of null values into the form and waiting for the subsequent to generate. When the applet realises that the string is null, it reads the default message from the applet param. There is a great advantage to using the message from the applet param rather than coding one into the Java class file. This is that if this method were applied to a larger more complicated applet that took a while to compile, just to re-compile the file to change the message would be a waste of processing time. So to counteract this, the message is placed as a parameter in the html page, this makes things a lot simpler when the message is needs to be changed. Just by saving the html document after the message is changed, saves re-compiling and is hence more efficient than its alternative.

5) If the user types in the word "time" in lower-case letters into the popup box, this is picked up by an if statement which then returns the time at that moment as the message repeated in the applet.

// Sets up an object which knows how to format the time.
DateFormat shortTime = DateFormat.getTimeInstance(DateFormat.SHORT);
// Displays the current time when the user types "time"
        if (message.equals("time"))
                message = shortTime.format(new Date());

A relatively trivial test here, the text "time" was entered into the dialogue box on the form and the time was displayed as hh:mm in 24-hour clock.This feature could be improved if the message was a time that replicated a real clock and showed time passing, or when the re-paint method was called by clicking on the applet this re-generated the time to the current time.

6) This feature has the same method as the above, however it returns today's date depending on the 'locale' of the user when called with "date".

// Sets up an object which knows how to format the date
DateFormat defaultDate = DateFormat.getDateInstance();
// Displays the current date when the user types "date"
if (message.equals("date"))
    message = defaultDate.format(new Date());



This is similar to the above feature, however it returns the date in the form DD-MMM-YY, and doesn't have the same scope for improvement as the time feature.

View Applet two