java programming, second edition chapter nine applets
TRANSCRIPT
Java Programming, Java Programming, Second EditionSecond Edition
Chapter NineChapter Nine
AppletsApplets
In this chapter, you will:In this chapter, you will:
Write an HTML document to host an Write an HTML document to host an appletapplet
Understand simple appletsUnderstand simple applets Use Labels with simple AWT appletsUse Labels with simple AWT applets Write a simple Swing applet and use a Write a simple Swing applet and use a
JLabelJLabel Add JTextField and JButton Components Add JTextField and JButton Components
to Swing appletsto Swing applets
Learn about event-driven programmingLearn about event-driven programming Add output to a Swing appletAdd output to a Swing applet Understand the Swing applet life cycleUnderstand the Swing applet life cycle Create a more sophisticated interactive Create a more sophisticated interactive
Swing appletSwing applet Use the setLocation() and setEnabled() Use the setLocation() and setEnabled()
methodsmethods
To Write a Java Application:To Write a Java Application:
Write the application in the Java Write the application in the Java programming language, and then save it programming language, and then save it with a .java file extensionwith a .java file extension
Compile the application into bytecode Compile the application into bytecode using the javac command. The bytecode is using the javac command. The bytecode is stored in a file with a .class file extensionstored in a file with a .class file extension
Use the java command to interpret and Use the java command to interpret and execute the .class fileexecute the .class file
Writing an HTML Document to Host Writing an HTML Document to Host an Appletan Applet
Applets- Programs that are called from Applets- Programs that are called from within another applicationwithin another application You run applets withinYou run applets within
a page on the Interneta page on the Internet an intranetan intranet or a local computer from within another program or a local computer from within another program
called Applet Viewercalled Applet Viewer To view an applet, it must be called from To view an applet, it must be called from
within another document written in HTMLwithin another document written in HTML
Writing an HTML Document to Host Writing an HTML Document to Host an Appletan Applet
To create an applet: To create an applet: Write the applet in the Java programming Write the applet in the Java programming
language, and save it with a .java file extensionlanguage, and save it with a .java file extension Compile the applet into bytecode using the javac Compile the applet into bytecode using the javac
commandcommand Write an HTML document that includes a Write an HTML document that includes a
statement to call your compiled Java classstatement to call your compiled Java class Load the HTML document into a Web browser or Load the HTML document into a Web browser or
run the AppletViewer programrun the AppletViewer program
Writing an HTML Document to Host Writing an HTML Document to Host an Appletan Applet
Applets are popular because users can Applets are popular because users can execute them using a Web browser execute them using a Web browser Web browser- A program that allows you to Web browser- A program that allows you to
display HTML documents on your display HTML documents on your computer screencomputer screen Internet ExplorerInternet Explorer Netscape NavigatorNetscape Navigator
Writing an HTML Document to Writing an HTML Document to Host an AppletHost an Applet
Code to run an applet from within an HTML documentCode to run an applet from within an HTML document <applet><applet> </applet></applet>
Applet tag attributesApplet tag attributes CODE = is followed by the name of the compiled applet you are CODE = is followed by the name of the compiled applet you are
callingcalling WIDTH = is followed by the width of the applet on the screenWIDTH = is followed by the width of the applet on the screen HEIGHT = is followed by the height of the applet on the screenHEIGHT = is followed by the height of the applet on the screen
AppletsApplets
The WIDTH and HEIGHT attributes are The WIDTH and HEIGHT attributes are measured in pixelsmeasured in pixels Pixels- Picture elements, or tiny dots that Pixels- Picture elements, or tiny dots that
make up the image on your video monitormake up the image on your video monitor
HTML ExampleHTML Example
Example of Garage.htmlExample of Garage.html
<applet code="Garage.class" width=250 <applet code="Garage.class" width=250 height=120>height=120>
</applet></applet>
Understanding Simple AppletsUnderstanding Simple Applets
To write an applet you must also:To write an applet you must also: Include import statements to ensure that Include import statements to ensure that
necessary classes are availablenecessary classes are available Learn to use some Windows components Learn to use some Windows components
and applet methodsand applet methods Learn to use the keyword extendsLearn to use the keyword extends
Understanding Simple AppletsUnderstanding Simple Applets
Component- A class that defines any Component- A class that defines any object that you want to displayobject that you want to display
Container- A class that is used to define a Container- A class that is used to define a component that can contain other component that can contain other componentscomponents
Understanding Simple AppletsUnderstanding Simple Applets
Most AWT applets contain 2 import Most AWT applets contain 2 import statementsstatements import java.applet.*;import java.applet.*; import java.awt.*;import java.awt.*;
java.applet- Contains a class named Appletjava.applet- Contains a class named Applet Every applet you create is based on AppletEvery applet you create is based on Applet
java.awt- The Abstract Windows Toolkit, or java.awt- The Abstract Windows Toolkit, or AWT AWT
Understanding Simple AppletsUnderstanding Simple Applets
Most Swing applets contain 2 import Most Swing applets contain 2 import statementsstatements import javax.swing.*;import javax.swing.*; import java.awt.*;import java.awt.*;
javax.swing- A package that contains javax.swing- A package that contains classes that define GUI components classes that define GUI components (Swing components)(Swing components)
Understanding Simple AppletsUnderstanding Simple Applets
Swing classes- part of a more general set Swing classes- part of a more general set of GUI programming capabilities that are of GUI programming capabilities that are known as the Java Foundation Classes, or known as the Java Foundation Classes, or JFCJFC
JFC includes Swing component classes and JFC includes Swing component classes and selected classes from the java.awt packageselected classes from the java.awt package
AWT and Swing AppletsAWT and Swing Applets
AWT and Swing appletsAWT and Swing applets Begin the same way as Java applicationsBegin the same way as Java applications Must also includeMust also include
extends Appletextends Applet extends JAppletextends JApplet
The extends keyword indicates the applet will The extends keyword indicates the applet will build upon Applet and JAppletbuild upon Applet and JApplet
AppletsApplets
Four methods in every appletFour methods 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()
Java can create these for youJava can create these for you
Using Labels with Simple AWT Using Labels with Simple AWT AppletsApplets
The java.awt package contains commonly The java.awt package contains commonly used Windows componentsused Windows components LabelsLabels MenusMenus ButtonsButtons
Label- Built-in class that holds text that Label- Built-in class that holds text that you can display within an appletyou can display within an applet
Using Labels with Simple AWT Using Labels with Simple AWT AppletsApplets
Label class contains fields that indicate Label class contains fields that indicate font and alignmentfont and alignment
You can assign some text to a label with You can assign some text to a label with the setText() methodthe setText() method
Use the add() method to add a component Use the add() method to add a component to an applet windowto an applet window
Writing a Simple Swing Applet and Writing a Simple Swing Applet and Using a JLabelUsing a JLabel
JLabel- Built-in class that holds text that JLabel- Built-in class that holds text that you can display within an appletyou can display within an applet The counterpart to the AWT LabelThe counterpart to the AWT Label
Writing a Simple Swing Applet and Writing a Simple Swing Applet and Using a JLabelUsing a JLabel
Available constructors include:Available constructors include:JLabel() creates a JLabel instance with no image and an JLabel() creates a JLabel instance with no image and an
empty string for the titleempty string for the titleJLabel(Icon image) creates a JLabel instance with the JLabel(Icon image) creates a JLabel instance with the
specified imagespecified imageJLabel(Icon image, int horizontalAlignment) creates a JLabel(Icon image, int horizontalAlignment) creates a
JLabel instance with the specified image and horizontal JLabel instance with the specified image and horizontal alignmentalignment
JLabel(String text) creates a JLabel instance with the JLabel(String text) creates a JLabel instance with the specified textspecified text
JLabel(String text, Icon icon, int horizontalAlignment) JLabel(String text, Icon icon, int horizontalAlignment) creates a JLabel instance with the specified text, image, creates a JLabel instance with the specified text, image, and horizontal alignmentand horizontal alignment
JLabel(String text, int horizontalAlignment) creates a JLabel(String text, int horizontalAlignment) creates a JLabel instance with the specified text and horizontal JLabel instance with the specified text and horizontal alignmentalignment
Writing a Simple Swing Applet and Writing a Simple Swing Applet and Using a JLabelUsing a JLabel
AWT components are added directly to the AWT components are added directly to the AppletApplet
Swing components must use a content Swing components must use a content panepane The content pane is an object of the The content pane is an object of the
Container classContainer class A container can be created using the A container can be created using the
getContentPane() methodgetContentPane() method
Changing a JLabel’s FontChanging a JLabel’s Font
Font object- Holds typeface and size informationFont object- Holds typeface and size information setFont() method requires a Font object setFont() method requires a Font object
argumentargument To construct a Font object you need 3 To construct a Font object you need 3
argumentsarguments TypefaceTypeface StyleStyle Point sizePoint size
Changing a JLabel’s FontChanging a JLabel’s Font
To construct a Font object you need 3 argumentsTo construct a Font object you need 3 arguments TypefaceTypeface
String representing a fontString representing a font Common fonts are Arial, Courier, and New Times RomanCommon fonts are Arial, Courier, and New Times Roman Is only a requestIs only a request
Style- applies an attribute to displayed textStyle- applies an attribute to displayed text Font.PLAINFont.PLAIN Font.BOLDFont.BOLD Font.ITALICFont.ITALIC
Point sizePoint size Integer that represents 1/72 of an inchInteger that represents 1/72 of an inch Printed text is usually 10- or 12 pointsPrinted text is usually 10- or 12 points
Adding JTextField Components to Adding JTextField Components to Swing AppletsSwing Applets
JTextField- Component into which a user can JTextField- Component into which a user can type a single line of text datatype a single line of text data
JText field can be constructed fromJText field can be constructed from public JTextField() constructs a new JTextFieldpublic JTextField() constructs a new JTextField public JTextField(int numColumns) constructs a new public JTextField(int numColumns) constructs a new
empty JTextField with a specified number of columnsempty JTextField with a specified number of columns public JTextField(String text) constructs a new public JTextField(String text) constructs a new
JTextField initialized with the specific textJTextField initialized with the specific text public JTextField(String text, int columns) constructs a public JTextField(String text, int columns) constructs a
new JTextField with the specified text and columnsnew JTextField with the specified text and columns
Other JTextField MethodsOther JTextField Methods
setText() method- Allows you to change setText() method- Allows you to change the text in a JTextField that has already the text in a JTextField that has already been createdbeen created
getText() method- Allows you to retrieve getText() method- Allows you to retrieve the string of text in a JTextFieldthe string of text in a JTextField
Other JTextField MethodsOther JTextField Methods
Keyboard focus- When the user clicks within the Keyboard focus- When the user clicks within the JTextField, the JTextField has focus, which JTextField, the JTextField has focus, which means the next entries from the keyboard will be means the next entries from the keyboard will be at that locationat that location
requestFocus() method- To have the insertion requestFocus() method- To have the insertion point appear automatically within the TextField point appear automatically within the TextField without requiring the user to click in it first without requiring the user to click in it first
Editable- The capacity for a field to accept Editable- The capacity for a field to accept keystrokeskeystrokes
setEditable() method- Used to change the setEditable() method- Used to change the editable status of a JTextFieldeditable status of a JTextField
Other JTextField Methods
Adding JButton Components to Adding JButton Components to Swing AppletsSwing Applets
JButton- Creates a buttonJButton- Creates a button JButton can be constructed fromJButton can be constructed from
public JButton() constructs a button with no set textpublic JButton() constructs a button with no set text public JButton(Icon icon) creates a button with an icon public JButton(Icon icon) creates a button with an icon
of type Icon or ImageIconof type Icon or ImageIcon public JButton(String text) creates a button with the public JButton(String text) creates a button with the
specific textspecific text public JButton(String text, int columns) constructs a public JButton(String text, int columns) constructs a
new JTextField with the specified text and columnsnew JTextField with the specified text and columns
Adding JButton Components to Adding JButton Components to Swing AppletsSwing Applets
setLabel() methodsetLabel() method To change a JButton’s labelTo change a JButton’s label readyJButton.setLabel(“Don’t press me again!”)readyJButton.setLabel(“Don’t press me again!”)
Adding Multiple Components to a Adding Multiple Components to a JAppletJApplet
To add multiple components in a container To add multiple components in a container use a layout manageruse a layout manager To control component positioningTo control component positioning Default behavior is to use a border layoutDefault behavior is to use a border layout
Border layoutsBorder layouts Flow layoutsFlow layouts
Adding Multiple Components to a Adding Multiple Components to a JAppletJApplet
Border layoutsBorder layouts Created by the BorderLayout classCreated by the BorderLayout class Divide a container into 5 sectionsDivide a container into 5 sections
North, South, East, West, and centerNorth, South, East, West, and center
Created with the BorderLayout() or Created with the BorderLayout() or BorderLayout(int, int) methodsBorderLayout(int, int) methods
Adding Multiple Components to a Adding Multiple Components to a JAppletJApplet
Flow LayoutsFlow Layouts Places components in a row, and when a row Places components in a row, and when a row
is filled, it automatically spills components is filled, it automatically spills components onto the next rowonto the next row
Default positioning of the row of components Default positioning of the row of components is centered in the containeris centered in the container
Learning about Event-Driven Learning about Event-Driven ProgrammingProgramming
Event- Occurs when someone using your applet Event- Occurs when someone using your applet takes action on a componenttakes action on a component
Procedural- Programmers dictate the order in Procedural- Programmers dictate the order in which events occurwhich events occur
Event-driven programs- The user can initiate any Event-driven programs- The user can initiate any number of events in any ordernumber of events in any order
Source- Component on which an event is Source- Component on which an event is generatedgenerated
Listener- Object that is interested in an eventListener- Object that is interested in an event
Preparing Your Swing Applet to Preparing Your Swing Applet to Accept Event MessagesAccept Event Messages
Prepare your applet to accept mouse Prepare your applet to accept mouse events by: events by: importing the java.awt.event packageimporting the java.awt.event package adding the phrase implements ActionListener adding the phrase implements ActionListener
to the class headerto the class header ActionListener is an interfaceActionListener is an interface Interface- A set of specifications for Interface- A set of specifications for
methods that you can use with event methods that you can use with event objectsobjects
Telling Your Swing Applet to Telling Your Swing Applet to Expect Events to HappenExpect Events to Happen
addActionListener() method addActionListener() method To tell the applet to expect ActionEventsTo tell the applet to expect ActionEvents aButton.addActionListener(this);aButton.addActionListener(this);
Telling Your Swing Applet How to Telling Your Swing Applet How to Respond to Any Events That HappenRespond to Any Events That Happen
actionPerformed(ActionEvent e) methodactionPerformed(ActionEvent e) method When a JApplet has registered as a listener When a JApplet has registered as a listener
with a JButton, and a user clicks the JButton with a JButton, and a user clicks the JButton the actionPerformed method executesthe actionPerformed method executes
Adding Output to a Swing Adding Output to a Swing AppletApplet
You can add components to an applet You can add components to an applet using the add() methodusing the add() method
You can also remove components from an You can also remove components from an applet using the remove() methodapplet using the remove() method Remove(answer);Remove(answer);
Understanding the Swing Applet Understanding the Swing Applet Life CycleLife Cycle
Override- When you write a method that Override- When you write a method that has the same method header as an has the same method header as an automatically provided methodautomatically provided method
Understanding the Swing Applet Understanding the Swing Applet Life CycleLife Cycle
start() method- Executes after the init() start() method- Executes after the init() methodmethod Executes every time the applet becomes Executes every time the applet becomes
active after it has been inactive active after it has been inactive stop() method- When a user leaves a web stop() method- When a user leaves a web
pagepage You do not usually write your own stop() You do not usually write your own stop()
methodsmethods
Understanding the Swing Applet Understanding the Swing Applet Life CycleLife Cycle
destroy() method- When the user closes destroy() method- When the user closes the browser or AppletViewerthe browser or AppletViewer You do not usually write your own destroy() You do not usually write your own destroy()
methodsmethods
Using the setLocation() and Using the setLocation() and setEnabled() Methods setEnabled() Methods
setLocation() method- Allows you to place a setLocation() method- Allows you to place a component at a specific location within the component at a specific location within the AppletViewer windowAppletViewer window X-axis- Horizontal position in a windowX-axis- Horizontal position in a window X-coordinate- Value increases as you travel from left X-coordinate- Value increases as you travel from left
to right across the windowto right across the window Y-axis- Vertical position in the windowY-axis- Vertical position in the window Y-coordinate- Value increases as you travel from top Y-coordinate- Value increases as you travel from top
to bottom in the windowto bottom in the window
The setEnabled() MethodThe setEnabled() Method
setEnabled() method- To make a setEnabled() method- To make a component unavailable and, in turn, to component unavailable and, in turn, to make it available againmake it available again
True if you want to enable a componentTrue if you want to enable a component False if you want to disable a componentFalse if you want to disable a component If (yLoc==280) If (yLoc==280)
pressButton.setEnabled(false);pressButton.setEnabled(false);