Вот и подошёл к концу наш конкурс! Поздравляем победителей!!! Подробнее.
Проект Programmers.kz и школа hotPen3D2D предлагает Вам курсы по веб-дизайну, веб-программированию и компьютерной графике. Подробности здесь.
- Просмотров: 726
- Автор: КазКиберГетик
An Introduction to Applets and Graphics
Категория: Программирование » Java » Уроки Java
Java Unit 5
An Introduction to Applets and Graphics
5.1 Web Pages and Viewing Applets
5.2 Some Information on the Geometric and Graphics Classes
5.3 An Applet Example
5.4 Drawing and Filling Geometric Shapes
5.5 Colors
5.6 Text
5.7 Putting Applets into Web Pages
5.8 Java Web Documentation
5.1 Web Pages and Viewing Applets
Applets are pieces of Java code that can be included in a Web page. When such a page is opened, the applet code is automatically downloaded and run on the local machine. Many interesting applets are graphical in nature. Both applets and graphics are large topics and not all of their details can be covered now. A very basic approach to writing applets is given in this unit, along with some introductory graphics classes and methods. More information can be found in the Java API documentation. How to write graphical applications and turn them into applets will be covered in a future unit.
When developing applets it is possible to test and view them without having them included in Web pages. If Java and TextPad were successfully installed on your system, in the menu under Tools, there should be an option “Run Java Applet”. You can compile applets with the compile option as usual and run them using this option. When you run an applet in this way, the system should open up another window for the applet viewer, and the results of the applet will be presented in this window. When first starting to do this, it is easy to mistakenly click on the “Run Java Application” option in the menu. If this happens, you should try again. Depending on the current state of affairs, an html file might have been created in the current directory and you may encounter a dialog box with the message “Choose File” in it when you try to test an applet. If this box comes up, you may click “No” as your answer. If you are still encountering difficulties, it might help to delete the html file and then try again.
5.2 Some Information on the Geometric and Graphics Classes
Java includes various graphical classes. Some of these have been used in previous examples, including Point and Rectangle2D. So far it has only been possible to use the println() method to see the values of the instance variables of objects of these classes. The goal now is to see them presented on the screen in a graphical way. The graphics classes are relatively complex because Java has evolved over time. For any geometric shapes there are both older and newer classes which implement them with differing features.
The Point class is a useful place to start. If you go to the Java API documentation, you will find these 4 classes related to points: java.awt.Point, java.awt.geom.Point2D, java.awt.geom.Point2D.Double, and java.awt.geom.Point2D.Float. At the tops of the entries for these classes you will find this information:
java.lang.Object
java.awt.geom.Point2D
java.lang.Object
java.awt.geom.Point2D
java.awt.Point
java.lang.Object
java.awt.geom.Point2D
java.awt.geom.Point2D.Double
java.lang.Object
java.awt.geom.Point2D
java.awt.geom.Point2D.Float
This information shows the hierarchical relationship among the classes. However, it also shows some other things which need to be briefly explained in order to distinguish them from the hierarchical information. Those parts of the naming convention such as java.awt.geom refer to Java packages. These are containers for storing system supplied classes. The names of the packages do not reflect the hierarchical relationship among the classes. Those parts of the names such as Point2D.Double indicate that there is a point class which takes double parameters and the definition of this class is physically contained in the Point2D class. This also does not reflect the hierarchical relationship among the classes.
Hierarchically, the Point class falls below Point2D, Point2D.Double falls below Point2D, and Point2D.Float also falls below Point2D. Point2D is a superclass and the other three point classes are subclasses of it. This kind of hierarchical relationship in Java is called an inheritance hierarchy. Subclasses inherit instance variables, methods, and constructors from their superclasses. An object of a subclass may have other things in it, which were defined in its own class, but it will also have all of the instance variables, etc. of its superclasses. Inheritance is a complex subject that will be covered in greater detail in a future unit. In the meantime it is helpful to be able to summarize the basic idea with UML notation. The inheritance relationship among classes is indicated by drawing arrows from subclasses to their superclasses. Here is such a diagram for the point classes:

Point2D serves as an overall heading for the other point classes. Its definition is written in such a way that it is not possible to construct an instance of it. Historically, the simple Point class came first. It takes integer parameters. When using the Point2D.Double and Point2D.Float classes in code, it is necessary to use their full names. However, to import them into a program it is only necessary to import Point2D. Here is a sample of the correct syntax for using them:
import java.awt.geom.Point2D;
…
Point2D.Double mypoint = new Point2D.Double();
…
This pattern of simple geometric classes integrated into a more complex set of related classes is repeated in Java. Look in the API documentation under Line or Rectangle, for example.
The machinery for presenting graphics in Java has also evolved over time. In earlier versions of Java there was a Graphics class. Now there is a Graphics2D class. In order for applications or applets written in earlier versions of Java to continue running correctly in later versions, the earlier, simpler class remains as part of the graphics machinery. Newer programs which make use of 2D graphics have to accommodate the earlier way of doing things.
Here is one last bit of information on graphics. You may recall from geometry that a point is an abstract location and has zero dimensions. This means that it cannot be pictorially represented in a literal sense. In Java, instances of points cannot be shown on the screen. In an application, in order to show points it would be necessary to draw small circles or dots, for example. Geometry also states that lines, having only one dimension, cannot be represented. However, in this case Java relents. Line segments are the simplest geometric objects that can be shown on the screen. Two dimensional shapes can also be represented.
5.3 An Applet Example
A simple example of an applet is given below, followed by an explanation. For the time being it is sufficient to be able to copy those elements needed in order for the applet to work and to become familiar with how to use the graphical elements. Numbers are included as comments in the code as reference points to the explanation.
import javax.swing.JApplet; // 1
import java.awt.Graphics; // 2
import java.awt.Graphics2D; // 3
import java.awt.geom.Point2D; // 4
import java.awt.geom.Line2D; // 5
public class LineApplet extends JApplet // 6
{
public void paint(Graphics g) // 7
{
Graphics2D g2 = (Graphics2D) g; // 8
Point2D.Double startpoint = new Point2D.Double(10, 20); // 9
Point2D.Double endpoint = new Point2D.Double(110, 120);
Line2D.Double myline = new Line2D.Double(startpoint, endpoint);
g2.draw(myline); // 10
}
}
A screen capture of the Applet Viewer after running the example is shown below. The x, y coordinate system in Java is oriented in this way: The origin, point (0, 0), is in the upper left hand corner. x values increase from left to right and y values increase from top to bottom. In other words, startpoint is in the upper left, and endpoint is to the lower right of it.

The numbered lines in the code are considered here:
1-5. If you look ahead in the code you will find that each of these classes is used, so each one is imported.
- Applets can be written as subclasses of the system supplied JApplet class. This line gives the correct syntax for establishing this.
- An applet has a paint() method rather than the main() method of an application. Within this method are the lines of code which draw things on the screen.
- The paint() method has to have a parameter of type Graphics. For historical reasons the parameter is typed Graphics, but it parameter should be cast to the class Graphics2D at the top of the method.
- In the example there are three lines of code where the startpoint, endpoint, and myline are created. Point objects are constructed with numerical parameters. Then a line object is constructed using those points as parameters.
- Calling the draw() method on the graphics object, g2, with myline as the parameter causes myline to be presented on the screen.
Although the individual lines can be explained, how the result is produced is not obvious from the code. In general, when the Java applet viewer is given a class such as this one, it creates an instance of the class. Since the class extends the JApplet class, the system knows that it has to contain a paint() method. The system calls this method on the object and passes the needed Graphics parameter. When the paint() method is run, the lines of code consisting of calls to draw() on g2 cause things to appear on the screen. It is convenient to think of the g2 object as a pen.
5.4 Drawing and Filling Geometric Shapes
Java comes with more complex geometric classes than just points and lines. Rectangles, ellipses, and circles will be used as examples and may appear in the assignment. For the sake of consistency, only 2D Double cases will be considered. The rectangle classes take four parameters, the x and y coordinates of the upper left hand corner of the rectangle, and the width (w) and height (h), respectively. Ellipses also take these four parameters. They are defined on the basis of the rectangle that they fit in, known as a bounding box.
Here is a simple example of the use of a rectangle in an applet. In addition to drawing a rectangle at a given location, the fill() method is also introduced, and a second rectangle appears in the output. The difference between draw() and fill() should be apparent.
import javax.swing.JApplet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
public class RectangleApplet extends JApplet
{
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Rectangle2D.Double myrectangle = new Rectangle2D.Double(10, 20, 30, 40);
g2.draw(myrectangle);
myrectangle = new Rectangle2D.Double(50, 20, 30, 40);
g2.fill(myrectangle);
}
}

5.5 Colors
Java also includes a mechanism for using colors in graphical output. There are system supplied colors. It is also possible to create custom colors. In order to use colors you need to import the Color class, using the following statement:
import java.awt.Color;
The system supplied colors are public, final constants in the Color class. Unlike other constants, their names consist entirely of small letters. This is how they can be referred to in a program:
Color.black
Color.blue
Color.cyan
Color.gray
Color.darkGray
Color.lightGray
Color.green
Color.magenta
Color.orange
Color.pink
Color.red
Color.white
Color.yellow
Colors are defined by telling how much of each of the three components red, green, and blue they contain. Each component can take on a value between 0.0 and 1.0. An example of creating a custom color is shown:
Color mycolor = new Color(0.75F, 0.0F, 0.25F);
For historical reasons, these parameters are floats rather than doubles. The “F” following each of the parameters causes a constant which would otherwise be considered a double to be cast to a float. Without this, there would be a compiler error.
Putting colors to use involves the graphics object, g2. This object has methods associated with it that allow you to change its characteristics. As already noted, you can think of it as a pen. Setting the color of the graphics object is like setting the color of the pen. Examples of statements which give the graphics object a particular color are:
g2.setColor(Color.red);
g2.setColor(mycolor);
Here is another small example of an applet with graphical output that illustrates the use of colors as well as the use of the Ellipse2D.Double class. In this example circles are created by setting the width and height parameters to the same value. Note that there is no convenient way of defining concentric circles. There is no constructor for ellipses that take the “center” as the reference point. The reference point for relative location is always the upper left hand corner of the bounding box.
import javax.swing.JApplet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.Color;
public class MyCircles extends JApplet
{
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Ellipse2D.Double mycircle = new Ellipse2D.Double(10, 20, 30, 30);
g2.setColor(Color.green);
g2.draw(mycircle);
mycircle = new Ellipse2D.Double(50, 20, 30, 30);
Color mycolor = new Color(0.75F, 0.0F, 0.75F);
g2.setColor(mycolor);
g2.fill(mycircle);
}
}
Here is the output from the program:

5.6 Text
It is also possible to include text in graphics output. The presentation of text has a long history. It has its own vocabulary, and virtually all of the details were worked out before the advent of computers. The topic is made complicated by the existence of different fonts on different kinds of computer systems, and the difficulty of trying to handle them all in a single computer language. This is one aspect of Java where supporting “Compile once, run everywhere” means limiting your choices.
Unlike the geometric shapes, which are oriented according to their upper left hand point in the x, y plane, text is oriented according to its “base point”. This is the left hand endpoint of the line on which the text is drawn. The base point does not depend on the lowest point of those parts of letters that descend below the line, and it also does not depend on where the initial letter first touches the line.
To use text in its simplest form in Java, it is necessary to use another method on the graphics object g2. You need to give the desired text as a string and also specify the x and y coordinates of the basepoint. Here is an example:
g2.drawString(“My text”, 20, 30);
If text is done in this way, you get the default font. It is also possible to change the font. In order to do this, Java’s Font class has to imported:
import java.awt.Font;
Among the system supplied fonts in Java are:
Serif
SansSerif
Monospaced
Dialog
DialogInput
These fonts can be set to different sizes which are given in the unit of measurement known as a point. They also have available system supplied characteristics like bold and italic. Here is a sequence of lines of code illustrating the creation of a new font, assigning it to the graphics object, and then presenting text in the output:
Font myfont = new Font(“Serif”, Font.BOLD, 16);
g2.setFont(myfont);
g2.drawString(“My text”, 20, 30);
In the Font constructor the three parameters are: The name of a Java supplied font type as a string; A characteristic of a font which is defined as a constant in the Font class; And a size in points which is an integer value. This new font is used as a parameter in the setFont() method of the Graphics2D object. Finally, a string is drawn. Note that the graphics object g2 can take on color characteristics, font characteristics, and other characteristics at the same time. Also keep in mind that parameters can be given as variables as well as constants.
When doing graphical output there may be difficulty in determining where things will appear relative to each other in the applet viewer window. Unfortunately, the relationship between the values of the coordinate axes for graphical shapes and for text output is not always clear. Rather than getting involved in a deep technical discussion of this, I recommend doing the following for now: Use trial and error and adjust the relative position of things by eye. Here is a final example where this technique was used in order to arrange things in a pleasing way.
import javax.swing.JApplet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.Color;
import java.awt.Font;
public class MyText extends JApplet
{
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.blue);
Font myfont = new Font("Serif", Font.ITALIC, 24);
g2.setFont(myfont);
String bluestring = "My Blue String";
Rectangle2D.Double bluerectangle = new Rectangle2D.Double(30, 30, 170, 45);
g2.draw(bluerectangle);
g2.drawString(bluestring, 40, 60);
}
}
Here is the output of the applet:

5.7 Putting Applets into Web Pages
In order to put an applet into a Web page you need to do three things: 1) Compile the applet and save the resulting class file. 2) Include the needed tags and other information in the html source code for the page that is to contain the applet. 3) Upload the html file and the class file to a directory on a server that is set to give access to Web pages.
Here is the minimum html code needed to create a Web page containing an applet:
<html>
<applet code="MyText.class" width="500" height="500">
</applet>
</html>
The <html> and </html> tags identify the beginning and ending of the page. The <applet> and </applet> tags identify the beginning and ending of the embedded applet. Inside the applet tag it is necessary to specify the source of the applet code to run as well as the size of the area in which it will appear. You may have discovered that it is possible to set the size of an applet from within the code rather than relying on the applet viewer’s default size. When attached to a Web page the size has to be set in the html file. Any line of code in the applet which is intended to set the size should be removed because it will conflict with the html tag. When doing your own examples you may duplicate the use of the code, width, and height tags as shown. Notice that it is the applet’s class file that is specified, not the .java source file. In this example the class file has to be in the same directory as the html file—no path is included when specifying the class file name. Remember that if you had to remove a line of code setting the size, the applet has to be recompiled and the new class file has to be used.
It is possible to embed applets in complex pages. It is also convenient to create simple pages such as the one shown above and link to them from other pages. This allows the main page to remain free of clutter while still making applets easily available through the browser.
5.8 Java Web Documentation
The topic of Java documentation is not conceptually related to the topic of applets. However, it is related in the sense that Java documentation is suitable for inclusion on a Web page. It is recommended practice to put comments in code when it is written. The examples in these notes are only sparsely commented because the programs are explained in the text. It is customary to provide comments for classes as a whole and for the constructors and methods within them. This serves as a form of internal documentation. Java also includes a feature where comments written following a specific format are all that is needed in order to generate Web documentation. Here is the cup class with comments in that format. The important features to note about this style of documentation are given following this class code.
/**
This version of the cup class has two constructors and three methods. The purpose of this example is to illustrate the format for comments that will generate Web documentation.
*/
public class Cup3Commented
{
private int seedCount;
/**
This is the default constructor. It takes no parameters. It explicitly sets the value of the seedCount instance variable of the cup to 0, the default initialization value. Because the class has another constructor written by the programmer, the system does not automatically provide a default constructor. As with all constructors, this constructor returns a reference to the object created.
*/
public Cup3Commented()
{
seedCount = 0;
}
/**
This constructor initializes the seedCount of the new cup to the value of the parameter.
@param initialCount, int, the initial value for the instance variable seedCount.
*/
public Cup3Commented(int initialCount)
{
seedCount = initialCount;
}
/**
This method returns the value of seedCount for a cup. It takes no parameters.
@return seedCount, int, the value of the instance variable seedCount.
*/
public int getSeedCount()
{
return seedCount;
}
/**
This method sets the seedCount for a cup. It does not return a value.
@param newCount, int, the new value for the instance variable seedCount.
*/
public void setSeedCount(int newCount)
{
seedCount = newCount;
}
/**
This method adds the value of the parameter to the current value of the seedCount for the cup. It does not return a value.
@param addedNumber, int, the amount by which the instance variable seedCount should be increased.
*/
public void increaseSeedCount(int addedNumber)
{
seedCount = seedCount + addedNumber;
}
}
Here is a brief description of the comment format shown above, and the steps needed in order to generate Web documentation from a Java file that has been commented in this way.
- Comments have to come immediately before the thing commented. This means, for example, that imports for a class will come before the comment for the class. Then inside the class, comments on the constructors and methods have to come right before the constructors and methods.
- Comments that are to generate Web page documentation have to be set off with a "slash-asterisk-asterisk" at the beginning and an "asterisk-slash" at the end. It is possible to include other comments in the code which will not generate any Web page documentation. These comments should be set off as usual by plain "slash-asterisk, asterisk-slash".
- For constructors and methods it is customary to provide general information and specific documentation on the parameters and return values, if there are any. The comments specifically for the parameters and return values are put on separate lines after the general comment, and these lines have to start with the "@" symbol.
- The documentation is generated by running the command line command "javadoc" against a Java source file containing such comments. The utility can also be run against more than one file in a directory at a time by using wildcards (*'s). This will cause unified documentation to be generated at the same time for all of the java source files that may belong together in a single application.
- It sometimes turns out that the biggest challenge to creating the documentation is problems with the PATH statement on the computer which prevent it from finding the javadoc program when you try to use it.
What follows is a list of some of the things you might need to know or might encounter when trying to create the documentation.
- You need to be able to get a command prompt. On a generic Windows machine you would follow the options: Start, Programs, Accessories, Command Prompt.
- You are then in a position where you need to know how to get to the directory where your program is stored. Generally, the command prompt will come by default at a prompt that starts "C:\...>". Depending on whether you’re on a network or not, and what kinds of drives are installed locally, the prompt may come up with a different letter.
- In particular, your prompt may come up "C:\WINDOWS>" or "C:\WINNT>" for example. If this is the case, then you can enter the command "cd .." and that will take you up one level in the directory tree so that your prompt is plain old "C:\>".
- On the other hand, if the prompt is comes up "H:\>", for example, or any other letter designating a different drive, the first thing you should do is type in "C:" and hit the enter key. This should bring you to a "C:\>" prompt.
- Now assume that your program is in a folder two levels down on the C drive. For example, it may be in the "myprogs" folder inside the "cs201" folder. In other words, the full path name to a particular program would read: c\cs201\myprogs\Someprog.java.
- You need to be able to navigate to this point using the command prompt. You can accomplish this as follows: At the C prompt, enter the command "cd cs201". When you hit the enter key, the prompt should come back as "C:\CS201>". At this prompt you should enter "cd myprogs". When you hit the enter key, the prompt should come back as "C:\CS201\MYPROGS>".
- Now if the PATH statement on your computer was set up correctly when Java was installed on it, at this prompt, you should be able to enter the following command. The full prompt and command are shown:
- C:\CS201\MYPROGS> javadoc Someprog.java
- If this runs successfully, you will find in the same directory a set of .html files containing the java documentation for the program. You can view and check them by opening them with the browser.
- If the path on your computer is not correct, it will not be able to find the javadoc utility, and it will not run. There are two possible approaches to dealing with this.
-
- If you are well versed in Windows or if you have a desire to read technical explanations, you can start studying the FAQ page on the TextPad and Sun web sites, finding out how you can change the path on your computer so that it will find javadoc.
-
- The second possible solution is quick and dirty. It is less than ideal, but it is sufficient to do this one time in order to complete an assignment. On a computer where Java has been installed it should be possible to find a folder on the C: drive with a name like "jdk1.3.1" (depending on what version was installed). Inside that folder should be a folder with the name "bin". Inside that folder is where the javadoc utility is. Make a copy of your Java source code file in that directory. Then go to the command prompt, change directories to the "bin" directory, and enter the command "javadoc Someprog.java". You have overcome the path problem because the system will find javadoc in the current directory along with your program file. Be careful not to delete or move any pre-existing system stuff out of the "bin" directory. This could potentially force you to have to re-install Java. However, do move all of the .html files resulting from a successful run of the javadoc utility out of that folder. These are the results that you are looking for.
Download MyTerminalIO class
Author: Kirk Scott
Мы рекомендуем Вам зарегистрироваться либо войти на сайт под своим именем.




