Lecture 4: Applets and AWT

Download Report

Transcript Lecture 4: Applets and AWT

Java
For Computational Finance
Applets and the AWT
Jeff Stephenson
(slides adapted from Manu Kumar)
Java


Applets?
Applets are Java programs which can run within your
web browser
Applets vs. Applications
– Applets



run in the web browser
subject to security restrictions
do not have a main()
– Applications




full fledged Java programs
run from commandline
no security restrictions
So far we’ve built applications
– for good reason too since we’ll need what we’ve learnt!
Java

Applet Sandbox
Applets Vs. Application
– Applet: runs in Web browser.
– Application: runs in any Java VM.

Applet restrictions (http://www.javasoft.com/sfaq)
– no access to Client’s file System



cannot check for existence, read, write, or rename a file
cannot create or list the contents of a directory
cannot check a file’s type, timestamp or size.
– Network connection ONLY to originating host


cannot connect to arbitrary servers / sites across the net
key issue when designing client-server applets
Java
Architecture in light of Sandbox
An overly simplified description :
Applet
WWW
DB
The Web server machine must
act as the proxy for all calls
to services on other machines
Java

Displaying applets in the browser
To add a Java applet to your HTML page
– use <APPLET> </APPLET tag



Full Syntax:
<APPLET CODE="..." WIDTH="..." HEIGHT="...”
[CODEBASE="..."
ALT="..." NAME="...” ALIGN=left | right | top
VSPACE="..." HSPACE="...” ]>
[<PARAM NAME="..." VALUE="...">]
[Text for non-Java supporting browsers]
</APPLET >
Browsers treatment of an applet tag
– Java enabled browser will load applet
– non-Java enabled browser will ignore <APPLET>

it will display Text for non-Java supporting browsers
Java


JavaPhysical Example
Place compiled Applet classes in directory under web
server
Include <APPLET> tag in HTML file
– <APPLET CODEBASE="OtherClasses"
CODE="JavaEnabled.class" WIDTH=375 HEIGHT=46>
<H2 ALIGN=CENTER>Your Browser is NOT Java
Enabled!</H2>
</APPLET>

Load up page in Java enabled browser!
Java

Applet Class
Applets inherit from java.applet.Applet
– provides basic structure for applet to run in a browser

What you must/should override
– default constructor, init(), start(), stop(), destroy()

For a threaded applet
– implement Runnable interface
– override run()

For graphics
– may override repaint(), update() and paint()
Java

Browser loads HTML page
–
–
–
–

Applet Lifecycle
Find <APPLET> tag
Locates code using codebase
Downloads .class files to browser
Browser verifies .class files for security
Applet methods executed AUTOMATICALLY in this
order:
–
–
–
–
–
init()
start()
leaving the page calls stop()
returning to the page calls start() again
exiting the browser or leaving the page permanently calls
destroy()
Java
HelloWorldApplet
import java.awt.*;
import java.applet.*;
public class HelloWorld extends Applet {
public void init() {
resize (150, 25);
}
public void paint(Graphics g) {
g.drawString("Hello World!", 50, 25);
}
}
Java

Applets in the Real World
To make applets more functional
– May need a complicated interface
– Must respond to events
– Do something useful

Applet uses
–
–
–
–
Make information and functionality available via browser!
No download necessary
Works automatically
Browser becomes the “platform”
Java
Handling Events

Sribble Applet

public boolean mouseDown(Event e, int x, int y) {
lastX = x;
lastY = y;
return true;
}

public boolean mouseDrag(Event e, int x, int y) {
Graphics g = getGraphics();
g.drawLine(lastX, lastY, x, y);
lastX = x;
lastY = y;
return true;
}
Java

Scribble Applet CodeWalk
Notice the two methods:
– mouseDown
– mouseDrag

These get call automatically when any mouse event
occurs
– all we need to do is override them and take the appropriate
action

If we run the applet
– we can draw anything we like with the mouse!
Java

Making applet functional
Requires:
– may more graphical components




buttons
labels
checkboxes
text fields etc.
– handling events other than mouse events





click on button
check a checkbox
doubleclick in a list
type in a text box etc.
To do this we’ll need the AWT!!!
Java

AWT
AWT
– Abstract Windowing Toolkit
– Awkward Windowing Toolkit ?!?

Java’s library for graphical elements
– Makes EXTENSIVE use of inheritance and OO techniques!

That’s why you needed to learn them before we got to Applets
– Hierarchical approach to developing “Components”

you’ll see when we look at the API
– The AWT is platform independent


gives you the same components and “widgets” on all platforms!
Allows you to write code for the Java-platform as opposed to
Windows or Mac or UNIX
Java

AWT Classes
The two MAIN classes in the AWT are
– Component
– Container

Component
– nearly all the “widgets” in the AWT inherit from Component


it inherits attributes and behavior from Component
Container
– a placeholder
– a Container can “contain” other Components
– a Container is a Component

I.e. a Container can contain another Container
Java


Layout Managers
AWT uses the concept of “Layout Managers” to define
the user interface
Layout Managers
– tell the AWT where to position a component or a container
– tell the AWT what to do when we resize the application/applet!


Dynamic resizing
Layout Managers specify everything using “relationships”
– There are lots of layout managers, we’ll look at a few…


GridLayout
BorderLayout
Java

Handling Events
Two approaches to handling events
– we saw one approach earlier

overriding specific event handler methods such as mouseDown,
mouseDrag etc.
– today we will see the better approach

using Listners
Java











Frame
Panel
Canvas
Button
Checkbox
Choice
Label
List
ScrollBar
TextArea
TextField
AWT Widgets
Java

AWT development process
Steps:
– Create a Container

–
–
–
–

An applet extends Panel and is therefore already a Container
Set the layout manager
Instantiate the components
Add the components to the container using the layout manager
Call show() to actually draw the components on the screen
Tricks:
– Remember the containers can be NESTED

VERY USEFUL TRICK!
– Use multiple nested layouts for complex user interfaces
Java

LayoutManagers
We’ll only look at two today
– BorderLayout

Provide North, South, East, West and Center regions
– GridLayout


Divides the container into equally spaced rows and columns
Lets see some working Demos and explanations!!
– Off to the Java Tutorial from here…
– http://www.javasoft.com/docs/books/tutorial/ui/layout/using.html
Java

Nesting in AWT
Key Concept:
– A Container is also a Component


in most cases we care about for this class
Example Problem
– Say we wish to create the
layout shown on the right
– Characteristics:



Button Bar on the left
TextField at the bottom
TextArea in the rest
– Note:

buttons are equally spaced
Java

Nesting in AWT (2)
Process
– Layout the design you want on paper or a whiteboard!
– Analyze the design to see what sections you can identify


Buttons on the left can be one possible piece
TextArea and TextField are the other two pieces
– Work from top to bottom

identify a suitable layout for the big pieces identified above
– BorderLayout (surprise!)
• Buttons in the West
• TextField in the South
• TextArea in the North

But what about the “Buttons”
– GridLayout for the buttons!
• Here is where we’ll use nesting
Java

Sample Solution
– (see ButtonPad.java):
// set the top level layout
setLayout(new BorderLayout(3,3));
// create the text area
notesArea = new WrappedTextArea(10, 30);
notesArea.setEditable(false);
// add the text area
add("Center", notesArea);
// create the text field
entryField = new TextField(40);
// add the entry field
add("South", entryField);
Nesting in AWT (3)
// create a NEW PANEL for NESTING!
Panel buttonPanel = new Panel();
//set the layout in this panel
buttonPanel.setLayout(new GridLayout(0, 1, 5, 5));
//create and add the buttons
button1 = new Button("Button 1");
button2 = new Button("Button 2");
button3 = new Button("Button 3");
button4 = new Button("Button 4");
button5 = new Button("Button 5");
buttonPanel.add(button1);
buttonPanel.add(button2);
buttonPanel.add(button3);
buttonPanel.add(button4);
buttonPanel.add(button5);
//add the panel to the west of the main BorderLayout
add("West", buttonPanel);
Java

Handling Events
Two approaches to handling events
– we saw one approach earlier

overriding specific event handler methods such as mouseDown,
mouseDrag etc.
– today we will see the better approach

using Listners
Java

Handling Events
Types of events:
– ACTION_EVENT, LIST_SELECT, LIST_DESELECT,
WINDOW_DESTROY, WINDOW_ICONIFY,
WINDOW_DEICONIFY, WINDOW_MOVED, MOUSE_DOWN,
MOUSE_UP, MOUSE_DRAG, KEY_PRESS, KEY_ACTION,
KEY_RELEASE, KEY_ACTION_RELEASE, GOT_FOCUS,
LOST_FOCUS, MOUSE_ENTER, MOUSE_EXIT,
MOUSE_MOVE

All can be handled with special listners
– We’ll use a MouseListner as an example

OR you can override the methods corresponding to
each event
– what we saw in the Scribble applet
Java
Handling Events (2)
public class MouseEventDemo ... implements MouseListener
{
...//where initialization occurs:
//Register for mouse events on blankArea and applet (panel).
blankArea.addMouseListener(this);
addMouseListener(this);
...
Java

Handling Events (3)
Continued …..
public void mousePressed(MouseEvent e)
{
saySomething("Mouse pressed; # of clicks: " + e.getClickCount(), e);
}
public void mouseReleased(MouseEvent e)
{
saySomething("Mouse released; # of clicks: " + e.getClickCount(), e);
}
public void mouseEntered(MouseEvent e)
{
saySomething("Mouse entered", e);
}
……..
}