How to Convert an Application into an Applet.



Similar documents
public class Craps extends JFrame implements ActionListener { final int WON = 0,LOST =1, CONTINUE = 2;

Graphical User Interfaces

CS 335 Lecture 06 Java Programming GUI and Swing

5.17 GUI. Xiaoyi Jiang Informatik I Grundlagen der Programmierung


Using A Frame for Output

GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC).

Programming with Java GUI components

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

method is never called because it is automatically called by the window manager. An example of overriding the paint() method in an Applet follows:

Packaging and Deploying Java Projects in Forte

LAYOUT MANAGERS. Layout Managers Page 1. java.lang.object. java.awt.component. java.awt.container. java.awt.window. java.awt.panel

How To Program In Java (Ipt) With A Bean And An Animated Object In A Powerpoint (For A Powerbook)

There are some important differences between an applet and a standalone Java application, including the following:

11. Applets, normal window applications, packaging and sharing your work

Introduction to Java Applets (Deitel chapter 3)

Mouse Event Handling (cont.)

How To Build A Swing Program In Java.Java.Netbeans.Netcode.Com (For Windows) (For Linux) (Java) (Javax) (Windows) (Powerpoint) (Netbeans) (Sun) (

Essentials of the Java(TM) Programming Language, Part 1

The Basic Java Applet and JApplet

Assignment # 2: Design Patterns and GUIs

GUI Components: Part 2

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus

Lab 1A. Create a simple Java application using JBuilder. Part 1: make the simplest Java application Hello World 1. Start Jbuilder. 2.

Swing. A Quick Tutorial on Programming Swing Applications

How Scala Improved Our Java

Tutorial: Time Of Day Part 2 GUI Design in NetBeans

Essentials of the Java Programming Language

Here's the code for our first Applet which will display 'I love Java' as a message in a Web page

Homework/Program #5 Solutions

JiST Graphical User Interface Event Viewer. Mark Fong

LAB4 Making Classes and Objects

Java is commonly used for deploying applications across a network. Compiled Java code

Flash MX Image Animation

Lab 9. Spam, Spam, Spam. Handout 11 CSCI 134: Spring, To gain experience with Strings. Objective

Making a Web Page with Microsoft Publisher 2003

An Overview of Java. overview-1

Hypercosm. Studio.

Konzepte objektorientierter Programmierung

How To Write A Program For The Web In Java (Java)

Nexawebホワイトペーパー. Developing with Nexaweb ~ Nexaweb to Improve Development Productivity and Maintainability

JIDE Action Framework Developer Guide

Extending Desktop Applications to the Web

// Correntista. //Conta Corrente. package Banco; public class Correntista { String nome, sobrenome; int cpf;

Java applets. SwIG Jing He

understand how image maps can enhance a design and make a site more interactive know how to create an image map easily with Dreamweaver

GUI Event-Driven Programming

public class Application extends JFrame implements ChangeListener, WindowListener, MouseListener, MouseMotionListener {

Yosemite National Park, California. CSE 114 Computer Science I Inheritance

Java GUI Programming. Building the GUI for the Microsoft Windows Calculator Lecture 2. Des Traynor 2005

WEEK 2 DAY 14. Writing Java Applets and Java Web Start Applications

Java Appletek II. Applet GUI

Interactive Programs and Graphics in Java

(These instructions are only meant to get you started. They do not include advanced features.)

file://c:\dokumente und Einstellungen\Marco Favorito\Desktop\ScanCmds.html

Java with Eclipse: Setup & Getting Started

Using and the Internet

Searching your Archive in Outlook (Normal)

creating a text-based editor for eclipse

CB Advanced: Innovative Document Templates

Using FileMaker Pro with Microsoft Office

Dashboard Skin Tutorial. For ETS2 HTML5 Mobile Dashboard v3.0.2

Karsten Lentzsch JGoodies SWING WITH STYLE

Java SE 6 Update 10. la piattaforma Java per le RIA. Corrado De Bari. Sun Microsystems Italia Spa. Software & Java Ambassador

Fireworks 3 Animation and Rollovers

Advanced Network Programming Lab using Java. Angelos Stavrou

Web Services using Tomcat and Eclipse

CS506 Web Design and Development Solved Online Quiz No. 01

Creating Web Pages with Microsoft FrontPage

STATGRAPHICS Online. Statistical Analysis and Data Visualization System. Revised 6/21/2012. Copyright 2012 by StatPoint Technologies, Inc.

With a single download, the ADT Bundle includes everything you need to begin developing apps:

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

Appendix M: Introduction to Microsoft Visual C Express Edition

An Informational User Guide for: Web Conferencing

Introduction to MS WINDOWS XP

Appendix K Introduction to Microsoft Visual C++ 6.0

Website Development Komodo Editor and HTML Intro

CS 170 Java Programming 1. Welcome to CS 170. All about CS 170 The CS 170 Online Materials Java Mechanics: Your First Program

DHBW Karlsruhe, Vorlesung Programmieren, Remote Musterlösungen

Customizing the SSOSessionTimeout.jsp page for Kofax Front Office Server 3.5.2

Module 1. 4 Login-Send Message to Teacher

Event-Driven Programming

Software for Producing Rack Layouts and Purchase Orders

Going Above and Beyond

KFUPM. Web Content Management System powered by SharePoint

CS170 Lab 11 Abstract Data Types & Objects

LAB 1: Getting started with WebMatrix. Introduction. Creating a new database. M1G505190: Introduction to Database Development

MICROSOFT OUTLOOK 2010 READ, ORGANIZE, SEND AND RESPONSE S

Contents. Launching FrontPage Working with the FrontPage Interface... 3 View Options... 4 The Folders List... 5 The Page View Frame...

Summer Internship 2013

Adobe Illustrator CS6. Illustrating Innovative Web Design

J a v a Quiz (Unit 3, Test 0 Practice)

Transcription:

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();