Home / Articles / Adobe Flash / Tools of the Trade: Flash meets Java with Transform SWF and JFlashPlayer

Tools of the Trade: Flash meets Java with Transform SWF and JFlashPlayer

  • Date: Feb 17, 2006.

Contents

  1. Create and update Flash movies with Transform SWF
  2. Play and Control Flash Movies with JFlashPlayer
  3. Conclusion

Article Description

Perhaps some of your Java applications can benefit from supporting Flash. Jeff Friesen introduces two tools that support Flash in a Java context: Transform SWF and JFlashPlayer. Transform SWF is useful for creating new Flash movies and updating existing Flash movies. JFlashPlayer gives you the ability to integrate a Flash movie player into your software. In this article, you're introduced to three Java applications that show you how to use these nifty tools.

Play and Control Flash Movies with JFlashPlayer

VersaEdge Software has created a tool for playing and controlling Flash movies from Java applications and applets that run on Windows platforms. You can download a trial version of this JFlashPlayer: Java Flash Player API For Windows tool by clicking the Download Free Trial link on VersaEdge’s Java APIs: JFlashPlayer Web page. After exploring the trial version, you might want to purchase a license to use JFlashPlayer in your commercial code. Four commercial licenses are available for purchase. Their costs, purchase links, and other details are specified on the JFlashPlayer Web page.

After downloading and unzipping JFlashPlayer’s trial version distribution file (jflashtrial.zip), install this tool by moving its home directory to a more appropriate directory (c:\jflashtrial, for example) by adding jflashtrial’s jflash.jar Jar file to your CLASSPATH (set classpath=%classpath%;c:\jflashtrial\jflash.jar;) and by making sure that jflashtrial’s atl2k.dll (a required library for Windows NT/2000/XP), atl98.dll (a required library for Windows 95/98/ME), and jflash.dll DLL files are accessible via your PATH environment variable (set path=%path%;c:\jflashtrial accomplishes that task). In addition to being properly installed on your platform, JFlashPlayer needs Macromedia’s flash.ocx ActiveX control. If this file has not been installed, JFlashPlayer cannot play Flash movies. I’ll talk about flash.ocx later in this article.

JFlashPlayer includes an example SampleFrame application that shows you how to integrate a Flash movie player with a Java application. Furthermore, this application demonstrates some of the features that the Java Flash Player API makes available, such as listening for Flash events, setting a Flash variable, playing and stopping a Flash movie, and determining whether or not the movie should run in a loop. Run this application by invoking the runsample.bat file, which locates in jflashtrial’s sample subdirectory. (After including the DLL files in the PATH, that batch file executes java -classpath ..\jflash.jar;. SampleFrame.) The SampleFrame application first reveals a dialog box that plays a "Welcome To JFlashPlayer" Flash movie. After you click the dialog box’s OK button, the window shown in Figure 2 appears. The top portion of this window displays various controls; the rest of the window presents the current frame in a sample Flash movie.

Figure 2

Figure 2 The SampleFrame application demonstrates various classes and methods in the Java Flash Player API.

The SampleFrame application’s SampleFrame.java source code—which locates in the sample subdirectory—references two of the Java Flash Player API’s three classes and that API’s solitary interface. These classes and interface are stored in package jflashplayer, corresponding to the jflash.jar Jar file:

  • FlashPanel is the package’s main class. This java.awt.Panel subclass identifies a component that integrates a Flash movie player into a Java-based GUI and makes it possible to play Flash movies within the component’s bounds. There are eight constructors to choose from when creating a FlashPanel.
  • FlashPanelListener is the package’s solitary interface. This interface presents a single public void FSCommand(String command, String arg) method that is called every time the Flash player invokes the ActionGetURL action, and that action has a URL beginning with FSCommand. For example, the movie.swf file played by SampleFrame identifies two buttons. Each button, when clicked, invokes an ActionGetURL action. For one of these actions, its URL is set to FSCommand:javaExecute, and its target window is set to the empty string. When this action executes, the FSCommand() method is called where the value of command is set to javaExecute and the value of arg is set to the empty string. For the other action, its URL is set to FSCommand:javaLink, and its target window is set to http://www.javaapis.com/. When this action executes, FSCommand() is called: command is set to javaLink and arg is set to http://www.javaapis.com/.
  • JFlashInvalidFlashException describes an exception that is thrown from one of FlashPanel’s constructors when you call FlashPanel’s public static void setRequiredFlashVersion(String ver) method with a specific version number as the String argument prior to invoking the FlashPanel constructor, and the required version of Flash is not available.
  • JFlashLibraryLoadFailedException describes an exception that is thrown from FlashPanel’s public static boolean hasFlashVersion(String version) method if one or more of atl2k.dll, atl98.dll, and jflash.dll is missing.

A JFlashPlayer-based Java application requires that a FlashPanel component be added to the GUI. But before you create the FlashPanel object, you need to make sure that a flash.ocx ActiveX control (the Flash movie player) is present—JFlashPlayer’s DLLs ultimately communicate with flash.ocx—and that flash.ocx is capable of playing your Flash movie(s). If there is no appropriate flash.ocx on your platform, FlashPanel lets you install that control and even uninstall the control before the application exits. (It’s a good idea to ask the user for permission before installing a specific version of flash.ocx.) The following code fragment shows you how to determine the existence of a specific version of flash.ocx and install that file (which you would presumably distribute with your application) if the required flash.ocx file does not exist:

if (!FlashPanel.hasFlashVersion ("7"))
  if (!FlashPanel.installFlash (new File ("flash.ocx")))
  {
    System.err.println ("Appropriate flash.ocx file not available");
    return;
  }

The code fragment calls hasFlashVersion() to determine whether flash.ocx version 7 (or higher) is present. That method returns true if at least version 7 is present. However, if a lower version of flash.ocx is present, or if flash.ocx is not present, that method returns false and FlashPanel’s public static boolean installFlash(java.io.File flashocx) method is called to install the proper flash.ocx file. That method returns true if it successfully installs flash.ocx. But if it fails, false returns, an error message outputs to the console, and the currently executing method is terminated.

After executing the previous code fragment, you are guaranteed that the version of flash.ocx is present. However, if you want additional assurance or if you choose not to test installFlash()’s return value, you would call setRequiredFlashVersion(), specifying the desired version of your Flash movie. If you call setRequiredFlashVersion() with a version number that is not supported by flash.ocx, the FlashPanel constructors throw JFlashInvalidFlashException objects. The code fragment below demonstrates a call to this method, which indicates that you require version 7 of the flash.ocx file to run your Flash movie(s):

FlashPanel.setRequiredFlashVersion ("7");

At this point, you can go ahead and create your FlashPanel component. For example, you could call the public FlashPanel(File f, java.awt.Image image) constructor to create a FlashPanel and start playing the Flash movie identified by the f-referenced File object. If any of JFlashPlayer’s DLL files is missing, if the appropriate flash.ocx file is not present, or if the Flash movie file cannot be found, FlashPanel displays the alternate image, stretched to the size of its boundaries. The following code fragment, which I excerpted from SampleFrame.java, returns a custom alternate Image and invokes this constructor to establish a FlashPanel for the welcome.swf movie:

Image imageWelcome = getImageOfString ("Welcome", Color.blue);

FlashPanel welcomePanel = new FlashPanel (new File ("welcome.swf"), imageWelcome);

After creating the FlashPanel component, you’ll want to add it to your GUI. The code fragment below, which I also excerpted from SampleFrame.java, adds this component to a JPanel and then passes that JPanel to one of javax.swing.JOptionPane’s dialogs:

JPanel jPanelWelcome = new JPanel (new BorderLayout ());
jPanelWelcome.add (welcomePanel, BorderLayout.CENTER);
jPanelWelcome.setPreferredSize (new Dimension (200, 150));
JOptionPane.showMessageDialog (null, jPanelWelcome, "Welcome To JFlashPlayer", JOptionPane.PLAIN_MESSAGE);

In response to your application’s GUI events, you can now call FlashPanel’s public void stop() method to stop the movie, public void back() method to move back one frame in the movie, public void forward() method to move ahead one frame in the movie, public void rewind() method to rewind the movie, public void play() method to restart the movie from its new location, public void setLoop(boolean loop) method to keep playing the movie in a loop (if loop is true), and so on.

If you installed a flash.ocx file, you will want to remove it before your application exits. FlashPanel makes this possible by providing the public static boolean uninstallFlash(File flashocx) method. Just as installFlash() returns true if installation succeeds, uninstallFlash() returns true if uninstallation is successful. You should set a Boolean flag to true when installing flash.ocx, and check this flag before uninstalling that file, to make certain that you do not accidentally uninstall what you did not install. The following code fragment demonstrates setting and testing this flag:

if (!FlashPanel.hasFlashVersion ("7"))
  if (!FlashPanel.installFlash (new File ("flash.ocx")))
  {
    System.err.println ("Appropriate flash.ocx file not available");
    return;
  }
  else
    fInstalled = true;

// ...

if (fInstalled)
  FlashPanel.uninstallFlash (new File ("flash.ocx"));

At some point, you will want to experiment with the aforementioned methods. To help get you started, I have put together a Java application that presents a framework for integrating a Flash movie player into the application’s Swing-based GUI. Listing 3 presents that application’s Flasher.java source code.

Listing 3 Flasher.java

// Flasher.java

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.File;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.filechooser.*;
import jflashplayer.*;

public class Flasher extends JFrame
{
  FlashPanel fp;
  JFileChooser fc;

  public Flasher (String title)
  {
   // Pass title to superclass.

   super (title);

   // Terminate application when user clicks x button in titlebar.

   setDefaultCloseOperation (EXIT_ON_CLOSE);

   // Create a new file chooser and make sure it starts up displaying SWF
   // files in the current directory.

   fc = new JFileChooser ();
   fc.setCurrentDirectory (new File ("."));

   // Make sure that only directories and files ending with the .swf file
   // extension are displayed.

   fc.setFileFilter (new SWFFilter ());

   // Make sure that the user cannot select the "All Files" entry in the
   // "Files of Type" drop-down listbox.

   fc.setAcceptAllFileFilterUsed (false);

   // Create a File menu with menu items to open movies and exit this
   // application. Because FlashPanel is a heavyweight component, and
   // because JMenus typically associate with lightweight popup menus that
   // are hidden behind heavyweight components, we must disable the File
   // JMenu’s lightweight popup. As a result, the popup will be heavyweight,
   // so that it is no hidden behind the FlashPanel.

   JMenu menuFile = new JMenu ("File");
   menuFile.getPopupMenu ().setLightWeightPopupEnabled (false);

   // Install the Open menu item on the File menu and register the action
   // listener to open the user-selected movie.

   ActionListener al;

   JMenuItem mi = new JMenuItem ("Open...");
   al = new ActionListener ()
      {
        public void actionPerformed (ActionEvent e)
        {
         if (fc.showOpenDialog (Flasher.this) ==
           JFileChooser.APPROVE_OPTION)
           try
           {
             fp.setMovie (fc.getSelectedFile ());
           }
           catch (Exception e2)
           {
             JOptionPane.showMessageDialog (Flasher.this,
                             e2.getMessage (),
                             "Flasher",
                             JOptionPane.
                             ERROR_MESSAGE);
           }
        }
      };

   mi.addActionListener (al);
   menuFile.add (mi);

   // Separate the Open menu item from the Exit movie item.

   menuFile.addSeparator ();

   // Install the Exit menu item on the File menu and register the action
   // listener to terminate the application.

   mi = new JMenuItem ("Exit");
   mi.addActionListener (new ActionListener ()
              {
                public void actionPerformed (ActionEvent e)
                {
                  dispose ();
                }
              });
   menuFile.add (mi);

   // Create a menu bar to hold the file menu, add the file menu to the
   // menu bar, and register the menu bar as this application’s menu bar.

   JMenuBar mb = new JMenuBar ();
   mb.add (menuFile);
   setJMenuBar (mb);

   try
   {
     // Attempt to create a FlashPanel component.

     fp = new FlashPanel (new File ("."));

     // Add component to application’s main window.

     getContentPane ().add (fp);
   }
   catch (Exception e)
   {
     e.printStackTrace ();
   }

   // Establish a default size for viewing Flash movies. User can always
   // drag the main window’s borders or maximize the window to make the
   // window bigger.

   setSize (400, 400);

   // Display the GUI.

   setVisible (true);
  }

  public static void main (String [] args)
  {
   try
   {
     // Verify that at least version 7 of flash.ocx is present.

     if (!FlashPanel.hasFlashVersion ("7"))
     {
       System.err.println ("Required version of Flash not available");
       return;
     }
   }
   catch (JFlashLibraryLoadFailedException e)
   {
     System.err.println ("One or more JFlashPlayer DLLs not found");
     return;
   }

   // If we make it here, the required flash.ocx is present, and the
   // JFlashPlayer DLLs are also present. Go ahead and create the GUI.

   new Flasher ("Flasher");
  }
}

class SWFFilter extends FileFilter
{
  // Accept all directories and swf files.

  public boolean accept (File f)
  {
   if (f.isDirectory ())
     return true;

   // Check extension for swf.

   String s = f.getName ();
   int i = s.lastIndexOf (’.’);

   if (i > 0 && i < s.length () - 1)
     if (s.substring (i + 1).toLowerCase ().equals ("swf"))
       return true;

   return false;
  }
  
  public String getDescription ()
  {
   return "Accepts swf files only.";
  }
}

Because Listing 3 is extensively commented, I haven’t much to say about the source code. However, take a look at fp = new FlashPanel (new File ("."));. That line of code creates a FlashPanel without loading a Flash movie. (You could also substitute a single space for the period character to accomplish the same task. Anything else would probably result in a java.io.FileNotFoundException.) Whenever you need to create a FlashPanel and don’t want to immediately load a Flash movie into that component, you can use the previous line of code to accomplish that task.

After compiling Listing 3, run this application. Select Open from the File menu and choose a SWF file. The Flash movie stored in that SWF file will start to play. For example, suppose you previously ran UpdateSquareCircle to modify squarecircle.swf and you now select the modified squarecircle.swf file. In response, you will see the blue square that appears in Figure 3.

Figure 3

Figure 3 A blue square moves in a circle over a green background.

I purposely minimized Listing 3’s functionality to give you some work to do. For example, you could introduce a Player menu with options for stopping, playing, rewinding, moving forward, moving backward, and choosing whether or not the movie plays in a loop. I’m sure you can think of other features to add to this application, as well.

3. Conclusion | Next Section Previous Section

Adobe Press Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Adobe Press and its family of brands. I can unsubscribe at any time.

Overview

Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Adobe Press products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security

Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children

This site is not directed to children under the age of 13.

Marketing

Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out

Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.adobepress.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links

This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020