Download Lesson 22- IntroToJavaApplets

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Object-Oriented S/W Development with Java CSCI 3381
Lesson 22:
Intro to Applets &
Multiple Document Interface (MDI)
April 17 & 19, 2012
Object-Oriented S/W Development with Java CSCI 3381
Java Applets
Applet: Java program that runs in an appletviewer or
www browser
Browser: Executes the applet when an HTML
document pointing to the applet is opened.
Can also execute applet from separate applet viewer or
from inside your editor or IDE
Object-Oriented S/W Development with Java CSCI 3381
A Complete Applet
import javax.swing.JApplet;
import java.awt.Graphics;
public class WelcomeApplet extends JApplet {
public void paint(Graphics g) {
super.paint(g);
g.drawString( "Welcome to Applets!",
25, 25 );
}
}
The paint method overrides the paint method inherited by
JApplet from class Container
25,25 indicates bottom left corner of where string should start
Object-Oriented S/W Development with Java CSCI 3381
Applet Launched from HTML File
To execute an applet, carry out two steps:
1. Compile Applet source files into class files
2. Create an HTML file that tells the browser which
class file to load first and how to size the applet
Example:
<html>
<applet code= "WelcomeApplet.class"
width=300 height=30>
</applet>
</html>
width and height determine display area
Object-Oriented S/W Development with Java CSCI 3381
Java Application Example: “Addition”
import javax.swing.JOptionPane;
public class Addition { // get, add &display sum of two ints
public static void main( String args[]){
String firstNumber, secondNumber;
int number1, number2, sum;
// read in two numbers from user as strings
firstNumber=JOptionPane.showInputDialog("Enter 1st int");
secondNumber=JOptionPane.showInputDialog("Enter 2nd");
number1=Integer.parseInt(firstNumber); //convert str->int
number2 = Integer.parseInt(secondNumber);
sum = number1 + number2; // find sum of values entered
// display the results
JOptionPane.showMessageDialog(null, "The sum is " + sum,
"Results", JOptionPane.PLAIN_MESSAGE);
System.exit( 0 );
// terminate the program
}
}
Object-Oriented S/W Development with Java CSCI 3381
vs. Java Applet “AdditionApplet”
import java.awt.Graphics;
import javax.swing.*;
// all classes in javax.swing
public class AdditionApplet extends JApplet {
double sum; // instance variable declaration
public void init(){
String firstNumber,
secondNumber;
double number1, number2;
firstNumber = JOptionPane.showInputDialog(
"Enter first floating-point value" );
secondNumber =JOptionPane.showInputDialog(
"Enter second floating-point value" );
number1 = Double.parseDouble( firstNumber );
number2 = Double.parseDouble( secondNumber );
sum = number1 + number2;
} // end init
Object-Oriented S/W Development with Java CSCI 3381
AdditionApplet’s Paint Method
public void paint( Graphics g ){
// draw the results with g.drawString
g.drawRect( 15, 10, 270, 20 );
g.drawString( “The sum is ” + sum, 25,25);
} // end paint
}// end Class AdditionApplet
Object-Oriented S/W Development with Java CSCI 3381
Converting Application to Applet
1.
2.
3.
4.
5.
6.
7.
8.
Create subclass of JApplet class (must make public,
otherwise applet can’t be loaded)
Eliminate main method from application; do not construct a
frame window for application
Move any initialization code from the frame window
constructor to init method for applet
Remove call to setSize in main; sizing done with width and
height parameters in HTML file
Remove call to setDefaultCloseOperation; applet cannot be
closed- terminates when browser exits
Eliminate call to method setTitle if used; applet title set
using HTML title tag
Don’t call setVisible(true); applet displayed automatically
Make HTML page with appropriate tag to load applet code
Object-Oriented S/W Development with Java CSCI 3381
AdditionApplet.html
<html>
<head>
<title>Addition Applet Demo</title>
</head>
<body>
<applet code= “AdditionApplet.class”
width=300 height=30>
</applet>
</body>
</html>
Object-Oriented S/W Development with Java CSCI 3381
To Create An Applet Using NetBeans
Step 1:Convert Addition to an applet. Using NetBeans...
Choose File, New Project. Under Categories, select General. Under Projects, select
Java Class Library. Click Next.
Under Project Name, enter the name of your application. Change the Project
Location to any folder on your computer.
Click Finish. The IDE creates the project folder.
Right-click the project node in the Projects window or Files window and select
New File/Folder. Under Categories, select Java Classes. Under File Types, select
JApplet. Click Next.
Under Class Name, enter AdditionApplet. Leave the Package empty.
Click Finish. The IDE creates the applet in the default package. The applet opens in
the Source editor.
Copy AdditionApplet code into the file you just created.
Build <shift+F11> and run <shift+F6> your applet.
This step is netBeans specific. It is required in order to fix a potential class path
problem introduced by creating your applet with the IDE. Go to your 'build'
directory and copy AdditionApplet.html from there to the 'src' directory. Now build
<shift+F11> your project again.
Object-Oriented S/W Development with Java CSCI 3381
Creating An Applet Using NetBeans (cont.)
Step 2: Save the following html text as a text file. Make sure the
filename ends in .html
<html>
<head>
<title>Addition Applet Demo</title>
</head>
<body>
<applet code= “AdditionApplet.class”
width=300 height=30>
</applet>
</body>
</html>
Step 3: Copy the AdditionApplet.class file from your
'build/classes' directory to the directory with your html file.
Step 4: Open your html with browser and applet should run.
Object-Oriented S/W Development with Java CSCI 3381
Life Cycle of an Applet
Methods guaranteed to be called during applet's lifetime:
Implicitly called (in this order) when Applet begins
execution:
Implicitly called when browser leaves page where
applet resides:
init() // 1st method called
start() // an applet is a thread!
paint(Graphics g); // draws to the
// applet area
stop()
Implicitly called when browser is exited:
destroy()
Object-Oriented S/W Development with Java CSCI 3381
Applet Security
Applets are designed to be loaded from a remote site and
then executed locally
Therefore, applets are restricted in what they can do; this
restricted execution environment referred to as the
“sandbox.” When running in the sandbox, applets:
can never run any local executable program
cannot communicate with any host other than the server
from which they were downloaded
cannot read from or write to a local computer’s file system
cannot find out any information about the local computer
carry a warning message in all applet windows that pop up
Object-Oriented S/W Development with Java CSCI 3381
Signed Applets
These restrictions are too strong for some situations,
e.g. a corporate intranet where you want an applet to
have access to local files
To allow for different levels of security under
different situations, you can use signed applets
Signed applet carries with it a certificate that indicates
identity of signer
If you trust the signer, you can choose to give the
applet additional rights
Completely trusted applets can be given same privilege
levels as local applications
To find out more about signed applets see:
http://mindprod.com/jgloss/signedapplets.html#JAWS
Object-Oriented S/W Development with Java CSCI 3381
Pop-up Windows in Applets
Just as with other applications, you can open another
window from within an applet
Can be done using a JFrame, omitting the call to
setDefaultCloseOperation. Example:
JFrame frame = new JFrame();
frame.setTitle(“Child Frame”);
frame.setSize(200, 200);
Object-Oriented S/W Development with Java CSCI 3381
Pop-up Windows in Applets (cont.)
Child frame opened from parent frame using JButton or
other means such as:
JButton openChild = new JButton(“Open
Child Frame”);
openChild.addActionListener(new
ActionListener()
{
public void actionPerformed
(ActionEvent evt)
{
frame.setVisible(true);
}
});
Object-Oriented S/W Development with Java CSCI 3381
Inter-Applet Communication
If web page contains multiple applets from the same
codebase, they can communicate with each other
If you give name attributes to each applet in the HTML
file, you can use the getApplet method of the
AppletContext interface to get a reference to the applet
Example: if your HTML file contains the tag
<applet code = “Parent.class” width =
“100” height = “100” name = “Parent”>
then the call
Applet parent =
getAppletContext().getApplet(“Parent”);
gives you a reference to the parent applet
Object-Oriented S/W Development with Java CSCI 3381
Inter-Applet Communication (cont.)
You can then use this reference to call methods from
the parent class by making the following cast:
((Parent) parent).parentMethod();
Similar technique can be used by the parent class to
invoke methods on the child; consequently two-way
inter-applet communication can be established
Object-Oriented S/W Development with Java CSCI 3381
Adv. GUI Components
Java Supports Multiple Document Interfaces (MDIs)
with Parent and Child Windows:
JDesktopPane - Manages Child Windows
JInternalFrame - A Child Window
Displayed Within the Parent Window via
JDesktopPane
Object-Oriented S/W Development with Java CSCI 3381
JDesktopPane and JInternalFrame
Creating JDesktopPane (Deitel Fig. 22.11)
35: theDesktop = new JDesktopPane( );
36: add( theDesktop ); // adds Desktop Pane to frame
Creating JInternalFrame
47: JInternalFrame frame = new JInternalFrame(
“Internal Frame”, true, true, true, true)
54: theDesktop.add ( frame ); // attach internal frame
55: frame.setVisible( true ); // show internal frame
Object-Oriented S/W Development with Java CSCI 3381
JDesktopPane / JInternalFrame Linkage
Linkage from JInternalFrame to parent JDesktopPane
available via JInternalFrame method getDesktopPane( )
getDesktopPane( ) returns the JDesktopPane this internal
frame belongs to
Linkage from JDesktopPane to child JInternalFrame(s)
provided via JDesktopPane methods getAllFrames( )
and getSelectedFrame( )
getAllFrames( ) returns an array containing all
JInternalFrames currently displayed in the desktop
getSelectedFrame( ) returns the internal frame that's
currently selected
Object-Oriented S/W Development with Java CSCI 3381
MDI’s with JFrames
A Multiple-Document Interface can also be provided
with JFrames
JFrame - A Dynamically Created Independent Window
• JFrames can be Moved Around Entire Screen
We will focus on JFrames
Object-Oriented S/W Development with Java CSCI 3381
*MDI’s with JFrames (example)
Object-Oriented S/W Development with Java CSCI 3381
From Initially Running App (MDIGridBag.java):
167: public void actionPerformed(ActionEvent e){
if (e.getActionCommand() == "Play Craps"){
playCrapsWindow();
}
}
186: public void playCrapsWindow(){
MDICraps myCraps = new MDICraps(this);
}
Note:
Calling MDICraps(this) creates a new instance of Craps,
Craps will Create (and Run in) its own JFrame
"this" provides MDICraps Constructor with Reference to
object instance that Created the MDICraps instance
Object-Oriented S/W Development with Java CSCI 3381
MDICraps Instance Runs in Independent Window
50:
public MDICraps(MDIGridBag creatorLink) {//MDICraps.java
creator = creatorLink;
JFrame frame =new JFrame("Craps Game");
Container c = frame.getContentPane();
...
frame.setSize(400,200);
frame.setVisible(true); // frame MUST show itself
Note:
MDICraps Constructor Creates a new JFrame in which to
Run
creatorLink is Reference to Caller (Creator) of MDICraps
Object-Oriented S/W Development with Java CSCI 3381
MDICraps Instance actionPerformed method
119: public void actionPerformed( ActionEvent e ){
…
if(e.getSource()== sendToCreatorButton){
creator.AddToCrapsTotal(bankRoll);
bankRoll = 0;
bankRollText.setText
(Integer.toString(bankRoll));
}
}
Note:
Via its constructor, MDICraps instance has a "creator"
reference to the application that dynamically allocated the
MDICraps instance.
Reference allows MDICraps instance to invoke methods of the
creating application.
Object-Oriented S/W Development with Java CSCI 3381
ICE: Comm Between GUI Content Panes
Alter the source code as necessary so that the
MDIGridBag instance has a button that causes the
current “Sum of Craps Totals…” value to be sent to
a particular instance of MDICraps.
Object-Oriented S/W Development with Java CSCI 3381
Applet Idiosyncrasies
If you make a change to your applet and recompile,
you need to restart the browser so that it loads the new
class files
Can avoid painful browser restart if you launch the
Java console (under Tools menu on Firefox) and issue
command x
Object-Oriented S/W Development with Java CSCI 3381
Summary
Java Applets
Applet extends JApplet
Uses HTML file to launch Applet in Web Browser or
Applet Viewer
Converting Application to Applet
Create An Applet Using NetBeans
Life Cycle of an Applet
Applet Security
Signed Applets
Object-Oriented S/W Development with Java CSCI 3381
Summary (cont.)
Communication between GUI content panes
Using name attributes in HTML file to establish
linkage between Applet windows
Using JDesktopPane and JInternalFrame to establish
linkage between content panes
Providing Multiple-Document Interface between
Jframes by keeping reference to created frames and
their creator