![]() | Monkeys at Keyboards: The Javanomicon © Michael James Heron | ||||
| Topic: Java Programming Level: 2 Version: delta | |||||
2 - Introduction to Applets! | |||||
| Previous | Table of Contents | Next |
| Forum |
| Chapter Objectives |
By the end of this chapter, the reader will be able to:
|
We will start off slowly with an introduction to Java applets - applets provide a very useful framework from which we can begin exploring how to develop powerful, professional looking programs. Before we begin doing that, we need to spend some time looking at the framework within which we will be functioning. Applets have a particular structure within which code is executed - this is different to the standard text-based framework most often encountered in introductory programming modules. However, the framework is the only real difference - all of the coding syntax is the same, the only change is where you put the code.
Java is a programming language that was written with the internet in mind. It has extensive functionality for providing useable and configurable user interfaces through a number of predefined Java libraries. For this module, we will initially be using Applets to provide a significant amount of the functionality. We will also look at free standing applications later in the module, particularly in relation to applications that make use of file I/O. For the first few weeks however we will be using applets exclusively, so it is a good idea if we spend some time looking at their basic structure. An applet is broken up into two parts:
Java code is written in a standard text file - to develop a Java application you need nothing more substantial than the Java Software Development Kit (SDK) and an ASCII text editor. The text of a Java program itself is not enough, however... Java code means nothing to anyone except software developers and the Java compiler. Before a Java program is ready to be deployed, it must be compiled into what is known as byte-code. This byte-code is contained in a class file. Compiling a program in Java is not quite like compiling a program in other languages. The process of compilation takes a human readable computer program and translates it into something that can be understood by the computer. In older languages like C, this means the code is translated into machine code or assembler. In Java however, the code is compiled to byte-code which is then executed on a Java Virtual Machine (JVM). The JVM acts as an interface between the Java code and the operating system. The benefit of this system is that a program written in Java will run on absolutely any computer that has a JVM installed... you do not need to write platform specific applications as is required with languages like C. The Java Virtual Machine takes on the task of finding out what the byte-code wants to do, and then sending the request to the underlying operating system.
This is a marked improvement on languages that are compiled to machine code or assembler... in such cases, the code needs to be rewritten and recompiled on every computer platform on which it is to be deployed:
Each operating system has its own quirks and idiosyncrasies... what works (and works well) on one system is not necessarily the thing that will work at all on another platform. The process of transferring a program written for one platform into a program written for another platform is called porting, and it is a specialist skill... the more complex the program, the more difficult it is to get it running on another system. Java circumvents all of this through the virtual machine - the only thing that must be ported to different systems is the JVM... one that has been deployed, then any Java program will (in theory, at least) run on that system without requiring the underlying code be changed. With other languages, like C, each system needs a compiler to be ported to the platform, and the underlying code will need to be tweaked to operate properly. This makes the job of developing for multiple platforms much more difficult. The downside is that the JVM itself consumes resources in addition to the deployed program - such programs consume more memory and CPU than is strictly needed to implement the functionality. In computing terms, they have a larger system footprint. So, the process for writing a Java program is to develop the code in a .java file, and then run a Java compiler over that program to turn it into a .class file which contains the Java bytecode needed by the virtual machine. It is the class file that our applet needs in order to run, and we create the class file from the Java code that we enter into our compiler. The code for a simple Java applet looks like this:
Of course, as we've discussed, the Java file itself is only one part of the applet structure. We also need an HTML file, although this can be very basic. For example:
So, that's the structure of a very simple applet. Most of the code in there we've warded off with a sign saying 'Here Be Dragons', or at least said 'don't worry about this for now'. This is important - the details of what all the code means can be a distraction from actually doing something. There is no need at this point for you to understand what everything does. As the module progresses, we'll build on our knowledge until everything in the code extract makes complete sense.
As indicated above, the paint method is responsible for drawing things onto the screen. The method gets a special object that deals with Graphics passed to it when it is called - this object has a whole range of neat things that can be done with it. For example, we can raw a line from one point to another point using the following method: drawLine (x1, y1, x2, y2)Where the drawString method draws a string of text, the drawLine method simply draws a straight line. It takes four parameters - the x and y co-ordinates of the start point, and the x and y co-ordinates of the end point. It then works out how to draw the line from that information:
This call will draw a line from (10, 10) to (50, 50) as illustrated below:
Our next methods can be used to draw a more complete shape on the screen... these are actually a pair of complementary methods: drawRect / fillRect (x, y, len, ht)The drawRect and fillRect methods draw a rectangle on the applet. drawRect will draw an outline of a rectangle, whereas fillRect will draw a fully coloured rectangle. We pass in four numbers to the method - the first is the x co-ordinate of the top left corner. The second is the y co-ordinate of the top left corner. The third parameter is the length of the rectangle, and the fourth is the height. All of these are expressed as integers:
drawOval / fillOval (x, y, len, ht)As with drawRect/fillRect, these are complementary methods that draw either an outline of an oval, or a fully filled oval. The numbers passed into the method are exactly the same as those for drawRect/fillRect - these specify an invisible rectangle, within which Java will attempt to draw an oval as best it can:
In order to change the colour used to draw things in Java, we need to make use of the setColour method of the Graphics object - Java supports a range of colours, and also offers the possibility for defining your own. We'll stick to the ones provided for us for the moment. setColour takes a parameter that looks a little different from the numbers that we've used in the other methods... we need to tell Java where it can find the information for mixing a particular colour, so we use a parameter that expresses this. Some of the valid parameters are listed in the table below:
Once you've changed the colour, it will stay like that until you change it again - it's just like if you're drawing with some felt-tip pens. If you draw a circle and then draw a rectangle, they'll both be the same colour unless you change the colour of the pen you're using in between.
The problem with the provided colours in Java is that they don't cover a particularly impressive range of the spectrum. However, we can create our own colours by mixing together values of red, green and blue to get the exact shade we want. However, in order to do this we need to use a little bit of Java voodoo and create an object to do this for us. As we progress through the book, it should make more sense as to what we're actually doing - for now though, we'll just look at the syntax. To create our own colour, we need three integer values... these values are between zero and 255, and they represent the intensity of a primary colour:
The primary colours here are those used in what is known as additive colour mixing - colours are made by the combination of different lights in your computer monitor. Don't get this mixed up with subtractive colour mixing (which is used for mixing paints) , which has a different set of primaries. If for example, we wanted a bright red:
Or a bright blue:
However, providing combinations of the numbers gives us the potential to mix whatever shade we can possibly hope for. For example, mixing red and green gives us yellow:
We can get a dark orange by reducing the amount of green in the colour:
We can also store the colours we create for later use - we create a Colour object that will hold particular values so that we can easily swap between different 'pens':
Far more sophisticated shades can be obtained by adding in a third colour and varying the intensity of that until exactly the right colour is obtained - you don't have to be limited by the rather parsimonious palette provided by Java by default. The cost is that it can be difficult to determine exactly what the numbers for each of the colours should be. To aid you in your search for colloidal perfection, there is an example applet that lets you mix your own colours until you find exactly what you are looking for - it's called ColourScrollbars. Don't worry about the code for now, but come back and take another look after chapter four - you should understand most of it. After chapter fourteen, you should understand the rest of it.
We can combine all of these drawing methods within the paint method to create some simple graphics. For example, a door (of sorts):
And voila, we have ourselves a little door:
It is often useful to separate out such composite pictures into methods of their own. The exercises at the end of this chapter will discuss some examples of this.
The Java libraries give us a range of shapes we can draw, but sometimes we need more. For example, it's possible to create a drawTriangle system using nothing more than three drawLine method calls - but how could we write a fillTriangle system? At the moment, we can't. However, Java does indeed provide us with a mechanism for drawing some more complicated shapes - that mechanism is called a polygon. In the same we can create our own Colors, we can also create our own shapes ready for drawing onto our applets. The first thing we need for this is a container for the shape we're going to use. As with a Colour, we give it a name:
Again, don't worry too much about the specifics of this - we'll see what this all means in chapter 10. To begin with, Java has no idea what shape we want to draw, so we need to tell it - we tell it by feeding it a series of co-ordinates... Java will draw straight lines between each of the points in this series to create a polygon. We feed a co-ordinate to the polygon through the following syntax:
We do this as many times as we need to, until we have the whole range of co-ordinates requires. For example, if we wanted to create a trinagle:
This would create the following polygon:
Note that this doesn't actually draw the polygon - it just creates it. The polygon never gets drawn until we tell Java to do so, and we do that using either drawPolygon or fillPolygon on the Graphics object:
We could add as many points as we required to the polygon to create the shape we wanted, but there is a danger - the order in which the co-ordinates are added is important and requires some planning. When Java creates the polygon, it draws connections between co-ordinates in a series. It draws a line between point one and two, and then point two and three, and then three and four, and so on until it comes to the last point. It then draws a line between the last point and the first point. For a triangle, it doesn't matter... but for more complex shapes, you may find the behaviour is quite strange. For example, if we have a series of points in the order ([50,50], [25, 100], [50, 150], [75, 100]) then we get a neat diamond (the order of the points in the series are shown on the diagram):
However, if we change the order to:
What we end up with is something quite different:
This gives a great deal of flexibility in how polygons are drawn, but it also leads to a fair degree of complexity if you want to draw something a little extravagant. The best plan is to plan all the points out on a separate piece of paper and play a game of connect the dots - it's the same strategy Java uses, so it should help you plan out your complex shapes.
Often the applet is all we need to concern ourselves with - the HTML page is just a container for our blood, sweat and tears. However, Java does provide us with a mechanism for passing information to our applet from the HTML page that contains it. It does this through the use of parameters. The parameters that are defined in the HTML file are made available to the Applet through its getParameter method. We define a parameter in the HTML file with the param tag. This goes between the opening and closing applet tags. The param tag has two attributes that go with it - the first is name, which is an identifier that indicates how we can reference to it within our applets. The second is value, which is the... you guessed it, the value the parameter will have. So, for example:
Here we've set up a parameter with the name message which has the value I like monkeys. We can make use of it within our applet like so:
Now when we run the applet, it will display the string 'I like monkeys'. We can do more with this framework - if you wanted to put in the effort, there's nothing to stop you allowing the user to configure any reasonable aspect of your applet so that it conforms to the exact style of the web-page in which it is embedded. You could allow for background colours to be changed, font styles to be set, and more besides.
This chapter is a slow, easy introduction to the topics of applets in Java. We've looked at the structure of an applet (or at least, we've looked at it a little bit), and we've seen some of the things that we can do with the Graphics object to which the paint object has access. We've seen the simple geometric shapes such as rectangles and ovals. We've also seen the more powerful polygon, and the additional shapes that allows us to develop. Playing about with these new toys will be a great help in demonstrating how Java's co-ordinate space works - this will be invaluable when it comes time to develop your own user-interfaces. The tools that we've covered don't give us a lot of scope for doing anything other than drawing pretty pictures, but that's okay - we can have some fun with that for now. At least that way, we get a little relaxation before the Back Breaking Labour that is to come!
Exercise oneCreate a new JApplet. Using only the drawString and drawOval methods, amend the paint method so that it displays your name with a copyright symbol (a c surrounded by a circle) to the top right of it. Exercise twoCreate a new JApplet. Write a paint method that allows you to draw a Robot's face using only ovals, lines and rectangles:
Exercise threeUsing seven fillRect calls, create an applet that displays the colours of the rainbow in order - these are Red, Orange, Yellow, Green, Blue, Indigo, Violet. The latter two have no direct parallel in Java's standard syntax, so use Pink and Magenta as substitutes... or if you feel adventurous, mix them up yourself. Exercise fourCreate a face using ovals and lines. Use the drawString method to write some text and then place an oval around it in the style of a speech bubble:
Exercise fiveWe looked at how to draw a door above. Expand this so that you draw an entire house, including a polygon for the roof. Exercise sixUsing a polygon for his hat, write an applet to draw a Happy Pirate complete with beard:
Exercise sevenMake use of the Java API documentation to find out how to draw an arc. Use this to draw a smile on the pirate's face. Exercise eightMaking use of a polygon object and a selection of filled ovals to draw a pair of crossed bones, write a JApplet that creates a pirate flag:
Further ReadingThe following table details further reading on the topic in this chapter, and also any external resources that you may find useful.
|
| Previous | Table of Contents | Next |
© 2004-2006 Michael James Heron