Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
JAVA PROGRAMMING SUBJECT CLASS UNIT SEMESTER STAFF NASC –IT : JAVA PROGRAMMING : II BSC IT : 4 : 4 : M. SHEELA NEWSHEEBA UNIT-IV: Managing Errors and Exceptions – Applet Programming – Graphics Programming. EXCEPTION HANDLING An exception is an abnormal condition that arises in a code sequence at runtime(or exception is a runtime error).A Java exception is an object that describes an exceptional condition that has occurred in a piece of code. When an exceptional condition arises an object representing the exception is created and it is thrown in the method that caused the error. The method can handle the exception or pass it. Exceptions can be generated by Java run-time system or they can be manually generated by your code. The statements that are to be monitored for any errors must be put inside the try block. If an exception occurs in the try block it is thrown. The code can catch that exception and handle it. To manually throw an exception use the keyword throw. All the exceptions that occur in a method has to be specified by the word throws. Any code that must be executed before a method returns is put in finally block. The general form of exception –handling block is try{ Block of code to be monitored for errors }catch(ExceptionType1 exobj){ //exception handler for ExceptionType1 } catch(ExceptionType2 exobj){ //exception handler for ExceptionType2 } finally{ //block of code to be executed before try block ends } Exceptiontype is the type of exception that has occurred. EXCEPTION TYPES The hierarchy of exception classes is as follows JAVA PROGRAMMING NASC –IT Throwable Error Exception Runtime Checked Exceptions Exceptions Errror and Exception are the subclasses of Throwable. And Exception class two subclasses ie Runtime unchecked Exceptions and Checked Exceptions. Stack overflow is an example for Error. Division by zero and invalid array indexing are examples for Runtime Exceptions. ClassNotFoundException, NoSuchFieldException are examples of Checked Exceptions. UNCAUGHT EXCEPTIONS Consider the following program public class Ex{ public static void main(String args[ ]){ int d = 0; int a = 50 / d ; } } We are making an attempt to divide a value by zero which results in an exception. Java runtime system detects this error and constructs a new exception object and throws the object. This causes the execution of the program to terminate. Since the exception is not caught here it will be handled by the default handler and the default handler just displays a string describing the exception and terminates the program. JAVA PROGRAMMING NASC –IT The output of the above program will be java.lang.ArithmeticException : / by zero at Ex.main(Ex.java.4) it the system specifies the class name and the method name where the exception occurs along with the line number. It keeps track of path of the exception. It specifies the type of the exception (ArithmeticException). Handling exceptions(using try and catch) Exception handling gives two advantages 1. It allows you to fix errors 2. It prevents the program from automatically terminating To handle a run-time error, enclose the code you need to monitor in try block and include a catch clause that specifies the exception type you wish to catch. Let us handle the ArithmeticException in the previous ex. class Ex2{ public static void main(String args[ ]){ int d, a; try{ d = 0; a = 50 / d ; System.out.println(“will not be printed”); }catch(ArithmeticException e){ System.out.println(“Division by zero”); } System.out.println(“After catch”); } } The output of the program Division by zero After catch. JAVA PROGRAMMING NASC –IT NESTED TRY STATEMENTS A try statement can be inside another try block. If an inner try block doesn’t have a catch handler then the next try block’s catch handlers are inspected for a match. This is continued until one of the catch statement succeeds or until all the try blocks have been exhausted. If no catch statement matches the Java run-time system will handle the exception. class Nesttry{ public static void main(String args[ ]){ try{ int a = 0; int b = 42 / a; System.out.println(“a “ +a); try{ int c [ ] = { 1}; c[ 42] = 99 ; }catch(ArrayOutofBoundsException e){ System.out.println(“Index out of range”); }catch(ArithmeticException e){ System.out.println(“Divide by zero”); } } } In the outer try block we are trying to assign a value to an array where index or subscript is out of range. The exception that occurs is ArrayOutofBoundsException which is handled and the outer block has ArithmeticException. USING THROW AND THROWS In the previous examples we handled exceptions which are thrown by Java run-time system. It is also possible for your program to throw exceptions explicitly using the keyword throw. The syntax is : throw throwableInstance ; When an exception occurs this statement throws the exception and the flow of execution stops after the throw statement. The subsequent statement in the try block are not executed and the enclosing catch is checked for matching exception. throws A throws clause lists the type of exceptions that a method might throw. This is necessary for all exceptions except that of type Error or Runtime Exception. All other exceptions can be declared in the throws clause. If not a compile-time error will occur. JAVA PROGRAMMING NASC –IT type method-name(parameter-list) throws exception-list{ //body of the method } exception-list is the list of exceptions that a method can throw Finally When exceptions occur, execution in a method takes a non-linear path. It is also possible for execution to cause the method to return prematurely. finally keyword is used to avoid this. finally will execute whether or not an exception is thrown. It can be useful for closing file handles and free up any other resources. Finally clause is optional. But each try statement must have atleast one catch or finally clause JAVA APPLET What is Java Applet •Java is a general purpose programming language. •A Java program is created as a text file with .java extension. •It is compiled into one or more files of bytecodes with .class extension. •Bytecodes are a set of instructions similar to machine code of a specific machine but it can be run on any machine that has a Java Virtual Machine (JVM). JVM interprets bytecodes. •JVM was first implemented on Sparc/Solaris and PC/Win32. Now ported to many other platforms. •Java applets are Java programs that are retrieved and executed by web browsers through the JVM under tight secure environment. •Web browsers retrieve Java applets according to following tags in the web pages: <applet code=ResPlotApplet.class width=600 height=500> deprecated or the new more general, <object codetype="application/java" classid="java:ResPlotApplet.class" width=600 height=500> • <param> are used to specify parameters for the applet. JAVA PROGRAMMING NASC –IT For example, <APPLET CODE="Animator.class" WIDTH="aNumber" HEIGHT="aNumber"> -- the width (in pixels) of the widest frame -- the height (in pixels) of the tallest frame <PARAM NAME="IMAGESOURCE" VALUE="aDirectory"> -- the directory that has the animation frames (gif, jpg) • All other types of java programs are called Java applications. • Examples: • Network Restoration Applet: User specifies two end node of a failed link. The applet retrieves the simulation results of two network restoration algorithms (twoprong and rreact) in two corresponding files at original web server site, and plot the results. SUN Java demos: MoleculeViewer SimpleGraph SortDemo BarChart Animator JumpingBox Java is safe • When a Java applet is downloaded, the bytecode verifier of the JVM verifies to see if it contains bytecodes that open, read, write to local disk. • Java applet can open new window but they have Java log to prevent them from being disguised as system window (for stealing password). • Java applet is not allowed to connect back to other servers except that hosts itself. JAVA PROGRAMMING NASC –IT • This secure execution environment is called sand box model. • JDK 1.1 extends this tight security with digitally signed applet using jar file. • More detailed fine grained security levels are planned for future release. Java Development Kit • The current release is JDK 1.1.7A. It is free for download, containing documents, demos, library, bin/utilities, and Java API packages. • Java Application Programming Interface (API) consists of classes for programming: o java.applet.*: for applet context and interface to browsers o java.lang.*: variable, string manipulation, exception handing, thread. o java.io.*: File I/O through [buffered] input/outputStream, o java.awt.*: Abstract Window Toolkit (AWT) for window/GUI design, image creation and manipulation o java.util.*: hashtable, stringTokenizer (simple split), date, random, bitset, vector. o java.net.*: url, urlconnection for connecting to original web servers, socket o java.math.*: math functions. o java.sql: for Java-Database interface • Extended APIs: o Media API for sound, video, 3D, VRML o Commerce API o Servlet API • JDK 1.2 will soon be released. JAVA PROGRAMMING NASC –IT Java Applet Development Environment • Make sure the CLASSPATH in your autoexec.bat does not contain local directory, or just comment it out. They triggers the security alarm saying that the applet trying access to local drive. • Use Jbuilder2 (in our PC lab). It contains o java source code editor o class browser o debugger o visual GUI design tool similar to VBasics. o wizard for guiding the java application, java applet, java class development. o extensive java beans and libraries for Database access and enhanced GUI design. • Create new Java Applet by o first create a project folder by select the File/New Project, the project wizard window appears replace the untitle string in the file textfield with your project name, say cs301hw6. replace the title of the project, click finish, a project template will appear. o then create the Java applet template by select File/New click on the Applet icon fill in the information in the applet creation dialog box (choose the core Java and Swing only option) write java code in the created template. control-s to save file the <jbuilder2 home>myprojects\cs301hw6 directory, where <jbuilder2home> is the directory setup for jbuilder2 in your system. select build/make "CompareCookieSales.java", it will compile the code, show the error if any, and save the class byte code in <jbuilder2home>myclasses\CompareCookieSales.class JAVA PROGRAMMING NASC –IT ftp the .java code and .class code (note there may be more than one .class generated) back to the web server directory. Make sure the case of the class file name is correct after the file transfer. • Download JDK1.1.7A (you can also try JDK1.2RC2 a beta release) to your own PC. • Use text editor to create .java source code. • Reference document http://java.sun.com/products/jdk/1.1/docs/api/packages.html web • Use " javac ResPlot.java" to compile the java code. • Create a web page with the object or applet tag to reference the Java Applet. page, Basics of Applet Programming Operators and Their Precedence The following table shows the precedence assigned to Java's operators. The operators in this table are listed in precedence order: the higher in the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with a relatively lower precedence. Operators on the same line have equal precedence. postfix operators [] . (params) expr++ expr-- unary operators ++expr --expr +expr -expr ~ ! creation or cast new (type)expr multiplicative * / % additive + - shift << >> >>> relational < > <= >= instanceof equality == != bitwise AND & JAVA PROGRAMMING NASC –IT bitwise exclusive OR ^ bitwise inclusive OR | logical AND && logical OR || conditional ? : assignment = += -= *= /= %= &= ^= |= <<= >>= >>>= When operators of equal precendence appear in the same expression, some rule must govern which is evaluated first. In Java, all binary operators except for the assignment operators are evaluated in left to right order. Assignment operators are evaluated right to left. Control Flow Statements A statement such as the while statement is a control flow statement, that is, it determines the order in which other statements are executed. Besides while, similar to C, the Java language supports several other control flow statements (except the exception handling), including: Statement Keyword decision making if-else, switch-case loop for, while, do-while exception try-catch-finally, throw miscellaneous break, continue, label: , return Note: Although goto is a reserved word, currently the Java language does not support the goto statement. Handling errors with Expression using Try, Catch, and Throw Basic Steps: •All Applet source code starts with import java.applet.*; JAVA PROGRAMMING NASC –IT and other import statements for packages used in the applet such as import java.awt.*; import java.io.*; import java.lang.*; import java.net.*; import java.util.*; •It then starts with a class definition like: public class Chart extends java.applet.Applet { // followed by a list of variables or objects declaration // Button b1 = new Button("play"); Button b2 = new Button("stop"); Button b3 = new Button("resume"); TextField tf = new TextField("Message here", 50); TextArea ta = new TextArea("please wait...", 10, 40); } •The main class contains four basic Applet methods: public void init() { // for any initialization code performed during loading time of the applet // such as loading graphics, initialize variables, creating objects // add() is used to insert the objects into the area allocated for the applet add(b1); add(b2); add(b3); add(tf); add(ta); } public void start() { // implement the main action of the applet behavior // it is also called by browser to restart after it was stopped. } public void stop() { // stop an applet's execution but leaves resources intact so it can restart. JAVA PROGRAMMING NASC –IT } public void destroy() { // release all its resources // typically happens when the user leaves the page containing the applet. } •Many Applet only needs to implement init() •For control and user input, Button, TextField, TextArea, Canvas objects are created in init() and special method action() is called when event happens public boolean action(Event e, Object o) { if (e.target instanceof Button) { String s = (String) o; if (s.equals("play") { tf.setText("play button is pushed"); } else if (s.equal("stop") { ta.setText("stop button is pushed"); } else { ta.appendText("resume button is pushed"); } return true; } return false; } •Try this basic example. JAVA PROGRAMMING NASC –IT Abstract Window Toolkit (AWT) Tutorial from Netscape Note that there are new GUI packages such swing and Java 2D graphics recommended by Netscape. They are great for making Java applications with GUI, but there are still a lot of browsers do not support that. They require JDK1.2 compatible viewer or Java plug in. "Java Plug-in software enables enterprise customers to direct Java applets or JavaBeansTM components on their intranet web pages to run using Sun's Java Runtime Environment (JRE), instead of the browser's default Java runtime. This enables an enterprise to deploy Java applets that take full advantage of the latest capabilities and features of the Java platform and be assured that they will run reliably and consistently. " -- http://java.sun.com/applets/index.html. Using JFC/SWING to create GUI The swing components in Java Foundation Classes (JFC) is the new package in JDK1.1 and JDK1.2 for supporting GUI design in Java applications and applets. It provides much more features to those of AWT. For examples, • allow images on buttons/labels, • dynamically change of borders, • component can be round, • specify look and feels (Java, Windows, CDE/Motif). • wider selection of components • not using native code (more portable) Unfortunately, Sun recommends that SWING and AWT components not mix. Their drawing sequence are basically different. "Heavyweight" AWT components such as menu, scrollpane, canvas, and panel always draw on top of "lightweight" SWING components. Tutorial on using GridBagLayout. JAVA PROGRAMMING NASC –IT Note that the current tutorial on java.sun.com is going through major revision. Some web pages, such as the layout manager tutorial, event hung the whole browser. Use them with caution. 12/3/98. Example for using GridBagLayout and submit data to a CGI script • Illustrate the use of the GridBagLayout manager and AWT components. • Learn how to exchange data between Applet and CGI script using URL. How we arrange the GridBagLayout using GridBagConstraints: • Here we create a title as a Label and set gbc.anchor = GridBagConstraints.NORTH. • We have login and address Labels and set their gbc.anchor = GridBagConstraints.WEST and gbc.gridwidth = 1. • The login TextField and address TextArea GridBagConstraints.REMAINDER. are set with gbc.grdiwidth = • The submit Button is set with gbc.anchor = GridBagConstraints.CENTER and padded with 10 pixels on each side using gbc.insets = new Insets(10,10,10,10); • Finally the return result TextArea is set with gbc.anchor = GridBagConstraints.SOUTH and gbc.grdiwidth = GridBagConstraints.REMAINDER. Basic steps for using the applet: • When the submit button is hit, the action method first performs www-url-encode on the content of address TextArea, then puts the fields of the login and address in the name-value pair format attached at the end of the url. • Create a URL with it, which in effect submit the data the corresponding CGI script on the server side. • The registerData.pl saves the data in a file and return a web page that is then displayed in the result TextArea JAVA PROGRAMMING NASC –IT JAVA GRAPHICS Canvas class First thing you will need is the Canvas class. This class is used to create an area in a frame to be used for displaying graphics. NOTE: All the classes you will need to display graphics (as well as frames) are located in the java.awt package. Canvas class methods: • void setSize(width, height) - Sets the size of the canvas • void setBackground(Color c) - Sets the background color of the canvas • void setForeground(Color c) - Sets the text color of the canvas Add a canvas to a frame just like you would any other component: Canvas C1 = new Canvas(); C1.setSize(120,120); C1.setBackground(Color.white); Frame F1 = new Frame(); F1.add(C1); F1.setLayout(new FlowLayout()); F1.setSize(250,250); F1.setVisible(true); Displaying graphics on a component Now that you have a Canvas (an area to display graphics on) how do you actually display those graphics? With the paint() method of the Frame class. The paint() method takes one attribute - an instance of the Graphics class. The Graphics class contain methods which are used for displaying graphics. The Graphics class lets a component draw on itself. JAVA PROGRAMMING NASC –IT Syntax: public void paint(Graphics g){ //methods for drawing graphics here; } Drawing lines To draw lines, the drawLine() method of the Graphics class is used. This method takes four numeric attributes - the first two indicating the x/y starting point of the line, the last two indicating the x/y ending point of the line. Example: public void paint(Graphics g){ //draw a line starting at point 10,10 and ending at point 50,50. g.drawLine(10, 10, 50, 50); } Drawing rectangles To draw rectangles, the drawRect() method is used. This method takes four numeric attributes the first two indicating the x/y starting point of the rectangle, the last two indicating the width and height of the rectangle. Example: public void paint(Graphics g){ //draw a rectangle starting at 100,100 width a width and height of 80 g.drawRect(100, 100, 80, 80); } Filling a rectangle By default a rectangle will have no color on the inside (it will just look like a box). You can use the fillRect() method to fill a rectangle. The fillRect() method has four numeric attributes indicating the x/y starting position to begin filling and the height and width. Set these values the same as you did for the drawRect() method to properly fill the rectangle. Example: public void paint(Graphics g){ //draw a rectangle starting at 100,100 width a width and height of 80 g.drawRect(100, 100, 80, 80); g.fillRect(100, 100, 80, 80); } Something's missing... The rectangle is filled, but we didn't set a color for it! To do this, we will use the setColor() method. g.setColor(Color.orange); JAVA PROGRAMMING NASC –IT Drawing ovals To draw ovals, the drawOval() method is used. This method takes four numeric attributes - the first two indicating the x/y starting point of the oval, the last two indicating the width and height of the oval. Fill an oval with the fillOval() method which also takes four numeric attributes indicating the starting position to begin filling and the height and width. Set these values the same as you did for the drawOval() method to properly fill the oval. Example: public void paint(Graphics g){ g.setColor(Color.gray); //draw an oval starting at 20,20 with a width and height of 100 and fill it g.drawOval(20,20, 100, 100); g.fillOval(20,20, 100, 100); } Displaying images To display images, the Image class is used together with the Toolkit class. Use these classes to get the image to display. Use the drawImage() method to display the image. Example: public void paint(Graphics g){ Image img1 = Toolkit.getDefaultToolkit().getImage("sky.jpg"); //four attributes: the image, x/y position, an image observer g.drawImage(img1, 10, 10, this); } An entire Java graphics program: import java.awt.*; class GraphicsProgram extends Canvas{ public GraphicsProgram() { setSize(200, 200); setBackground(Color.white); } public static void main(String[] argS) { //GraphicsProgram class is now a type of canvas //since it extends the Canvas class //lets instantiate it JAVA PROGRAMMING NASC –IT GraphicsProgram GP = new GraphicsProgram(); //create a new frame to which we will add a canvas Frame aFrame = new Frame(); aFrame.setSize(300, 300); //add the canvas aFrame.add(GP); aFrame.setVisible(true); } public void paint(Graphics g) { g.setColor(Color.blue); g.drawLine(30, 30, 80, 80); g.drawRect(20, 150, 100, 100); g.fillRect(20, 150, 100, 100); g.fillOval(150, 20, 100, 100); Image img1 = Toolkit.getDefaultToolkit().getImage("sky.jpg"); g.drawImage(img1, 140, 140, this); } } Drawing basic shapes For answers to the questions asked in the previous section, see the discussion on this page. Contents • 1 Drawing basic shapes o 1.1 Introduction to Graphics o 1.2 Etching a line on the canvas 1.2.1 Understanding coordinates 1.2.2 Drawing a simple line across the screen o 1.3 Drawing a simple rectangle 1.3.1 Playing around with colors JAVA PROGRAMMING NASC –IT 1.3.2 Filling up the area of the rectangle o 1.4 What about a circle? o 1.5 A new form of a rectangle o 1.6 Hmm, everything's perfect, but... o 1.7 What has eyes that pop out? o 1.8 External Links Introduction to Graphics Throughout this chapter, we would be referring to the process of creation on Graphical content by code as either drawing or painting. However, Java officially recognizes the latter as the proper word for the process, but we will differentiate between the two later on. Now, the main class that you would be needing would, without doubt, be the Graphics class. If you take a closer look at the method that we used in the previous section, namely the paint(Graphics) method, you would see that while you overrode said method, you actually obtained an instance of the Graphics class. Up until now the structure of code that we have is as follows (from Listing 9.2): Listing 9.3: Identifying the acquisition of the Graphics class in our code import java.awt.*; import javax.swing.*; public class MyCanvas extends Canvas { public MyCanvas() { } public void paint(Graphics graphics) { JAVA PROGRAMMING NASC –IT /* We would be using this method only for the sake * of brevity throughout the current section. Note * that the Graphics class has been acquired along * with the method that we overrode. */ } public static void main(String[] args) { MyCanvas canvas = new MyCanvas(); JFrame frame = new JFrame(); frame.setSize(400, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(canvas); frame.setVisible(true); } } To view the contents of the Graphics class, please check the external links at the bottom of the page for links to the online API. Etching a line on the canvas Understanding coordinates To start off your drawing experience, consider drawing the most basic shape - a line. A canvas when viewed upon with regards to drawing routines can be expressed as an inverted Cartesian coordinate system. A plane expressed by an x- and a y-axis. The origin point or (0,0) being the top-left corner of a canvas and the visible area of the canvas being the Cartesian quadrant I or the positive-positive (+,+) quadrant. The further you go down from the top, the greater the value of y-coordinate on the y-axis, vice-versa for the x-axis as you move toward the right from the left. and unlike the values on a normal graph, the values appear to be positive. So a point at (10,20) would be 10 pixels away from the left and 20 pixels away from the top, hence the format (x,y). JAVA PROGRAMMING NASC –IT Figure 9.2: A simple line form displayed across the canvas from Listing 9.4 Drawing a simple line across the screen Now, we already know that a line is a connection of two discreet points atop a canvas. So, if one point is at (x1,y1) and the other is at (x2,y2), drawing a line would require you to write a syntax like code below. For the sake of brevity, we will skim out the rest of the method unused in the example. Listing 9.4: Drawing a simple line form ... public class MyCanvas extends Canvas { ... public void paint(Graphics graphics) { JAVA PROGRAMMING NASC –IT graphics.drawLine(10, 20, 300, 310); } ... } In the above example, a simple method is used to define precisely where to place the line on the Cartesian scale of the canvas. The drawLine(int,int,int,int) asks you to put four arguments, appearing in order, the x1 coordinate, the y1 coordinate, the x2 coordinate and the y2 coordinate. Running the program will show a simple black line diagonally going across the canvas. Figure 9.3: A simple black-outlined rectangle drawn Drawing a simple rectangle We now proceed on to our second drawing. A simple rectangle would do it justice, see below for code. Listing 9.5: Drawing a simple rectangle JAVA PROGRAMMING NASC –IT public class MyCanvas extends Canvas { public void paint(Graphics graphics) { graphics.drawRect(10, 10, 100, 100); } } In the above example, you see how easy it is draw a simple rectangle using the drawRect(int,int,int,int) method in the Graphics instance that we obtained. Run the program and you will see a simple black outline of a rectangle appearing where once a blank canvas was. The four arguments that are being passed into the method are, in order of appearance, the xcoordinate, the y-coordinate, width and the height. Hence, the resultant rectangle would start painting at the point on the screen 10 pixels from the left and 10 from the top and would be a 100 pixel wide and a 100 pixel in height. To save the argument here, the above drawing is that of a square with equal sides but squares are drawn using the same method and there is no such method as drawSquare(int,int,int,int) JAVA PROGRAMMING NASC –IT Figure 9.4: Same rectangle drawn with a red outline Playing around with colors You can change the color of the outline by telling the Graphics instance the color you desire. This can be done as follows: Listing 9.6: Changing the outline color of the rectangle public class MyCanvas extends Canvas { public void paint(Graphics graphics) { graphics.setColor(Color.red); graphics.drawRect(10, 10, 100, 100); } } Running the program would render the same rectangle but with a red colored outline. For the purposes of bringing color to our drawing, we used a method namely the setColor(Color) method which asks for an argument of type Color. Now because you have no idea of how to actually instantiate a Color class, the class itself has a few built-in colors. Some built-in colors that you can use are mentioned below. • Color.red • Color.blue • Color.green • Color.yellow • Color.pink • Color.black JAVA PROGRAMMING • NASC –IT Color.white Try running the program while coding changes to colors for a different colored outline each time. Play around a bit with more colors. Look for the Color class API documentation in the external links at the bottom of the page. Figure 9.5: Same rectangle drawn with a red outline and a yellow fill Filling up the area of the rectangle Up until now, you have been able to draw a simple rectangle for yourself while asking a question silently, "why is the outline of the rectangle being painted rather the area as a whole?" The answer is simple. Any method that starts with drawXxxx(...) only draws the outline. To paint the area within the outline, we use the fillXxxx(...) methods. For instance, the code below would fill a rectangle with yellow color while having a red outline. Notice that the arguments remain the same. Listing 9.7: Drawing a yellow rectangle with a red outline public class MyCanvas extends Canvas { public void paint(Graphics graphics) JAVA PROGRAMMING NASC –IT { graphics.setColor(Color.yellow); graphics.fillRect(10, 10, 100, 100); graphics.setColor(Color.red); graphics.drawRect(10, 10, 100, x); } } Figure 9.6: A white circle drawn with a blue outline What about a circle? Drawing a circle is ever so easy? It is the same process as the syntax above only that the word Rect is changed to the word Oval. And don't ask me why oval? You simply don't have the JAVA PROGRAMMING NASC –IT method drawCircle(int,int,int,int) as you don't have drawSquare(int,int,int,int). Following is the application of Graphics code to draw a circle just to whet your appetite. Listing 9.8: Drawing a white circle with a blue outline public class MyCanvas extends Canvas { public void paint(Graphics graphics) { graphics.setColor(Color.white); graphics.fillOval(10, 10, 100, 100); graphics.setColor(Color.blue); graphics.drawOval(10, 10, 100, 100); } } A new form of a rectangle JAVA PROGRAMMING NASC –IT Figure 9.7: A pink rounded rectangle with a red outline. Amazing! Simple so far, isn't it? Of all the shapes out there, these two are the only shapes that you'd need to build for the moment. Complex graphics routines are required to build shapes like a rhombus, triangle, trapezium or a parallelogram. We would be tackling them later on in another section. However, on a last note I would leave you with another interesting shape - a combination of both ovals and rectangle. Think a rectangle with rounded corners, a Rounded Rectangle (RoundRect). Listing 9.9: Drawing a pink rounded retangle with a red outline public class MyCanvas extends Canvas { public void paint(Graphics graphics) { graphics.setColor(Color.pink); graphics.fillRoundRect(10, 10, 100, 100, 5, 5); JAVA PROGRAMMING NASC –IT graphics.setColor(Color.red); graphics.drawRoundRect(10, 10, 100, 100, 5, 5); } } Notice that the syntax of the drawRoundRect(int,int,int,int,int,int) method is a bit different than the syntax for the simple rectangle drawing routine drawRect(int,int,int,int). The two new arguments added at the end are the width of the arc in pixels and the height of the arc in pixels. The result is pretty amazing when you run the program. You don't need to squint your eyes to tell that the corners of the rectangle are slightly rounded. The more the values of the width and height of the arcs, the more roundness appears to form around the corner. [edit] Hmm, everything's perfect, but... Sometimes people ask, after creating simple programs like the ones above, questions like: • Why did I have to tell the Graphics instance the color before each drawing routine? Why can't it remember my choice for the outlines and for the fill colors? The answer is simpler than it seems. But, to fully understand it, we need to focus on one little thing called the Graphics Context. The graphics context is the information that adheres to a single instance of the Graphics class. Such an instance remembers only one color at a time and that is why we need to make sure the context knows of the color we need to use by using the setColor(Color) method. • Can I manipulate the shapes, like tilt them and crop them? Hold your horses, cowboy! Everything is possible in Java, even tilting and cropping drawings. We will be focusing on these issues in a later section. • Is making shapes like triangles, rhombuses and other complex ones tedious? Well, to be honest here, you need to go back to your dusty book cabinet and take out that High School Geometry book because we would be covering some geometry basics while dealing with such shapes. Why not read a wikibook on Geometry? [edit] What has eyes that pop out? A happy Java noob after this section, perhaps! Now that we have covered the drawing of basic shapes, let's see how much you were paying attention to the content. Try answering these questions below. Answers will be revealed in the next section. Question 9.3: Throughout the exercise listings above, we have been filling the shapes first and then drawing their outlines. What happens if we do it the other way around? Consider the code below. JAVA PROGRAMMING NASC –IT ... public void paint(Graphics graphics) { graphics.setColor(Color.red); graphics.drawRect(10, 10, 100, 100); graphics.setColor(Color.yellow); graphics.fillRect(10, 10, 100, 100); } 1. The left and the top outlines disappear. 2. The right and the bottom outlines disappear. 3. The color for the outline becomes the color for the fill area. 4. All the outlines disappear.