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 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 ); Container pane = f.getcontentpane(); pane.setlayout( new BorderLayout() ); Ex1_Panel p = new Ex1_Panel (); pane.add( p, BorderLayout.CENTER ); f.setvisible( true ); public class Ex1_Panel extends JPanel { private JTextField txt = new JTextField(); private JLabel lblresponse = new JLabel(); public Ex1_Panel() { setbackground( Color.ORANGE ); setlayout( new GridLayout( 2, 2 ) ); JLabel lbl = new JLabel("Enter an integer: "); JButton btn = new 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 Run_App1.java Hey! Look at this! 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(){ /* 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. 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. 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 class MyFrame extends JFrame { private Ex2_Panel left; private Ex2_Panel right; private int num = 0; 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 ); 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. In the paintcomponent method the panel calls f.getnum() to get the current value of num and prints it. 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() ); 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. public class Run_App2 extends JApplet { private Ex2_Panel left; private Ex2_Panel right; private int num = 0; // changed from MyFrame // continued on the next page
public void init() { // changed from MyFrame 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 ); 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 public class Run_Ex3 { public static void main( String [] args ) { JFrame f = new JFrame(); f.settitle( "Example" ); f.setsize( 300, 300 ); f.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); public class Ex3_Panel extends JPanel { private ImageIcon img; private boolean face = true; public Ex3_Panel() { img = new ImageIcon( "girl.jpg" ); setbackground( Color.ORANGE ); addmouselistener( new Rat() ); Container pane = f.getcontentpane(); pane.setlayout( new BorderLayout() ); Ex3_Panel p = new Ex3_Panel (); pane.add( p, BorderLayout.CENTER ); f.setvisible( true ); 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( "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. public class Run_App3 extends JApplet{ public void init() { Container pane = getcontentpane(); pane.setlayout( new BorderLayout()); Ex3_Panel p = new Ex3_Panel (); pane.add( p, BorderLayout.CENTER ); public class Ex3_Panel extends JPanel { private ImageIcon img; private boolean face = true; public Ex3_Panel( ) { img = new ImageIcon( getclass().getresource( "girl.jpg" ) ); setbackground( Color.ORANGE ); addmouselistener( new Rat() ); 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();