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 –BCA : JAVA PROGRAMMING : III BCA : IV : 5 : S.SAVITHA & N.P.SHIJU UNIT-IV: Managing Errors and Exceptions – Applet Programming – Graphics Programming. PART A 1. An exception is an abnormal condition that arises in a code sequence at runtime. 2.A try statement can be inside another try block. 3. JDK 1.1 extends this tight security with digitally signed applet using jar file. 4. The swing components in Java Foundation Classes (JFC) is the new package in JDK1.1 and JDK1.2. 5. A Java program is created as a text file with .java extension. PART B 1.Note on 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 ; JAVA PROGRAMMING NASC –BCA }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. 2. How 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. 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 PROGRAMMING NASC –BCA PART C 1. Explain 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 Throwable JAVA PROGRAMMING Error NASC –BCA 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. 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”); } JAVA PROGRAMMING NASC –BCA } The output of the program Division by zero After catch. 2.Describe 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: • 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 JAVA PROGRAMMING BarChart Animator JumpingBox NASC –BCA 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. • 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. JAVA PROGRAMMING 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. NASC –BCA 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 JAVA PROGRAMMING NASC –BCA 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 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, 2.Explain 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: JAVA PROGRAMMING NASC –BCA • 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. 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); } JAVA PROGRAMMING NASC –BCA 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); 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. Drawing basic shapes Introduction to Graphics JAVA PROGRAMMING NASC –BCA 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) { /* 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(); JAVA PROGRAMMING NASC –BCA 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 –BCA 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 –BCA 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 –BCA 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 –BCA 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 –BCA 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 –BCA { 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 –BCA 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 –BCA 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 –BCA 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 –BCA ... 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.