Программисты.kz > Уроки Java > An Introduction to Applets and Graphics
An Introduction to Applets and Graphics18-12-2009, 19:35. Разместил: КазКиберГетик |
|
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.lang.Object
java.lang.Object
java.lang.Object
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.
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;
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.
What follows is a list of some of the things you might need to know or might encounter when trying to create the documentation.
Download MyTerminalIO class Author: Kirk Scott Вернуться назад |