700 likes | 812 Views
Honors Computer Programming 1-2. Introduction To Chapter 4 Applets and Graphics. Chapter Goals. To be able __________________________________. to write simple graphical applications. To be able _____________________. to write simple applets.
E N D
Honors Computer Programming 1-2 Introduction To Chapter 4 Applets and Graphics
Chapter Goals • To be able __________________________________ to write simple graphical applications • To be able _____________________ to write simple applets • To ______________________________________________ display graphical shapes such as lines and ellipses • To use _________ colors • To __________________________ display text in multiple fonts • To select ____________________________ appropriate units for drawing
Why Applets? There are three kinds of Java programs that you will learn to write: ___________________ , _____________________ , and _______ . console applications graphical applications applets window Console applications run in a single, plain ________ . Applications with a graphical interface use one or more windows filled with _________________________ such as _________ , _______________ , and ________ . user interface components buttons text input fields menus Applets are similar to applications with a graphical interface but they run inside a _________ . browser
Why Applets? web server The code for an applet is stored on a ___________ and downloaded into the browser whenever you access a web page that contains the applet. There is an advantage to this: you don't have to be at your own computer to _____ a program that is _____________ as an applet. run implemented The designers of Java came up with two safeguards: Java applets can run at specified _________________ and they can be _______. security privileges signed Virtual Machine That is because the Java _______________ can limit the actions of an _______ . applet information By default, applets can only display ____________ and get user input, but it can't ___________________ on the user's computer. touch anything else privileges read You can give the applet more __________ such as the ability to ______ and ______ local files if you notify your browser that the applet is to be ________ . write trusted
Frame Windows In this section you will learn how to display a _______ window. frame To show a frame carry out the following steps: • construct an object of the JFrame class JFrame frame = new JFrame( ); • set the size of the frame frame.setSize(300, 400); • set the title of the frame frame.setTitle("An Empty Frame"); If you omit this step, the _________ is simply left blank. title bar • set the "default close operation" frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); When the user closes the frame, the program automatically ______ . exits If you omit this step, the program continues _________ even after the frame is ________ . running closed • make the frame visible frame.setVisible(true);
Frame Windows The following simple program shows all of these steps and produces the frame shown. import javax.swing.JFrame; public class EmptyFrameTest { public static void main(String[ ] args) { JFrame frame = new JFrame( ); frame.setSize(300, 400); frame.setTitle("An Empty Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
Drawing Shapes In this section you will learn how to make shapes appear inside a _______ window. frame just two rectangles. The first drawing will be very modest: The purpose of this example is to show you the basic ________ of a program that creates a _________ . outline You cannot draw directly on a _______ . drawing Whenever you want to show anything inside a frame, be it a ________ or a _________ , frame you have to construct a ___________ object and _____ it to the ______ . button drawing component In the Swing toolkit, the _____________ class represents a _______ component. add frame JComponent blank
Drawing Shapes Since we don't want to add a blank component, we have to modify the ____________ class and specify how the component should be ________ . painted JComponent The solution is to define a new class that ________ the JComponent class. extends You will learn about the process of extending classes in chapter 11. For now, simply use the following code as a template: public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { drawing instructions go here } }
Drawing Shapes The __________ keyword indicates that our component class, ______________________ , inherits the methods of ____________ . extends RectangleComponent JComponent However, the RectangleComponent class is different from the plain JComponent class in one respect: the _________________ method will contain instructions to draw the ___________ . paintComponent rectangles When the window is shown for the first time, the paintComponent method is called ______________ . The method is also called when the window is ________ . automatically resized
Drawing Shapes The paintComponent method receives an object of type ____________ . Graphics the current _______ , _____ , etc. The Graphics object stores the graphics state: color font The designers of Java implemented an enhanced graphics class called _____________ . primitive However, the Graphics class is _________ . Graphics2D Whenever the Swing toolkit calls the paintComponent method, it actually passes a parameter of type ____________ . To recover the Graphics2D object, we use a ______ : Graphics2D cast public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D)g; //recover Graphics2D ... } }
Drawing Shapes Now you are ready to draw ________ . The ______ method of the Graphics2D class can draw shapes such as ___________ , _________ , line __________ , __________ , and _____ . shapes draw rectangles ellipses Here we draw a rectangle: segments polygons arcs public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { ... Rectangle box = new Rectangle(5, 10, 20, 30); g2.draw(box); ... } } The Graphics and Graphics2D classes are part of the java.awt package. The acronym _____ stands for Abstract Windowing Toolkit . awt
Drawing Shapes Here is the code for the RectangleComponent and RectangleComponentTest classes. Note that the _________________ method of the RectangleComponent class draws two rectangles. paintComponent import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.JComponent; public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { // recover Graphics2D Graphics2D g2 = (Graphics2D)g; // construct a rectangle and draw it Rectangle box = new Rectangle(5, 10, 20, 30); g2.draw(box); box.translate(15, 25); // move the rectangle 15 right and 25 down g2.draw(box); // draw moved rectangle } }
Drawing Shapes In order to see the drawing, one task remains. You need to _________ the frame into which you added a component object. display Follow these steps: • construct a _______ as described in the preceeding section frame • construct an object of your component class RectangleComponent component = new RectangleComponent( ); • add the component to the frame frame.getContentPane( ).add(component); If you are running version 5.0 of Java, this line becomes frame.add(component); • make the frame _______ as shown in the preceeding section visible
Drawing Shapes The following simple program shows the complete process: import javax.swing.JFrame; public class RectangleComponentTest { public static void main(String[ ] args) { JFrame frame = new JFrame( ); frame.setSize(300, 400); frame.setTitle("Two Rectangles"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); RectangleComponent component = new RectangleComponent( ); frame.getContentPane( ).add(component); frame.setVisible(true); } }
Applets Some people prefer to use ________ to display graphical shapes. applets They don't need separate ____________ and ______ classes. Applets have two advantages. component Instead you only need a ______ class. And more importantly, applets can run inside a _________ which allows you to put your creations on a __________ . test single browser web page public class MyApplet extends JApplet { public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; // drawing instructions go here ... } } To run an applet, use this code outline: This is almost the same outline as for a component with two minor differences: • you extend _________ , not JComponent JApplet • you place the drawing code inside the ________ method, not inside paintComponent paint
Applets The following applet draws two rectangles: import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.JApplet; public class RectangleApplet extends JApplet { public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; Rectangle box = new Rectangle(5, 10, 20, 30); g2.draw(box); box.translate(15, 25); g2.draw(box); } }
Applets To run this applet, you need a _______ file with an _______ tag. HTML, the __________ _________ __________ , is the language used to describe ______ pages. HTML applet hypertext markup language Here is the simplest possible file to display the rectangle applet: web <applet code="RectangleApplet.class" width="300" height="300"> </applet> If you know HTML, you can add text and more HTML tags: <html> <head> <title>Two Rectangles</title> </head> <body> <p>Here is my <i>first</i> applet.</p> <applet code="RectangleApplet.class" width="300" height="300"> </applet> </body> </html>
Applets To run the applet, you have two choices. You can use the applet ________ , a program that is included with your Java software. viewer You can also open the applet in a _____________ by using the browser to open the ______ file. web browser HTML The _________ is responsible for starting up the Java _______________ , Unlike applications, applets don't have a ______ method. browser main for loading the applet ______ , and for ________ the applet. Virtual Machine code starting The applet generated is shown at the right. The top line will only appear if the HTML file is opened inside a browser.
Graphical Shapes bounding box To draw an ellipse, you specify its ______________ in the same way that you would specify a rectangle, namely by specifying the x- and y- coordinates of its ________ corner and the ______ and _______ of the box. top-left width height To do this we will use the __________________ class. Ellipse2D.Double Here is how you construct an ellipse: Ellipse2D.Double easterEgg = new Ellipse2D.Double(5, 10, 15, 20);
Graphical Shapes The class name Ellipse2D.Double which is composed of two names separated by a period, indicates that Double is an ___________ inside the ___________ class. inner class In the import statement at the top of your program, you must import only the ____________ which is: Ellipse2D outer class import java.awt.geom.Ellipse2D;
Graphical Shapes To draw an ellipse, you use the same ______ method of the ___________ class that you use for rectangles: draw Graphics2D g2.draw(easterEgg); To draw a circle, set the _______ and ________ to the same value: width height Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter); g2.draw(circle); Note the (x, y) is the _________ corner of the bounding box, not the _______ . top-left center
Graphical Shapes You construct a line by giving the coordinates of its ___________ . To draw a line, use an object of the _______________ class. Line2D.Double You can do this in two ways. endpoints You can simply give the endpoints of both points: Line2D.Double segment = new Line2D.Double(x1, y1, x2, y2); Or you can specify each endpoint as an object of the _________________ class: Point2D.Double Point2D.Double from = new Point2D.Double(x1, y1); Point2D.Double to = new Point2D.Double(x2, y2); Line2D.Double segment = new Line2D.Double(from, to);
Graphical Shapes To draw thicker lines, supply a different _______ object to the Graphics2D parameter. stroke For example, to get lines 4 pixels thick: g2.setStroke(new BasicStroke(4.0F)); The parameter 4.0F indicates that the number is of type ______ . float
Colors When you first start drawing shapes, all shapes are drawn with a _______ pen. black To change the color, you have to supply an object of type ______ . Color Colors are specified by different amount of ____ , ______ , and _____ . red green blue The amounts are given as ______ values, which you must identify by the suffix ___ . float to _____ (maximum amount present). They vary from ______ (primary color not present) 1.0F F 0.0F For example, Color magenta = new Color(1.0F, 0.0F, 1.0F); constructs a _______ object with maximum red, no green, and maximum blue yielding a color called _________ . Color magenta
Colors A variety of colors have been predefined in the Color class. These are shown in the table.
Colors Once you have an object of type Color, you can change the _____________ of the Graphics2D object with the __________ method. current color setColor For example, the following code draws a rectangle in _______ , then switches the color to _____ , and draws the next rectangle in _____ . black red red public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; Rectangle cerealBox = new Rectangle(5, 10, 20, 30); g2.draw(cerealBox); // draws in black cerealBox.translate(15, 25); // move rectangle g2.setColor(Color.red); // set current color to red g2.draw(cerealBox); // draws in red }
Colors If you want to color the inside of the shape, you use the ______ method instead of the ______ method. fill For example, draw fills the inside of the rectangle with the ________ color. current g2.fill(cerealBox);
Fonts You can use the ____________ method of the Graphics2D class to draw a _______ anywhere in the window. drawString You must specify the _______ and the x- and y-coordinates of the ___________ of the first character in the string. string string Basepoint For example, g2.drawString("Applet", 50, 100);
Fonts You can select different _______ . You create a ______ object and call the ____________ method of the Graphics2D class. fonts Font To create a Font object you specify: drawString • the font face _______ name • the ______ (one of _____________ , _____________ , ____________ , or __________________________ ) style Font.PLAIN Font.ITALIC Font.BOLD + Font.ITALIC Font.BOLD • the __________ point size
Fonts The font face name is either one of the five __________________ or a typeface name. logical face names The five logical face types are summarized in the table shown.
Fonts The code below shows how to write "Applet" in huge red letters. final int HUGE_SIZE = 36; final int HUGE_SIZE = 36; String message = "Applet"; String message = "Applet"; Font hugeFont = new Font("Serif", Font.BOLD, HUGE_SIZE); Font hugeFont = new Font("Serif", Font.BOLD, HUGE_SIZE); g2.setFont(hugeFont); g2.setFont(hugeFont); g2.setColor(Color.red); g2.setColor(Color.red); g2.drawString(message, 50, 100); call the drawString method of the Graphics2D class to draw the string call the setColor method of the Graphics2D class to set the color call the setFont method of the Graphics2D class to set the font set the font name, style, and point-size use a constant to set the font size define the string
Fonts To measure the size of a string, you need to construct a ____________________ object, which you can obtain from the Graphics2D object by calling ________________________ . FontRenderContext A font render context is an object that knows how to transform letters into _______ . getFontRenderContext pixels
Fonts getStringBounds To get the size of the string you call the _________________ method of the Font class. For example, String message = "Applet"; String message = "Applet"; FontRenderContext context = g2.getFontRenderContext( ); FontRenderContext context = g2.getFontRenderContext( ); Rectangle2D bounds = hugeFont.getStringBounds(message, context); declare and assign the string get the FontRenderContext of the graphics environment bounds is a rectangle that matches the size of the string. If bounds were drawn, it would appear as shown above.
basepoint corresponding pointon bounds at (0,0) Fonts The returned rectangle is positioned so that the origin (0, 0) falls on the __________ . basepoint part of bounds The height and width of bounds matches the height and width of the string.
Fonts The returned rectangle is positioned so that the origin (0, 0) falls on the __________ . Therefore, you get the ________ , _________ , ________ , and _______ as basepoint ascent descent height width double yMessageAscent = -bounds.getY( ); double yMessageDescent = bounds.getHeight( ) + bounds.getY( ); double yMessageHeight = bounds.getHeight( ); double xMessageWidth = bounds.getWidth( );
Fonts The following program uses these messages to center a string precisely in the middle of an applet window even if it is resized. To center the string, you have to know the _____ of the applet. size The __________ and ___________ methods return the applet size in pixels. getWidth getHeight To center the string, think of the amount of white space you have available.
Fonts The width of the applet window is _____________ . The width of the string is ________________ . getWidth( ) Therefore, the blank space is the difference xMessageWidth getWidth( ) - xMessageWidth . Therefore, the string should start at Half of that space should be distributed on either side. double xLeft = (getWidth( ) - xMessageWidth) / 2;
Fonts For the same reason, the top of the string is at double yTop = (getHeight( ) - yMessageHeight) / 2; . But the drawString method needs the basepoint of the string. You get to the baseposition by adding the ascent: double yBase = ytop + yMessageAscent; The complete code is shown on the handout. Try resizing the window and observe that the string always stays centered.
Drawing Complex Shapes The next program shows how to ___________________ to draw a simple figure of a car. put shapes together It is a good idea to make a separate class for ____________________ . To figure out how to draw a complex shape, make a ________ on graph paper. each complex shape sketch The code for the program is shown on the handout in two files: • CarApplet.java// applet code • Car.java// code to draw a car
Reading Text Input The applets we have seen so far are not ___________ that is, you can't change the __________ of the shapes that are drawn on the screen. interactive positions In a console program, the _____________ dictates control flow and forces the user to enter each ______ in a predetermined order. programmer input A graphical program, however, generally makes available to the user a large number of _________ ( _________ , ____________ , ___________ , etc) which users can manipulate in any order they please. controls buttons input fields scroll bars Therefore, the program must be prepared to process input from multiple sources in _________ order. You will learn how to do that in chapter 10. random
Reading Text Input In the meantime, we will continue to read input with the _______________________________ method. JOptionPane.showInputDialog You should place any calls to the showInputDialog method into the __________________ , not the _______ method. That way, the user is prompted for input exactly ______ . applet constructor paint To get another chance to supply input, choose ________ or _________ from the browser or applet viewer. once Reload Refresh
Reading Text Input If you put the call to showInputDialog inside the applet constructor, then your applet needs to remember the user input in one or more _______________ and refer to these variables in the _______ method. instance fields paint The following program is an example. It prompts the user for _____ , _______ , or ______ values and then fills a rectangle with the color that the user specified. red green blue The code is on the handout.
Reading Text Input When you run this program, you will note that the input dialog has a label identifying it as an ______________ . This is an applet _________ feature. applet window security It would be an easy matter for a hacker to write an applet that pops up a dialog "Your password has expired. Please reenter your password." and then sends the _______ back to the web server. input The window label tips you off that it is an _______ and not your _________________ . applet All windows that pop up from an applet have this ________________ . operating system security feature
Comparing Visual and Numerical Information The next problem will consider the intersection of a circle and a line. Ask the user to specify the position of a vertical line. The circle has a radius of 100 and a center of (100, 100). Then draw the circle, the line, and the intersection points.
Comparing Visual and Numerical Information The equation of a circle with radius r and center point (a, b) is We will consider a little mathematics: . If you know x, then you can solve for y : . This is easy to compute in Java: double root = Math.sqrt(r r - (x - a) (x - a)); double y1 = b + root; double y2 = b - root;
Comparing Visual and Numerical Information If your program is correct, these two points will show up right on top of the actual intersections in the picture. The code for this program is on the handout.
Comparing Visual and Numerical Information At this point, you have to be careful to specify only lines that _________ the circle. intersect If the line doesn't meet the circle, then the program will attempt to compute a __________ square root and a ___________ will occur. negative math error We have not yet discussed how to implement a _____ to protect against this situation. test That is the topic of the next chapter.
Coordinate Transformations pixels By default the draw method uses _______ to measure screen locations. This system causes problems when working with real-world data. For example, suppose you want to show a chart plotting the average temperature (degrees Celsius) in Phoenix for every month of the year. The temperature ranges from 11 degrees Celsius in January to 33 degrees Celsius in July.
Coordinate Transformations Here the x-values range from ___ to ____ and the y-values range from ____ to ____ . 1 12 11 The applet pixel coordinates range from ___ to ________________ and ___ to _________________ . 33 0 If the height and width of the applet were 300 pixels each, we can't use pixel coordinates for the data since the graph would be too small. getWidth( )-1 0 getHeight( )-1
y y min max Coordinate Transformations In such a situation, you need to define _________________ that make sense for your particular situation. user coordinates You can transform user coordinates by using the following equations: are _________ . Note that for the y-coordinates, the roles for and In Java, y-coordinates increase when moving ________ whereas in mathematics they __________ when moving down. reversed down decrease