chapter 9: applets jim burns fall 2011. outline learn about applets learn about applets write an...

57
Chapter 9: Chapter 9: Applets Applets Jim Burns Jim Burns Fall 2011 Fall 2011

Upload: cori-griffith

Post on 26-Dec-2015

224 views

Category:

Documents


2 download

TRANSCRIPT

Chapter 9: AppletsChapter 9: Applets

Jim BurnsJim Burns

Fall 2011Fall 2011

OutlineOutline

Learn about appletsLearn about applets Write an HTML doc to host an appletWrite an HTML doc to host an applet Understand where applets fit in the class Understand where applets fit in the class

hierarchyhierarchy Create a Japplet containing an init() Create a Japplet containing an init()

methodmethod Change a Jlabel’s fontChange a Jlabel’s font Add JTextField and JButton components Add JTextField and JButton components

to a JAppletto a JApplet

OutlineOutline

Introducing AppletsIntroducing Applets

Apps are stand-alone applications that Apps are stand-alone applications that occasionally get compiled and linked occasionally get compiled and linked into machine code, frequently into machine code, frequently compiled into bytecodescompiled into bytecodes

Applets are Java programs that get Applets are Java programs that get interpreted by a Java bytecode interpreted by a Java bytecode interpreter interpreter

Applets run under the control of a Applets run under the control of a larger program, such as a web pagelarger program, such as a web page

AppletsApplets

Displayed as a rectangular areaDisplayed as a rectangular area Contains any number of components, Contains any number of components,

such as buttons, text fields, pictures, such as buttons, text fields, pictures, etc.etc.

Can respond to user-initiated events, Can respond to user-initiated events, such as mouse clicks or keyboard such as mouse clicks or keyboard pressespresses

Many of an applet’s behaviors come Many of an applet’s behaviors come from a Java class named JAppletfrom a Java class named JApplet

Writing an applet requires five Writing an applet requires five major steps:major steps:

Setting up a layout for the appletSetting up a layout for the applet Creating components and adding Creating components and adding

them to the appletthem to the applet Arranging for listeners to listen for Arranging for listeners to listen for

events generated by users who events generated by users who interact with the applet’s componentsinteract with the applet’s components

Writing methods to respond when the Writing methods to respond when the events occurevents occur

Writing a document to host the appletWriting a document to host the applet

Writing an HTML Document to Writing an HTML Document to Host an AppletHost an Applet

The applet is usually run within an The applet is usually run within an HTML document (i.e. a web page)HTML document (i.e. a web page)

The applet can also be run from The applet can also be run from within an applet viewerwithin an applet viewer

HTML (Hypertext Markup Language) HTML (Hypertext Markup Language) is a simple language for creating web is a simple language for creating web pagespages

When you create an applet, When you create an applet, you do the following…you do the following…

Write the applet in Java and save it with Write the applet in Java and save it with a .java file extension, just as when you a .java file extension, just as when you write a Java applicationwrite a Java application

Compile the applet into bytecode using Compile the applet into bytecode using the javoc command, just as when you the javoc command, just as when you write a Java applicationwrite a Java application

Write an HTML document that includes a Write an HTML document that includes a statement to call your compiled Java statement to call your compiled Java appletapplet

Load the HTML document into a Web Load the HTML document into a Web browser, or run the Applet Viewer browser, or run the Applet Viewer program, which in turn uses the HTML program, which in turn uses the HTML documentdocument

Writing HTMLWriting HTML

You need to learn only two pairs of You need to learn only two pairs of HTML commands, called tagsHTML commands, called tags

The tag that begins every HTML The tag that begins every HTML document is <html>document is <html>

The tag that ends every HTML The tag that ends every HTML document is </html>document is </html>

In between, you needIn between, you need <object code = “AClass.class” width <object code = “AClass.class” width

= 300 height = 200> </object>= 300 height = 200> </object>

The complete HTML docThe complete HTML doc

<html><html><object code = “AClass.class” width = <object code = “AClass.class” width =

400 height = 300> </object>400 height = 300> </object></html></html>

Here, width defines the width of the Here, width defines the width of the applet in pixels, while height defines applet in pixels, while height defines the height of the applet in pixelsthe height of the applet in pixels

400x300 is about ¼ of the total 400x300 is about ¼ of the total screen sizescreen size

Running an AppletRunning an Applet

Use the web browserUse the web browser Use the Applet ViewerUse the Applet Viewer The appletviewer command is part of The appletviewer command is part of

your SDKyour SDK Simply type appletviewer at the Simply type appletviewer at the

command line followed by the full command line followed by the full HTML filename.HTML filename.– When you press return the viewer window When you press return the viewer window

opens and displays the appletopens and displays the applet

Understanding where Applets Understanding where Applets fit in the Class Hierarchyfit in the Class Hierarchy

To write an applet, you must…To write an applet, you must…– Include necessary Include necessary importimport statements statements

Import javax.swing.JApplet;Import javax.swing.JApplet; JApplet is a swing class from which you can JApplet is a swing class from which you can

instantiate an appletinstantiate an applet Swing components are UI elements such as Swing components are UI elements such as

dialog boxes and buttonsdialog boxes and buttons

– Learn to use some new user interfaces, Learn to use some new user interfaces, such as buttons, text fields and applet such as buttons, text fields and applet methodsmethods

– Learn to use the keyword Learn to use the keyword extendsextends

The class hierarchyThe class hierarchy

Java.lang.ObjectJava.lang.Object– Java.awt.ComponentJava.awt.Component

Java.awt.ContainerJava.awt.Container–Java.awt.PanelJava.awt.Panel

Java.applet.AppletJava.applet.Applet Javax.swing.JappletJavax.swing.Japplet

From this hierarchy, we learn that From this hierarchy, we learn that every container is a component, but every container is a component, but not every component is a containernot every component is a container

The JLabel HierarchyThe JLabel Hierarchy

Java.lang.ObjectJava.lang.Object– Java.awt.ComponentJava.awt.Component

Java.awt.ContainerJava.awt.Container–Javax.swing.JComponentJavax.swing.JComponent

Javax.swing.JLabelJavax.swing.JLabel

Some ComponentsSome Components Labels – JLabel()Labels – JLabel()

– Writes text on the form Writes text on the form Textboxes –JTextFieldTextboxes –JTextField

– Places a textbox on the form (single line of Places a textbox on the form (single line of text)text)

– A textbox is a box the user can write text inA textbox is a box the user can write text in– This text can be captured and storedThis text can be captured and stored

Font – Font()Font – Font()– Allows you to adjust font (typeface), style Allows you to adjust font (typeface), style

and point size in a Jlabeland point size in a Jlabel Button – JButton()Button – JButton()

Available constructors for Available constructors for Jlabel classJlabel class

Jlabel() creates a Jlabel instance with no Jlabel() creates a Jlabel instance with no image and with an empty string for the image and with an empty string for the titletitle

Jlabel(Icon image) creates a Jlabel Jlabel(Icon image) creates a Jlabel instance with the specified imageinstance with the specified image

Jlabel(Icon image, int horizontalAlignment) Jlabel(Icon image, int horizontalAlignment) creates a Jlabel instance with the creates a Jlabel instance with the specified image and horizontal alignmentspecified image and horizontal alignment

Jlabel(String text) creates a Jlabel instance Jlabel(String text) creates a Jlabel instance with the specified textwith the specified text

import javax.swing.*;import javax.swing.*;

import java.awt.*;import java.awt.*;

Public class Jhello extends JappletPublic class Jhello extends Japplet

{{

Container con = getContentPane();Container con = getContentPane();

JLabel greeting = new Jlabel(“Hello. Who JLabel greeting = new Jlabel(“Hello. Who are you?”);are you?”);

public void init()public void init()

{{

con.add(greeting);con.add(greeting);

}}

}}

Creating a JApplet Containing Creating a JApplet Containing an init() methodan init() method

In applications your main method gets In applications your main method gets called by the system, and the main called by the system, and the main method calls other methodsmethod calls other methods

In applets, four methods are included In applets, four methods are included in every applet:in every applet:– public void init()public void init()– public void start()public void start()– public void stop()public void stop()– public void destroy()public void destroy()

No main method in a Java No main method in a Java AppletApplet

If you fail to provide an init(), a If you fail to provide an init(), a start(), a stop(), or a destroy()start(), a stop(), or a destroy()– Java creates them for youJava creates them for you– But Java-created methods are empty—But Java-created methods are empty—

you must put something into at least you must put something into at least one of themone of them

Changing a JLabel’s FontChanging a JLabel’s Font

YOU have to use a class called ‘Font’YOU have to use a class called ‘Font’ Font headlineFont = new Font headlineFont = new

Font(“helvetica”, font.BOLD, 36);Font(“helvetica”, font.BOLD, 36);

..

..

..

greeting.setFont(headlineFont);greeting.setFont(headlineFont);

import javax.swing.*;import javax.swing.*;

import java.awt.*;import java.awt.*;

Public class Jhello extends JappletPublic class Jhello extends Japplet

{ { Container con = getContentPane();Container con = getContentPane();

JLabel greeting = new Jlabel(“Hello. Who are JLabel greeting = new Jlabel(“Hello. Who are you?”);you?”);

Font headlineFont = new Font(“Helvetica”, Font headlineFont = new Font(“Helvetica”, Font.BOLD, 36);Font.BOLD, 36);

public void init()public void init()

{ { greeting.setFont(headlineFont);greeting.setFont(headlineFont);

con.add(greeting);con.add(greeting);

}}

}}

Adding JTextField and JButton Adding JTextField and JButton components to a JAppletcomponents to a JApplet

JTextField is a component into which a JTextField is a component into which a user can type a single line of text datauser can type a single line of text data

JTextField answer = new JTextField(10);JTextField answer = new JTextField(10);– Will display 10 charactersWill display 10 characters

To add the JTextField named answer to To add the JTextField named answer to the Container named con within the the Container named con within the JApplet, you write:JApplet, you write:

con.add(answer);con.add(answer);

JTextfield Constructors

public JTextField() – constructs a new JTextfield

public JTextField(int columns) constructs a new, empty JTextField with the specified number of columns

public JTextField(String text) constructs a new JTextField initialized by the specified text

public JTextField(String text, int columns) does it all

Other methods for use with JTextFields

setText() method allows you to change the text in a JTextField that has already been created, as in– answer.setText(“Thank you”);– Answer.setText(“”); -- clears out whatever

getText() method allows you to retrieve the String of text in a JTextField, as in– String whatDidTheySay = answer.getText();– answer.requestfocus(); causes the cursor to

appear in the JTextField—only one component can have focus at any given time

import javax.swing.*;import java.awt.*;import java.awt.event.*;public class JHello9 extends JApplet implements ActionListener{ JLabel greeting = new JLabel("Hello. Who are you?"); Font headlineFont = new Font("Helvetica", Font.BOLD, 36); JTextField answer = new JTextField(10); JButton pressMe = new JButton("Press me"); JLabel personalGreeting = new JLabel(""); Container con = getContentPane(); public void init() { greeting.setFont(headlineFont); personalGreeting.setFont(headlineFont); con.add(greeting); con.add(answer); con.add(pressMe); con.setLayout(new FlowLayout()); pressMe.addActionListener(this); answer.addActionListener(this); } public void actionPerformed(ActionEvent e) { remove(pressMe); remove(answer); String name = answer.getText(); personalGreeting.setText("Hello, " + name); con.add(personalGreeting); validate(); personalGreeting.setLocation(10,150); }}

Adding JButtonsAdding JButtons

JButton creates a button that the JButton creates a button that the user can click on to make a selectionuser can click on to make a selection—five constructors—five constructors– public JButton()public JButton()– public JButton(Icon icon)public JButton(Icon icon)– public JButton(String text)public JButton(String text)– public JButton(String text, Icon icon)public JButton(String text, Icon icon)– public JButton(Action a)public JButton(Action a)

To create a JButton with the label “Press when ready”, you write:

JButton readyJButton = new JButton(“Press when ready”);

To add the JButton TO A CONTAINER named con in an applet, you write:

Con.add(readyButton); To change a JButton’s label with the

setLabel() method, you usereadyJButton.setLabel(“Don’t press me

again!”);

Adding Multiple Components to Adding Multiple Components to a JAppleta JApplet

The following code places one The following code places one component on top of the other, component on top of the other, completely hiding itcompletely hiding it

In this case, the JTextField gets In this case, the JTextField gets placed on top of the JLabel, placed on top of the JLabel, completely obscuring itcompletely obscuring it

import javax.swing.*;import java.awt.*;public class JHello3 extends JApplet{ JLabel greeting = new JLabel("Hello. Who are

you?"); Font headlineFont = new Font("Helvetica",

Font.BOLD, 36); JTextField answer = new JTextField(10); public void init() { Container con = getContentPane(); greeting.setFont(headlineFont); con.add(greeting); con.add(answer); }}

The following code …

Does just the opposite, placing the JLabel on top of the JTextField

import javax.swing.*;import java.awt.*;public class JHello4 extends JApplet{ Container con = getContentPane(); JLabel greeting = new JLabel("Hello. Who are

you?"); Font headlineFont = new Font("Helvetica",

Font.BOLD, 36); JTextField answer = new JTextField(10); public void init() { greeting.setFont(headlineFont); con.add(answer); con.add(greeting); }}

To fix this, you must use a layout manager

Layout manager—a class that controls component positioning

This is in contrast to the use of the BorderLayout format

The BorderLayout class divides a container into five regions: north, east, south, west and center

The following code…

Uses the flowLayout() to control the ordering of the components

import javax.swing.*;import java.awt.*;public class JHello5 extends JApplet{ Container con = getContentPane(); JLabel greeting = new JLabel("Hello. Who are you?"); Font headlineFont = new Font("Helvetica", Font.BOLD, 36); JTextField answer = new JTextField(10); JButton pressMe = new JButton("Press me"); public void init() { greeting.setFont(headlineFont); con.add(greeting); con.add(answer); con.add(pressMe); con.setLayout(new FlowLayout()); }}

import javax.swing.*;import java.awt.*;public class JHello5 extends JApplet{ Container con = getContentPane(); JLabel greeting = new JLabel("Hello. Who are you?"); Font headlineFont = new Font("Helvetica", Font.BOLD, 36); JTextField answer = new JTextField(10); JButton pressMe = new JButton("Press me"); public void init() { greeting.setFont(headlineFont); con.add(greeting); con.add(answer); con.add(pressMe); con.setLayout(new FlowLayout()); }}

Learning about event-driven Learning about event-driven programmingprogramming

An An eventevent occurs when someone occurs when someone using your applet takes action on a using your applet takes action on a component, such as clicking the component, such as clicking the mouse on a JButton objectmouse on a JButton object

In an In an event-driven programevent-driven program, the user , the user has dozens of events to choose from has dozens of events to choose from in any given orderin any given order– Consider MS Word…Consider MS Word…

A component that a user can act on A component that a user can act on is a is a sourcesource of an event of an event

Sources…

A button that a user can click on A text field that a user can enter text

into A menu bar is another collection of

sources

Listeners

An object that is interested in an event is a listener

If you want an object, such as your applet, to be a listener for an event, you must register the object as a listener for the source

Listeners must have event-handling methods that respond to the events

To respond to user events

Prepare your JApplet to accept event messages

Tell your JApplet to expect events to happen

Tell your JApplet how to respond to events

Preparing your JApplet to Preparing your JApplet to Accept Event MessagesAccept Event Messages

You must add this import statementYou must add this import statement

Import java.awt.event.*;Import java.awt.event.*; Then you must change your class Then you must change your class

header as follows:header as follows:

Public class JHello6 extends JApplet Public class JHello6 extends JApplet implements ActionListenerimplements ActionListener

See the code belowSee the code below

import javax.swing.*;import java.awt.*;import java.awt.event.*;public class JHello6 extends JApplet implements ActionListener{ Container con = getContentPane(); JLabel greeting = new JLabel("Hello. Who are you?"); Font headlineFont = new Font("Helvetica", Font.BOLD, 36); JTextField answer = new JTextField(10); JButton pressMe = new JButton("Press me"); public void init() { greeting.setFont(headlineFont); con.add(greeting); con.add(answer); con.add(pressMe); con.setLayout(new FlowLayout()); pressMe.addActionListener(this); } public void actionPerformed(ActionEvent e) { String name = answer.getText(); System.out.println("You pressed the button, " + name); }}

import javax.swing.*;import java.awt.*;import java.awt.event.*;public class JHello6 extends JApplet

implements ActionListener{ Container con = getContentPane(); JLabel greeting = new JLabel("Hello. Who

are you?"); Font headlineFont = new

Font("Helvetica", Font.BOLD, 36); JTextField answer = new JTextField(10); JButton pressMe = new JButton("Press

me");

public void init() { greeting.setFont(headlineFont); con.add(greeting); con.add(answer); con.add(pressMe); con.setLayout(new FlowLayout()); pressMe.addActionListener(this);

answer.addActionListener(this);/* to allow user to hit return, as well as click button */

} public void actionPerformed(ActionEvent e) { String name = answer.getText(); System.out.println("You pressed the button, " +

name); }}

Telling your JApplet How to Telling your JApplet How to Respond to EventsRespond to Events

The ActionListener interface contains The ActionListener interface contains the actionPerformed(ActionEvent e) the actionPerformed(ActionEvent e) methodmethod

Telling Your JApplet to Expect Telling Your JApplet to Expect Events to HappenEvents to Happen

You tell your applet to expect You tell your applet to expect ActionEvents with the ActionEvents with the addActionListener() methodaddActionListener() method

Adding and Removing JApplet Adding and Removing JApplet ComponentsComponents

remove(pressMe);remove(pressMe); Removes the pressMe buttonRemoves the pressMe button

remove(answer);remove(answer); Removes the answer JTextFieldRemoves the answer JTextField

personalGreeting.setText(“hello, “ + personalGreeting.setText(“hello, “ + name);name);

Con.add(personalGreeting);Con.add(personalGreeting); Adds a componentAdds a component

Validate()Validate()

This method is added to an This method is added to an actionPerformed method after one or actionPerformed method after one or more JComponents have been added more JComponents have been added to the screen. The method ensures to the screen. The method ensures that each Component draws itself that each Component draws itself properly on the screenproperly on the screen

Understanding the JApplet Life Understanding the JApplet Life CycleCycle

Init()

start()

stop()

stop()

destroy()

Using Additional Applet Using Additional Applet MethodsMethods

There are 200 additional methods for There are 200 additional methods for manipulating components within manipulating components within JappletsJapplets

You can learn about these at You can learn about these at http://java.sun.comhttp://java.sun.com

Using Additional Applet Using Additional Applet MethodsMethods

Using the setLocation() Using the setLocation() MethodMethod

The The setLocation() setLocation() MethodMethod Allows you to place a component at a Allows you to place a component at a

specific location within the Applet specific location within the Applet Viewer windowViewer window

Does not allow you to specify the Does not allow you to specify the location of the applet itselflocation of the applet itself

Using the setEnabled() Using the setEnabled() MethodMethod

Use this method to make a Use this method to make a component unavailable and then component unavailable and then make it available again in turnmake it available again in turn

pressMe.setEnabled(false);pressMe.setEnabled(false);

answer.setEnabled(false);answer.setEnabled(false);

The above statements will make the The above statements will make the textbox and buttons on the form dim textbox and buttons on the form dim so that they cannot be enabledso that they cannot be enabled