Download How to Convert an Application into an Applet.

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
How to Convert an Application into an Applet.
A java application contains a main method. An applet is a java program part of a web page and
runs within a browser. I am going to show you three different examples. All of them involve
converting a program with a GUI into an applet.
Example 1. Original Program Contains a JFrame. This is a program that we used in Unit 10.
Run_Ex1.java
Ex1_Panel.java
import javax.swing.*;
import javax.swing.*;
import java.awt.*;
import java.awt.*;
import java.awt.event.*;
public class Run_Ex1 {
public static void main( String [] args ) {
public class Ex1_Panel extends JPanel {
JFrame f = new JFrame();
private JTextField txt = new JTextField();
f.setTitle( "Example" );
private JLabel lblResponse = new JLabel();
f.setSize( 300, 100 );
f.setDefaultCloseOperation(
public Ex1_Panel() {
JFrame. EXIT_ON_CLOSE );
setBackground( Color.ORANGE );
Container pane = f.getContentPane();
setLayout( new GridLayout( 2, 2 ) );
pane.setLayout( new BorderLayout() );
JLabel lbl = new
Ex1_Panel p = new Ex1_Panel ();
JLabel("Enter an integer: ");
pane.add( p, BorderLayout.CENTER );
JButton btn = new
f.setVisible( true );
JButton( "Click Here" );
}
btn.addActionListener( new Bob() );
}
add( lbl );
add( txt );
add( btn );
add( lblResponse );
}
private class Bob implements
ActionListener {
public void actionPerformed(
ActionEvent e) {
String str = txt.getText();
int num = Integer.parseInt( str );
if ( num % 2 == 0 )
lblResponse.setText("EVEN");
else
lblResponse.setText("ODD");
}
}
}
Step 1. Create a project in DrJava. Copy Ex1_Panel.java into the project. Copy Run_Ex1.java
into the project but rename it Run_App1.java and make the changes shown on the next page.
Run_Ex1.java
import javax.swing.*;
import java.awt.*;
Run_App1.java
import javax.swing.*;
import java.awt.*;
public class Run_Ex1 {
public static void main( String [] args ) {
JFrame f = new JFrame();
f.setTitle( "Example" );
f.setSize( 300, 100 );
f.setDefaultCloseOperation(
JFrame. EXIT_ON_CLOSE );
public class Run_App1 extends JApplet{
public void init(){
Hey! Look at this!
/* no, you don’t have to leave these lines
blank. I wanted to emphasize the lines that are
no longer needed because applets do not use
JFrames. */
Container pane = f.getContentPane();
pane.setLayout( new BorderLayout() );
Ex1_Panel p = new Ex1_Panel ();
pane.add( p, BorderLayout.CENTER );
f.setVisible( true );
Container pane = getContentPane();
pane.setLayout( new BorderLayout() );
Ex1_Panel p = new Ex1_Panel ();
pane.add( p, BorderLayout.CENTER );
}
}
}
}
General rules for converting application code into applet code.
 You need a class that extends JApplet. This has a getContentPane method (just like
JFrame).
 Do not write a constructor for the class that extends JApplet. On the other hand, you
must override the init method. This basically serves as our main method (which we do
not use.)
 Do not use the JFrame class.
Step 2. You create a jar file that contains compressed
copies of your files. It makes for faster downloads.
You can easily do this in DrJava if you are in a project.
Click on the Project menu and then select Create Jar
File from Project …
Select “Jar All Files” though it may work to select “Jar
classes.”
Name the Jar file “Run_App1.jar” and click OK.
Step 3. You write an html file that displays the applet. Open Notepad or Wordpad and enter the
following:
<html><head><title>Example 1 Applet</title></head><body>
<h1>Example 1</h1>
<applet code = "Run_App1.class" archive = "Run_App1.jar"
width = "300"
height= "100" >
</applet>
</body></html>
Save it as Ex1.html. Double-click on this file and your program should display (and work)
within the web page. This is valid html from around 2007. Times change but I think this is good
enough. Feel free to disagree with me.
Example 2. Original Program Contains a Class that
Extends JFrame. This program has contains two
panels. If you click on the left or right panel, num
increases by one and both messages display the new
value.
This is a simple runner class.
public class Run_Ex2 {
public static void main( String [] args ) {
MyFrame my_f = new MyFrame();
}
}
This class extends JFrame. It
creates two panel objects and
passes a reference to itself to
each of the panels. This
allows each panel to call
methods of the MyFrame
class.
import javax.swing.*;
import java.awt.*;
public class MyFrame extends JFrame {
private Ex2_Panel left;
private Ex2_Panel right;
private int num = 0;
Notice that I did not set a size
for the frame. Instead, each
panel sets a preferred size and
the frame calls the pack
method which causes the
frame to calculate its size
based on the objects it
contains.
public MyFrame() {
setTitle( "Example 2" );
setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE);
Container pane = getContentPane();
pane.setLayout( new GridLayout( 1, 2 ) );
left = new Ex2_Panel ( this, Color.ORANGE );
right = new Ex2_Panel ( this, Color.WHITE );
pane.add( left );
pane.add( right );
pack();
setVisible( true );
}
In addition to the panels, there
is an instance variable, num,
and mutator and accessor
methods. Notice that
whenever we change num we
send a message to each panel
to repaint itself.
public int getNum(){
return num;
}
public void increaseNum(){
num++;
left.repaint();
right.repaint();
}
}
The Ex2_Panel class
contains a reference back to
the frame that is creating the
objects. Whenever the user
clicks on a panel, it calls
f.increaseNum();
which increases num in the
MyFrame object and causes
each panel to repaint itself.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Ex2_Panel extends JPanel {
private MyFrame f;
private static final int LENGTH = 200;
public Ex2_Panel( MyFrame myF, Color c ) {
f = myF;
setBackground( c );
setPreferredSize( new Dimension(LENGTH, LENGTH) );
addMouseListener( new Handle() );
}
In the paintComponent
method the panel calls
f.getNum()
to get the current value of
num and prints it.
public void paintComponent( Graphics g ){
super.paintComponent( g );
g.setFont( new Font("SansSerif", Font.BOLD, 24) );
g.drawString ("Num is " + f.getNum(), 50, 50 );
}
private class Handle extends MouseAdapter {
public void mousePressed(MouseEvent e) {
f.increaseNum();
}
}
}
Create the applet.
Step 1. Create a project in DrJava. Create a new class called Run_App2. This is nearly identical
to MyFrame except that (1) it extends JApplet and not JFrame; (2) the constructor is replaced by
the init method; and (3) some calls to JFrame methods have been deleted.
Copy Ex2_Panel.java into the project and change any references to MyFrame to
Run_App2.
The Run_Ex2 class, which contains the main method, is not needed in the applet version.
Here is the code for the Run_App2 class.
import javax.swing.*;
import java.awt.*;
public class Run_App2 extends JApplet {
private Ex2_Panel left;
private Ex2_Panel right;
private int num = 0;
// continued on the next page
// changed from MyFrame
public void init() {
Container pane = getContentPane();
pane.setLayout( new GridLayout( 1, 2 ) );
left = new Ex2_Panel ( this, Color.ORANGE );
right = new Ex2_Panel ( this, Color.WHITE );
pane.add( left );
pane.add( right );
}
// changed from MyFrame
public int getNum(){
return num;
}
public void increaseNum(){
num++;
left.repaint();
right.repaint();
}
}
Step 2. You create the jar file and name it the same as the class that contains the init method.
Does it absolutely have to have the same name as the class that contains the init method? I don’t
think so but I’ve had problems when I’ve changed it and I haven’t taken the time to get to the
bottom of it.
Step 3. You write an html file that displays the applet. Open Notepad or Wordpad and enter the
following:
<html><head><title>Example 2 Applet</title></head><body>
<h1>Example 1</h1>
<applet code = "Run_App2.class" archive = "Run_App2.jar"
width = "600"
height= "150" >
</applet>
</body></html>
Save it as Ex2.html. Double-click on
this file and your program should
display (and work) within the web
page.
Notice that the size of the applet is
determined by the width and height in
the above html tag and not the
preferred sizes of the panels.
Example 3. Original Program Loads and Uses an JPG. If your program works with files
then you will have to make some small changes to handle that. Here is a program that displays
an image. Clicking on the panel causes the image to switch to another image and back
import javax.swing.*;
import javax.swing.*;
import java.awt.*;
import java.awt.*;
import java.awt.event.*;
public class Run_Ex3 {
public class Ex3_Panel extends JPanel {
public static void main(
private ImageIcon img;
String [] args ) {
private boolean face = true;
JFrame f = new JFrame();
f.setTitle( "Example" );
f.setSize( 300, 300 );
f.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
public Ex3_Panel() {
img = new ImageIcon( "girl.jpg" );
setBackground( Color.ORANGE );
addMouseListener( new Rat() );
}
Container pane =
f.getContentPane();
pane.setLayout(
new BorderLayout() );
public void paintComponent( Graphics g ){
super.paintComponent( g );
int iw = img.getIconWidth();
int ih = img.getIconHeight();
int w = getWidth();
int h = getHeight();
int x = (w - iw)/2;
int y = (h - ih)/2;
img.paintIcon( this, g, x, y );
}
Ex3_Panel p = new Ex3_Panel ();
pane.add( p,
BorderLayout.CENTER );
f.setVisible( true );
}
private class Rat extends MouseAdapter {
public void mousePressed( MouseEvent e) {
if ( face )
img = new ImageIcon( "fish.jpg" );
else
img = new ImageIcon( "girl.jpg" );
}
face = !face;
repaint();
}
}
}
If you convert the above application into an applet using the process
we used before, there will be an error and the picture will not display.
If you click on the Java icon in the bottom task bar and select “Open
1.6.0_31 Console” you’ll see the following run-time error:
java.security.AccessControlException: access denied (java.io.FilePermission girl.jpg read)
A solution. Wherever you instantiate an ImageIcon like this:
img = new ImageIcon( "fish.jpg" );
replace it with this:
img = new ImageIcon(getClass().getResource( "fish.jpg" ) );
Here is the applet version of this program.
import javax.swing.*;
import javax.swing.*;
import java.awt.*;
import java.awt.*;
import java.awt.event.*;
public class Run_App3
extends JApplet{
public class Ex3_Panel extends JPanel {
private ImageIcon img;
public void init() {
private boolean face = true;
Container pane =
getContentPane();
public Ex3_Panel( ) {
pane.setLayout(
img = new ImageIcon(
new BorderLayout());
getClass().getResource( "girl.jpg" ) );
setBackground( Color.ORANGE );
addMouseListener( new Rat() );
Ex3_Panel p =
new Ex3_Panel ();
pane.add( p,
BorderLayout.CENTER );
}
public void paintComponent( Graphics g ){
super.paintComponent( g );
int iw = img.getIconWidth();
int ih = img.getIconHeight();
int w = getWidth();
int h = getHeight();
int x = (w - iw)/2;
int y = (h - ih)/2;
img.paintIcon( this, g, x, y );
}
}
}
private class Rat extends MouseAdapter {
public void mousePressed(MouseEvent e){
if ( face )
img = new ImageIcon(
getClass().getResource( "fish.jpg" ) );
else
img = new ImageIcon(
getClass().getResource( "girl.jpg" ));
face = !face;
repaint();
}
}
}