Wyo Java Ch. 4 Lecture Notes
Objective #1: Create applets.
- An applet is a Java program that executes within a Web browser such as Microsoft Internet Explorer.
- By default, an applet executes within a sandbox which prevents it from writing to files and performing other "dangerous" tasks on a person's desktop computer. Although, an applet can be signed to mark it as trusted on a given desktop computer in which case it can perform practically any operation that a Visual Basic, C, or C++ program could perform.
- An applet must be housed within a Web page (i.e. an HTML file) since it must execute within a browser. The applet tag can be used to include the applet within the HTML file.
<applet code="example.class" width="300" height="500"></applet>
The HTML code above allows the compiled Java file named example.class to execute within the Web page. The size of the area on the Web page where the applet is allowed to execute is 300 pixels wide by 500 pixels tall.
- Since the Web browser executes an applet, the applet does not need a main method like the console applications that we have studied previously. However, the applet does neet to contain a paint method in order for it to be seen within the browser window. The paint method receives a Graphics object as a parameter. By convention, this Graphics object is named g. The Graphics object stores the state of the graphics window that is going to be displayed. Properties such as current color, font, etc. are included as part of the Graphics object's state.
- You must add the import statements
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
to the top of a Java applet source file.
Objective #2: Display graphical shapes.
- Some interesting classes to use are Rectangle, Rectangle2D.Double, and Ellipse2D.Double. The difference between Rectangle2D.Double and Rectangle is that Rectangle2D.Double allows a rectangle's coordinates to be floating-point values whereas Rectangle only allows integer coordinates to be used. Rectangle2D.Double and Ellipse2D.Double are called inner classes and must be typed with the period in their names.
- The Line2D.Double class is useful to draw line segments in an applet or GUI application.
- Some useful methods of the Graphics2D class are draw and setStroke.
- You must add the appropriate import statements to the top of an applet or GUI application source file in order to use the previously mentioned objects:
import java.awt.Line2D;
import java.awt.Rectangle2D;
import java.awt.Ellipse2D;
import.java.awt.Point2D;
Objective #3: Use colors.
- Color objects can be used to give interesting colors to graphical shapes drawn in an applet or GUI application.
Objective #4: Display text with various fonts.
- You can use the drawString method of the Graphics2D class to display text in an applet or GUI application window.
- You can also instantiate a Font object and use the setFont method of the Graphics2D class to use that font in an applet.