<<

Lecture 4 Applets

HTML:

Hypertext Markup Language lays out the syntax for web pages. The relevant parts for our purposes are shown below:

// start tag for document // Introduces the Head section Hi // Title that will appear on title bar // end of head section // start of body section


// Horizontal line // initial window height // end of applet definition
The source. // declares a link // end of body section // end of html document

Here's the code for the Java image in the syllabus:

// the param parameter passes a value to a variable in the applet Applets:

Some additional applet parameters for the applet tag in HTML are:

CODEBASE This url specifies the base url of the applet, the default is the html document's url.

ALT Text the browser can display IF it can't run the applet - but understands the applet tag.

ALIGN Gives the alignment of the applet. Possible values are: BASELINE, CENTER, LEFT, MIDDLE, RIGHT, TEXTBOTTOM, TEXTMIDDLE, TEXTTOP.

VSPACE Specifies the number of pixels above and below the applet.

HSPACE Specifies the number of pixels on each side of the applet.

Here's the class hierarchy that pertains to applets:

java.lang.Object java.awt.Component java.awt.Container java.awt.Panel java.applet.Applet

AWT means the Abstract Windows Toolkit which we will investigate later. Event Oriented:

Java applets are event oriented. We'll see mouse and keyboard events later.

Key events in an applets life:

Loading the Applet:

1. An instance of the applet's controlling class is created (this is a subclass of Applet).

2. The applet initializes itself.

3. The applet starts running.

Reloading the Applet:

This occurs when the window is minimized (iconified) or goes to another page. The applet can (has the option) of stopping itself. If it stops it must restart, with the steps shown above in loading an applet.

Quitting the Applet:

The applet has a chance of stopping itself and doing final cleanup.

And the Member methods:

init Initializes the applet each time it is opened (loaded or reloaded). This is called after the constructor. This method is called by the browser or applet viewer to inform this applet that it has been loaded into the system. It is always called before the first time the start method is called. A subclass of Applet should override this method if it has initialization to perform. For example, an applet with threads would use the init method to create the threads and the destroy method to kill them.

start This method is called by the browser or applet viewer to inform this applet that it should start its execution. It is called after the init method and each time the applet is revisited in a Web page. A subclass of Applet should override this method if it has any operation that it wants to perform each time the Web page containing it is visited. For example, an applet with animation might want to use the start method to resume animation, and the stop method to suspend the animation.

stop This method is called by the browser or applet viewer to inform this applet that it should stop its execution. It is called when the Web page that contains this applet has been replaced by another page and also just before the applet is to be destroyed. A subclass of Applet should override this method if it has any operation that it wants to perform each time the Web page containing it is no longer visible. For example, an applet with animation might want to use the start method to resume animation, and the stop method to suspend the animation.

destroy This method is called by the browser or applet viewer to inform thisapplet that it is being reclaimed and that it should destroy any resources that it has allocated. The stop method will always be called before destroy. A subclass of Applet should override this method if it has any operation that it wants to perform before it is destroyed. For example, an applet with threads would use the init method to create the threads and the destroy method to kill them.

paint Paints this component. Most application components, including applets, override this method. The paint method of Component calls the repaint method of this component's peer. .

repaint schedules a call to component’s update method asap.

update is responsible for redrawing the component. The default redraws the background and then calls paint.

Here's an example: import java.applet.Applet; import java.awt.Graphics; public class Hi extends Applet {

private int m_nInitCnt; private int m_nStartCnt; private int m_nStopCnt; private int m_nDestroyCnt; private int m_nPaintCnt;

public Hi() { m_nInitCnt = 0; m_nStartCnt = 0; m_nStopCnt = 0; m_nDestroyCnt = 0; m_nPaintCnt = 0; }

public void init() { resize(320, 240); m_nInitCnt++; }

public void start() { m_nStartCnt++; }

public void stop() { m_nStopCnt++; }

public void destroy() { m_nDestroyCnt++; }

public void paint(Graphics g) { g.drawString("Init count = " + m_nInitCnt, 0, 20); g.drawString("Start count = " + m_nStartCnt, 0, 30); g.drawString("Stop count = " + m_nStopCnt, 0, 40); g.drawString("Destroy count = " + m_nDestroyCnt, 0, 50); g.drawString("Paint count = " + ++m_nPaintCnt, 0, 60); } } Painting and Graphics:

paint is a member of the Component class. It has a signature of

public void paint(Graphics g)

Paints this component. For example, a string would NOT be painted with println but with drawString. Most application components, including applets, override this method. The paint method of Component calls the repaint method of this component's peer. The (0, 0) coordinate of the graphics context is the top-left corner of this component. This is the MM_TEXT mapping mode of C++ Windows programming. The clipping region of the graphics context is the bounding rectangle of this component.

Positive x value are to the right. The y offset has positive values going down.

Parameters:

g - the graphics context to use for painting

The Graphics class is the abstract base class for all graphics contexts which allow an application to draw onto components or onto off-screen images.

public abstract class java.awt.Graphics extends java.lang.Object { // Constructors protected Graphics()

// Methods public abstract void clearRect(int x, int y, int width, int height); public abstract void clipRect(int x, int y, int width, int height); public abstract void copyArea(int x, int y, int width, int height, int dx, int dy); public abstract Graphics create(); public Graphics create(int x, int y, int width, int height); public abstract void dispose(); public void draw3DRect(int x, int y, int width, int height, boolean raised); public abstract voiddrawArc(int x, int y, int width, int height, int startAngle, int arcAngle); public void drawBytes(byte data[], int offset, int length, int x, int y); public void drawChars(char data[], int offset, int length, int x, int y); public abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer); public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer); public abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer); public abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer); public abstract void drawLine(int x1, int y1, int x2, int y2); public abstract void drawOval(int x, int y, int width, int height); public abstract void drawPolygon(int xPoints[], int yPoints[], int nPoints); public void drawPolygon(Polygon p); public void drawRect(int x, int y, int width, int height); public abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight); public abstract void drawString(String str, int x, int y); public void fill3DRect(int x, int y, int width, int height, boolean raised); public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle); public abstract void fillOval(int x, int y, int width, int height); public abstract void fillPolygon(int xPoints[], int yPoints[], int nPoints); public void fillPolygon(Polygon p); public abstract void fillRect(int x, int y, int width, int height); public abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight); public void finalize(); public abstract Rectangle getClipRect(); public abstract Color getColor(); public abstract Font getFont(); public FontMetrics getFontMetrics(); public abstract FontMetrics getFontMetrics(Font f); public abstract void setColor(Color c); public abstract void setFont(Font font); public abstract void setPaintMode(); public abstract void setXORMode(Color c1); public String toString(); public abstract void translate(int x, int y); } An Event Application:

An Event object has the following:

public Object arg; // optional additional argument public int clickCount; // number of times in a row that mouse was pressed public Event evt; // the next event (for a linked list) public int id; // the event type (see below) public int key; // the key that was pressed public int modifiers; // Modifier state (like shift, control and alt) public Object target; //object on which the event occurred (like a window) public long when; // time when event occurred public int x; // x coordinate (for mouse event) public int y; // y coordinate (for mouse event)

// possible values for the id field public final static int ACTION_EVENT; public final static int GOT_FOCUS; public final static int KEY_ACTION; public final static int KEY_ACTION_RELEASE; public final static int KEY_PRESS; public final static int KEY_RELEASE; public final static int LIST_DESELECT; public final static int LIST_SELECT; public final static int LOAD_FILE; public final static int LOST_FOCUS; public final static int MOUSE_DOWN; public final static int MOUSE_DRAG; public final static int MOUSE_ENTER; public final static int MOUSE_EXIT; public final static int MOUSE_MOVE; public final static int MOUSE_UP; public final static int SAVE_FILE; public final static int SCROLL_ABSOLUTE; public final static int SCROLL_LINE_DOWN; public final static int SCROLL_LINE_UP; public final static int SCROLL_PAGE_DOWN; public final static int SCROLL_PAGE_UP; public final static int WINDOW_DEICONIFY; public final static int WINDOW_DESTROY; public final static int WINDOW_EXPOSE; public final static int WINDOW_ICONIFY; public final static int WINDOW_MOVED;

// possible values for the key field when the // action is KEY_ACTION or KEY_ACTION_RELEASE public final static int DOWN; public final static int END; public final static int F1; public final static int F2; public final static int F3; public final static int F4; public final static int F5; public final static int F6; public final static int F7; public final static int F8; public final static int F9; public final static int F10; public final static int F11; public final static int F12; public final static int HOME; public final static int LEFT; public final static int PGDN; public final static int PGUP; public final static int RIGHT; public final static int UP;

// possible masks for the modifiers field public final static int ALT_MASK public final static int CTRL_MASK; public final static int META_MASK; public final static int SHIFT_MASK; Connect the Dots:

Use AppletWizard to generate a LineDraw applet. Use single-threaded. In Step 3 select mouseDrag/mouseMove and mouseDown/mouseUp.

//**************************************************************** // LineDraw.java: Applet //**************************************************************** import java.applet.*; import java.awt.*;

//======// Main Class for applet LineDraw // //======public class LineDraw extends Applet { // Dimension is a class that encapsulates the width and height // of a component in a single object static final intm_nMAXLOCS = 100; // max number of locations Dimension m_dimLocs[]; // save the locations int m_nNumMouseClicks; // # clicks Dimension m_dimCursorLoc; // current cursor location

// LineDraw Class Constructor //------public LineDraw() { // TODO: Add constructor code here m_dimLocs = new Dimension[m_nMAXLOCS]; m_nNumMouseClicks = 0; m_dimCursorLoc = new Dimension( 0, 0); }

public String getAppletInfo() { return "Name: LineDraw\r\n" + "Author: Gary J. Koehler\r\n" + "An Example"; }

public void init() { resize(320, 240);

// TODO: Place additional initialization code here } public void destroy() { // TODO: Place applet cleanup code here } public void start() { // TODO: Place additional applet start code here } public void stop() { } public void paint(Graphics g) { // put a cross where cursor is located int nX = m_dimCursorLoc.width; int nY = m_dimCursorLoc.height; g.drawLine( nX-2, nY, nX+2, nY); g.drawLine(nX,nY-2, nX, nY+2);

// draw a line from each clicked location // to every other for(int i=0;i< m_nNumMouseClicks-1;i++) { for(int j=i+1;j

// MOUSE SUPPORT: // The mouseDown() method is called if the mouse is pressed // while the mouse cursor is over the applet's portion of the screen. //------public boolean mouseDown(Event evt, int x, int y) { // We'll use multiple clicks to clear the screen if ( evt.clickCount > 1 ) m_nNumMouseClicks = 0; else { // Need to save the location - if enough room if ( m_nNumMouseClicks < m_nMAXLOCS) m_dimLocs[m_nNumMouseClicks++] = new Dimension(x,y); } repaint(); return true; }

// MOUSE SUPPORT: // The mouseUp() method is called if the mouse button is released // while the mouse cursor is over the applet's portion of the screen. //------public boolean mouseUp(Event evt, int x, int y) { // just ignore return true; }

// MOUSE SUPPORT: // The mouseDrag() method is called if the mouse cursor moves over the // applet's portion of the screen while the mouse button is held down. //------public boolean mouseDrag(Event evt, int x, int y) { // just ignore return true; }

// MOUSE SUPPORT: // The mouseMove() method is called if the mouse cursor moves over the // applet's portion of the screen and the mouse button isn't held down. //------public boolean mouseMove(Event evt, int x, int y) { // record the mouse location and repaint it m_dimCursorLoc = new Dimension(x, y); repaint(); return true; } } Speeding Things Up:

repaint() Repaints this component. This method causes a call to this component's update method as soon as possible.

update() Clears this component by filling it with the background color. Sets the color of the graphics context to be the foreground color of this component. Calls this component's paint method to completely redraw this component.

So, repaint is repainting the entire window whenever anything changes. Let's only redraw the part that changes.

In our LineDraw application, we could compute the smallest rectangle needed to be redrawn and then call repaint(int, int, int, int) with the rectangle.