Webcam Chat QuickBooks Advice international calling cards international phone cards
JavaBeat Java Books Certifications Certifications Kits Articles Tutorials Tips QNA Book Store Interview Questions SCJP 1.5 SCJP 1.6 SCWCD 5.0 SCBCD 5.0 SCEA SCJA Feeds

JavaFX Media

Author : PacktPub
Topic : books javafx 
Pages :
Submit Your Blog Feedback Request Article Print Email

Title : JavaFX Media
Publisher : PacktPub
Topic : books
Related : Hibernate, Spring, Struts, ejb
Javabeat : Tips, Java / J2EE Tutorials, Certifications

JavaFX 1.2 Application Development Cookbook

This book is a collection of code recipes, examples, and informative discourses designed to enable the reader to get started with creating JavaFX application quickly. The book is arranged as a series of loosely related code recipes that a reader can easily select to fit his or her needs. It exposes readers to a great variety of topics designed to satisfy different skill levels. Readers will learn about the language, animation techniques, paints, effects, JavaFX controls, integration of Swing components, styling with CSS, audio/video, deployment practices, and JavaFX integration with Adobe design tools.

What This Book Covers

Chapter 1, Getting Started with JavaFX... This is the "getting started" chapter of the book. It provides introductory materials to the platform, including installation instructions to get your environment set up. It also covers language basics such as classes, data types, function usage, variable declaration, data binding, triggers, Java and JavaFX integration.

Chapter 2, Creating JavaFX Applications... This chapter covers the essential building blocks of the JavaFX application framework, including primitive shapes, path, text, constructive area geometry, mouse/keyboard input, custom node, and window styling.

Chapter 3, Transformations, Animations, and Effects... This chapter explores the animation capabilities supported in JavaFX. You start with the Transition API to quickly build simple animations. The material continues to cover the KeyFrame API for more advanced animation sequences. You will learn about colors, effects, and how to create your own custom paint and effects.

Chapter 4, Components and Skinning... This chapter is divided into two sections. The first section shows readers how to use the set of standard JavaFX controls. The chapter also shows how to embed Swing components in your JavaFX scene graph. You will also learn how to create your own custom visual controls. The second section of the chapter introduces the reader to JavaFX's support for CSS. The reader will learn how to style controls using inline and externalized CSS to create skins.

Chapter 5, JavaFX Media... One of the exciting features of JavaFX is its inherent support for multimedia. JavaFX includes support for rendering of images in multiple formats and support for playback of audio and video on all platforms where JavaFX is supported. In this chapter, readers learn how to display and manipulate images using the Image API. They will also learn how to playback both audio and video using the Media API. The chapter shows also how to create practical custom playback controls.

Chapter 6, Working with Data... JavaFX provides superb support for accessing and manipulating data both locally and remotely. In this chapter, readers are introduced to the Storage API for local data storage. It provides extensive coverage of JavaFX's HttpRequest API for accessing data on remote web servers. Readers will learn how to use JavaFX's XML and JSON parsers to build RESTful client mashups using popular services such as Google Map, Yahoo Weather, and Zillow Listing. Finally, the chapter explores JavaFX's built-in Chart API for data visualization.

Chapter 7, Deployment and Integration... This chapter provides coverage of the deployment mechanism supported by JavaFX. Readers will learn how to properly build and package their applications to target the different runtimes supported by JavaFX, including the web browser and the desktop. Readers learn how to create Java Web Startready applications using the build tools included in the SDK. The chapter shows how to write JavaScript that communicates with your JavaFX applet while running within the browser.

Chapter 8, The JavaFX Production Suite... This chapter covers JavaFX's integral support for designer tools from Adobe, including Illustrator and Photoshop. Readers are walked through the process of exporting creative assets using the JavaFX Production Suite plugins available for these tools. The chapters also shows how to integrate exported objects from Photoshop and Illustrator into JavaFX.

JavaFX Media

In this chapter, we will cover the following topics:

  • Accessing media assets
  • Loading and displaying images with ImageView
  • Applying effects and transformations to images
  • Creating image effects with blending
  • Playing audio with MediaPlayer
  • Playing video with MediaView
  • Creating a media playback component

Introduction

One of the most celebrated features of JavaFX is its inherent support for media playback. As of version 1.2, JavaFX has the ability to seamlessly load images in different formats, play audio, and play video in several formats using its built-in components. To achieve platform independence and performance, the support for media playback in JavaFX is implemented as a two-tiered strategy:

  • Platform-independent APIs— the JavaFX SDK comes with a media API designed to provide a uniform set of interfaces to media functionalities. Part of the platform-independence offerings include a portable codec (On2's VP6), which will play on all platforms where JavaFX media playback is supported.
  • Platform-dependent implementations— to boost media playback performance, JavaFX also has the ability to use the native media engine supported by the underlying OS. For instance, playback on the Windows platform may be rendered by the Windows DirectShow media engine (see next recipe).

This chapter shows you how to use the supported media rendering components, including ImageView, MediaPlayer, and MediaView. These components provide high-level APIs that let developers create applications with engaging and interactive media content.

Accessing media assets

In previous chapters, you have seen the use of variable _DIR__ when accessing local resources, but little detail was offered about its purpose and how it works. So, what does that special variable store? In this recipe, we will explore how to use the __DIR__ special variable and other means of loading resources locally or remotely.

Getting ready

The concepts presented in this recipe are used widely throughout the JavaFX application framework when pointing to resources. In general, classes that point to a local or remote resource uses a string representation of a URL where the resource is stored. This is especially true for the ImageView and MediaPlayer classes discussed in this chapter.

How to do it...

This recipe shows you three ways of creating a URL to point to a local or remote resource used by a JavaFX application. The full listing of the code presented here can be found in ch05/ source-code/src/UrlAccess.fx.

Using the __DIR__ pseudo-variable to access assets as packaged resources:


	var resImage = "{__DIR__}image.png";

Using a direct reference to a local file:


	var localImage =
		"file:/users/home/vladimir/javafx/ch005/source-code/src/image.png";

Using a URL to access a remote file:


	var remoteImage = "http://www.flickr.com/3201/2905493571_a6db13ce1b_d.
	jpg"

How it works...

Loading media assets in JavaFX requires the use of a well-formatted URL that points to the location of the resources. For instance, both the Image and the Media classes (covered later in this chapter) require a URL string to locate and load the resource to be rendered. The URL must be an absolute path that specifies the fully-realized scheme, device, and resource location.

The previous code snippets show the following three ways of accessing resources in JavaFX:

  • __DIR__ pseudo-variable— often, you will see the use of JavaFX's pseudo variable __DIR__, used when specifying the location of a resource. It is a special variable that stores the String value of the directory where the executing class that referenced __DIR__ is located. This is valuable, especially when the resource is embedded in the application's JAR file. At runtime, __DIR__ stores the location of the resource in the JAR file, making it accessible for reading as a stream. In the previous code, for example, the expression {__DIR__}image.png explodes as jar:file:/users /home/vladimir/javafx/ch005/source-code/dist/source-code.jar! /image.png.
  • Direct reference to local resources—when the application is deployed as a desktop application, you can specify the location of your resources using URLs that provides the absolute path to where the resources are located. In our code, we use file:/users/ home/vladimir/javafx/ch005/source-code/src/image.png as the absolute fully qualified path to the image file image.png.
  • Direct reference to remote resources—finally, when loading media assets, you are able to specify the path of a fully-qualified URL to a remote resource using HTTP. As long as there are no subsequent permissions required, classes such as Image and Media are able to pull down the resource with no problem. For our code, we use a URL to a Flickr image http://www.flickr.com/3201/2905493571_ a6db13ce1b_d.jpg.

There's more...

Besides __DIR__, JavaFX provides the _FILE__ pseudo variable as well. As you may well guess, __FILE__ resolves to the fully qualified path of the of the JavaFX script file that contains the __FILE__ pseudo variable. At runtime, when your application is compiled, this will be the script class that contains the __FILE__ reference.

Loading and displaying images with ImageView

If you have already checked out recipes in previous chapters, you know by now that JavaFX provides classes, which make it easy to load and display images. This recipe takes a closer look at the mechanics provided by the Image API to load and display images in your JavaFX applications.

Getting ready

This recipe uses classes from the Image API located in the javafx.scene.image package. Using this API, you are able to configure, load, and control how your images are displayed using the classes Image and ImageView . For this recipe, we will build a simple image browser to illustrate the concepts presented here. The browser allows users to load an image by providing its URL. You will use standard JavaFX controls, such as text boxes and buttons, to build the GUI. If you are not familiar with the standard GUI controls, review the recipe Creating a form with JavaFX controls from Chapter 4, Components and Skinning.

How to do it...

The code given next has been shortened to illustrate the essential portions involved in loading and displaying an image. You can get a full listing of the code from ch05/source-code/ src/image/ImageBrowserSimpleDemo.fx.


	def w = 800;
	def h = 600;
	var scene:Scene;
	def maxW = w * 0.9;
	def maxH = h * 0.9;
	def imgView:ImageView = ImageView{
		preserveRatio:true
		fitWidth: maxW fitHeight:maxH
		layoutX:(w-maxW)/2 layoutY:(h-maxH)/2
	};
	function loadImg(){
		imgView.image = Image{
			url:(scene.lookup("addr") as TextBox).text
			backgroundLoading:true
			placeholder:Image{url:"{__DIR__}loading.jpg"}
		}
	}
	def addrBar = Group{
		layoutX: 20
		layoutY: 20
		content:HBox {
			nodeVPos:VPos.CENTER
			spacing:7
			content:[
				Label{text:"Image URL:" textFill:Color.SILVER}
				TextBox{id:"addr" columns:80 promptText:"http://"
					action:function(){loadImg()}
				}
				Button{id:"btnGo" text:"Get Image"
					action:function(){loadImg()}
				}
			]
		}
	}

When the variables imgView and addrBar are placed on the scene and the application is executed, you will get the results as shown in the following screenshot:

The image shown in this screenshot is licensed under creative common. For additional information and licensing details, go to http://www.flickr.com/photos/ motleypixel/2905493571/sizes/m/.

How it works...

Loading and displaying images in JavaFX involves two classes, Image and ImageView. While class Image is responsible for accessing and managing the binary stream of the image, ImageView, on the other hand, is of the type Node and is responsible for displaying the loaded image on the scene. The code presented in this recipe lets the user enter a URL for an image and loads the image on the screen. Let's take a closer look at the code and how it works:

  • The ImageView—the first significant item to notice is the declaration of an ImageView instance assigned to the variable imgView. This is the component that will display the image on the scene when it is fully loaded. We specify the properties fitWidth, fitHeight, and preserveRatio . These properties will cause imgView to stretch (if the image is smaller than specified) or shrink (if the image is larger than specified) while preserving the aspect ratio of the image.
  • Image URL bar— the form that captures the URL of the image to load is grouped in the Group instance variable addrBar. The form consists of a Label, a TextBox, and a Button instance. The TextBox instance has several properties set, including id="addr", which allows us to find a reference to it in the code. Both the TextBox and the Button instances have their action properties defined as a function that invokes function loadImg(). Therefore, when the TextBox has focus and the Enter key is pressed, or when the Button instance is clicked on, the image will be loaded.
  • Loading the image—the image is loaded by calling the function l oadImg(). It assigns an instance of Image to imgView.image. For the Image.url property, we use the Scene.lookup(id:String) function to retrieve an instance of the TextBox using its id of addr. For images that may take a while to load, we set up the following two properties:
    • To ensure that the application does not hang while the image loads, the property backgroundLoading:Boolean is set to true. This causes the GUI to remain responsive while an image loads.
    • The property p laceholder:Image is used to specify a local image to use while the remote image is loading, as shown in the previous screenshot. For example, we use the local image {__DIR__} loading.png. It gets loaded immediately and remains on the screen while the remote image loads. When the remote image is loaded, it replaces the placeholder image.

There's more...

Format support

As of version 1.2, JavaFX has inherent supports for the most popular image formats (popularity here = web-supported), which includes PNG, JPG, BMP, and GIF. If you have requirements for formats other than these, such as TIFF for instance, you will have to take matters into your own hands and use external image libraries such as Java Advanced Imaging (JAI) API (not covered here).

Asynchronous loading issues

As mentioned in the previous section, when you are loading images from locations with high latency (over the network for instance), you can use the asynchronous background-loading option for your image. This causes the image-loading operation to occur in a separate execution thread to keep your GUI responsive.

This, however, presents an issue, whereby if you want to determine the dimensions of the image (which is available only after the image is fully downloaded), it will report zero when loading asynchronously, as shown in the next segment:


	def img = Image{
		url:"http://someimage.com/img.png"
		backgroundLoading:true
	}//does not wait here, it continues to next line
	println (img.width); // prints 0

This is because the image is still being downloaded on the Image thread, and the main GUI thread did not wait for completion and continues with its execution. Therefore, when we query the property width of Image, it will be zero.

Unfortunately in version 1.2, the Image class does not offer event notification functions to know when image is done loading. If your code relies on the actual size of the image to be known, you must block with asynchronous loading (by setting backgroundLoading = false) to wait for the image to download and get the size. Another way around is to specify the size of the image yourself by specifying the dimensions (see next sub-section on Image resize and aspect ratio).

Image resize and aspect ratio

Another feature supported by Image and ImageView is the automatic resizing of the image. The Image class will attempt to resize the image when a value is provided for the properties. width:Number or height:Number. ImageView will attempt to do the same when the properties fitWidth:Number and fitHeight:Number are specified. Both classes support property preserveRation:Boolean, which forces the resize operation to maintain the aspect ratio of the original image while resizing to the specified dimensions as shown next:


	def imgView:ImageView = ImageView{
		preserveRatio:true
		fitWidth: 200
	};

The previous code will resize the image to a width of 200 pixels. Because the preserveRatio property is true, the height of the image is automatically calculated. This is useful especially if you do not know the actual size of the image ahead of time (see previous section).

See also

  • Chapter 4—Creating a form with JavaFX controls
  • Introduction
  • Accessing media assets

Submit Your Blog Feedback Request Article Print Email

Related Articles


JavaBeat Website (2004-2011), India
javabeat | advertise | about us | contact | useful resources
Copyright (2004 - 2011), JavaBeat


Technology Blogs
Technology blogs Technology Blogs
blog log