Introduction to Java Programming: a Stroll Through Java A Stroll through Java Nancy McCracken NPAC Syracuse University 111 College Place Syracuse NY 13244-4100 March 6, 1996 Click here for body text A Stroll through Java Java is an object-oriented language based on C++ suitable for general distributed applications programming. In this course, we will concentrate on Java applets to program application interfaces on the World Wide Web. These lecture slides on programming in Java will show a series of small programming examples, designed to illustrate the main features of the language. They accompany the Java Course Module, by Geoffrey Fox, which covers more details about the language. Text: "Teach yourself Java in 21 days", by Laura Lemay and Charles L. Perkins, February 1996, Sams.net Publishing. The Simplest Java Application: Hello, World! Since Java is object-oriented, programs are organized into modules called classes, which may have data in variables and functions called methods. The Simplest Java Applet: Hello, World! Java applets are part of the class hierarchy that can call methods to display on a screen (within the browser window). This example defines the public method paint in this class and calls a method drawString defined in the class Graphics. Displaying your applet from a Web page. You should name the file with your applet name, HelloWorldApplet.java, run the compiler (javac), getting a bytecode file HelloWorldApplet.class, which you put in a web directory. The Graphics class An object of the graphics class represent a rectangular drawing grid, with a coordinate system in pixels. When you draw objects, there is a current "state" consisting of a font and a color. Using Graphics properties Fonts and colors are objects (sometimes called instances) of the font and color class in the awt package. Passing parameters to an applet: the HTML Within the applet tags, any number of param tags may occur. Attributes can control the alignment of the applet window on the html page. Passing parameters to an applet: the applet A standard method, init(), is executed when your applet is loaded; it can call the method getParameter. Drawing simple shapes Methods are available for drawing lines, rectangles, rounded rectangles, ovals, arcs, and polygons. This example draws a rectangle filled with green with a black border, and a circle filled with magenta. Centering a string in the applet window. The method applet.size() returns the width and height as a dimension object, which has width and height variables. FontMetrics has variables for various attributes of the font, including width and height. Random color boxes example This example fills the applet's drawing area with square boxes, each of which has a randomly chosen color. Arrays of random colors This demonstrates 2-dimensional arrays by first filling arrays with random colors, and then drawing, uses a fixed size drawing window for simplicity. Applet Flow of Control Each applet's flow of control goes through a sequence of standard methods: public void init() { . . . } executed once when applet is downloaded to the browser. public void start(){ . . . } executed each time the browser window is entered. public void paint(){ . . . } executed whenever you want to draw in the window. public void stop(){ . . . } executed each time the browser window in exited. public void destroy(){ . . . } executed just before the applet exits. See ColorBoxes examples with init and start. Threads A thread is a single sequential flow of control within a process. If a process has more than one thread, then each thread executes concurrently. Any Java applet which has extensive execution or loops to repaint the window must run as a concurrent thread with the browser window. To make an applet with a thread, which is almost always recommended: Change your applet definition to add "implements Runnable", the interface for threads. Include an instance variable for the thread of your applet. Have a start() method which creates a thread and starts it running and a stop() method which stops it running. Have a run() method containing the body of your applet code. Example showing the standard thread methods These start and stop methods can always be used Example showing thread methods, continued The body of the applet is in the run method, in this case a loop to keep showing the date. Object-Oriented Programming in JAVA - defining a class We define a parent class for movable point objects. Each instance of this class is represented by an x,y location, by a dx,dy offset for the object to move, and a color for the object. More methods in the class definition We include methods to change the default values for the offsets and color, a method to move the object, and one to paint a point. Defining a child class We define a class for movable rectangle objects. It uses x,y from the parent class mPoint for the location of the rectangle, but adds h,w to specify height and width of the rectangle. Using parent and child classes This applet creates 2 mRectangles and loops to move them. Parent and child example, continued The repaint method calls update, which is overridden here to move the objects, and paint, which is overridden here to redraw whole graphics area. Overloading Constructors You are allowed to have more than one constructor in a class, if they constructors have different types or numbers of arguments. For example, for people who are using the java.awt.Point class, you can add a constructor to mRectangle which creates a rectangle by giving the top left and bottom right corner points. More child classes Once we have structured the concepts of our data into classes, it is easy to add new shapes of movable objects as child classes of mRectangle. These classes only have to redefine paint to draw a differently shaped object. The Class Hierarchy of this example Getting Images The Applet class provides a method getImage, which retrieves an image from a web server and creates an instance of the Image class. Image img = getImage(new URL("http://www.tc.com/image.gif")); Another form of getImage retrieves the image file relative to the directory of the HTML or the directory of the java code. Image img = getImage(getDocumentBase(), "images/image.gif"); Image img = getImage(getCodeBase(), "images/image.gif"); Drawing Images The Graphics class provides a method drawImage to actually display the image on the browser screen. You can also scale the image to a particular width and height. An Image Drawing Example This example shows how to get the actual height and width of the image to use in scaling the image under java program control. Double Buffering This technique is most effective in eliminating flicker, but does take longer and use more memory. Using Mouse Events for User Interaction We set up a test program that creates 3 movable objects, a rectangle, circle and triangle, as in the earlier example. In this program, we start with them all red. Whenever the mouse is detected to be over one of the objects, it's color is changed to cyan. If the mouse button is used to drag the object, we move the object to the mouse location. Note that it is not necessary to introduce a thread for this applet since it is not running continuously - it is mostly waiting for mouse events. Mouse Events: Initializing the movable objects Mouse Move Event Whenever the user moves the mouse, a message is sent to from the client workstation to the Java system. It generates a form of interrupt called an event. Your Java applet can choose to provide a method which does appropriate response for any event. This is called an event handler - you must return true to show the general event handler that you have intervened. The Set of Mouse Dragging Events These handle the sequence of the user clicks the mouse (mouse down), moves the mouse (mouse drag) and releases the mouse button (mouse up). More Methods in the Movable Point class We add methods to detect when the mouse is inside an object, and a more general method moveTo for large moves under dragging. Keyboard Events You may also choose to respond to individual keys being pressed from the keyboard. (Later we will learn of a more general way to handle text input.) AWT - Grid Layout with Two Components A simple example of using the Abstract Windowing Toolkit divides the applet space into two components. One is a Canvas for drawing graphics or images; one is a Panel which has three buttons. We choose to draw the Canvas within the Applet and to create the Panel in another class. AWT - Adding Components to a Layout AWT - Canvas Component The initialization of the Canvas was done in the applet init method; the other method for painting the Canvas simply changes the background color. About the only thing a Canvas can do is explicit drawing and graphics. AWT - Panel Component with Buttons This class does not need to be a subclass of Applet - like all components except Canvas, you don't need to paint, just add components and handle events and actions. AWT - Handling Actions from Components The Button component generates an action whenever the button is clicked on. In this example, we call the method that changes the color of the Canvas in another part of the layout. Designing an AWT User Interface - the Pizza Order example We design a Java applet to provide a more interactive interface to our Pizza Order CGI script. We start by laying out the web page in which people either select a special or choose toppings. Pizza Order: GUI Components We design a set of classes to hold the components of the graphical user interface. The top level page consists of three panels, where the second is the first page of a card layout, with a specials page and a toppings page. Pizza Order: the Specials Component The constructor of this component reads the specials file on the server and displays the contents here. Pizza Order: the Toppings Component and Graphics Canvas Users may drag toppings onto the pizza area to select them. Unlike our HTML form, we allow users to select multiple toppings (and yes, we'll have to change our pizza2.pl CGI script a little bit to allow that). Pizza Order: the Class Hierarchy Pizza Order: the Calling Hierarchy The main function of the pizza order applet is to fill in values for the variables in the order component: address, phoneno. and pizzatype. The instance of the order component class is constructed by the top page, so it is passed to the other constructors so that they have access to the variables and methods of ordercomp.