Blakes 21 Days Chapter 14 Document
Day 14, Developing Swing Applications
- Top
- 391 The first exposure many people had to the Java programming language was applets, small, security-restricted Java programs that run on web pages.
- Java Web start, a protocol for downloading and running Java programs, makes it possible to launch applications from a web page as if they were applets.
- 391 Today, you learn how to create these web-launched Java programs as you explore the following topics:
- How to install and run Java applications in a web browser
- How to publish your application's files and deploy it
- How Swing applications can run into performance slowdowns on time-consuming tasks
- How to address these problems using SwingWorker, a class that performs Swing work in its own thread.
Java Web Start
- Top
- 392 One of the issues you must deal with as a Java programmer is how to make your software available to your users.
- 392 Java applications require a Java Virtual Machine (JVM), so one must be included with the application, previously installed on a computer, or installed by users.
- The easiest solution (for you) is to require that users download and install the Java Runtime Envitonment from Oracle's website at www.java.com
- 392 Regardless of how you deal with the requirement for a JVM, you distribute an application like any other program,
- making it available for download, distributing it on a CD, or using some other means.
- A user must run an installation program to set it up, if one is available, or copy the files and folders manually.
- Top
- 392 Java eases the challenges of software deployment with Java Web Start, a way to run Java applications presented on a web page and stored on a web server.
- Here's how it works:
- A programmer packages an application and all the files it needs into a JAR archive,
- along with a file that uses the Java Network Launching Protocol (JNLP), part of Java Web Start.
- The file is stored on a web server with a web page that links to that file.
- A user loads the page with a browser and clicks the link.
- If the user does not have the Java Runtime Environment, a dialog box opens, asking whether the JRE should be downloaded and installed.
- The full installation is from 40 to 70MB in size (depending on operating system).
- The Java Runtime Environment installs and runs the program, opening new frames and other interface components like any other application.
- The program is saved in a cache, so it can be run again later without requiring installation.
- 392 To see Java Web Start in action, visit Oracle's Java Web Start site at www.oracle.com/technetwork/java/javase/javawebstart
- Click the Code Samples & Apps link, and then the Demos link.
- The Web Start Demos page, shown in Figure 14.1, contains pictures of several Java applications, each with a Click to Launch! button you can use to run the application.
- 392 Click the Click to Launch! button of one of the applications.
- If you don't have the Java Runtime Environment yet, a dialog box opens, asking whether you want to download and install it.
Figure 14.1 - Presenting Web Start applications on a web page. - goes here
- Top
- 393 The runtime environment includes the Java Plug-in, a JVM that adds support for the current version of the language to browsers.
- The environment also can be used to run applications, regardless of whether they use Java Web Start.
- 393 When an application is run using Java Web Start, a title screen appears briefly, and then the application's graphical user interface appears.
- 393 NOTE: If you have installed NetBeans or the JDK, you probably have the Java Runtime Environment on your computer already.
- 393 Figure 14.2 shows one of the demo applications that Oracle offers, a military strategy game in which three black dots attempt to keep a red dot from moving into their territory.
- 393 As you can see in Figure 14.2, the application looks no different from any other application.
- Unlike applets, which are presented in conjunction with a web page, applications launched with Java Web Start run in their own windows, as if they were run from a command line.
Figure 14.2 - Running a Java Web Start application. - goes here
- Top
- 394 One thing that's different about a Java Web Start application is the security that can be offered to users.
- When an application attempts to do something, such as read or write files, the user can be asked for permission.
- 394 For example, another of the demo programs is a text editor.
- When you try to save a file for the first time with this application, the Security Warning dialog box opens, as shown in Figure 14.3
Figure 14.3 - Choosing an application's security privileges. - goes here
- Top
- 394 If the user does not permit something that requires such authorization, the application cannot function fully.
- The kinds of things that trigger a security dialog box are reading and writing files, loading network resources from servers other than the one hosting the program, and the like.
- 394 After Java Web Start has run an application, it is stored on a user's computer in a cache, enabling it to be run again later without installation.
- The only exception is when a new version of the application becomes available.
- In this case, the new version is downloaded and installed automatically in place of the existing one.
- 395 NOTE: Although you run a Java Web Start application for the first time using a web browser, that's not a requirement.
- The applications can be run from a desktop shortcut.
- 395 The default security restrictions in place for a Java Web Start application can be overridden if it is stored in a digitally signed Java archive.
- The user is presented with the signed security certificate, which documents the program's author and the certificate-granting authority vouching for its identity,
- and is asked whether to accept or reject it.
- The application won't run unless the certificate has been accepted.
Using Java Web Start
- Top
- 395 Any Java application can be run using Java Web Start as long as the web server that offers the application is configured to work with the technology
- and all the class files and other files it needs have been packaged together.
- 395 To prepare an application to use Java Web Start, you must save the application's files in a JAR file (Java archive),
- create a special Java Web Start configuration file for the application, and upload the files to the web server.
- 395 The configuration file that must be created uses JNLP, an Extensible Markup Language (XML) file format that specifies the application's main class file,
- its JAR archive, and other things about the program.
- 395 NOTE: XML is introduced during Day 20, "XML Web Services."
- Because the format of the JNLP files is relatively self-explanatory, you don't need to know much about XML to create a JNLP file.
- 395 The next project you will undertake is using Java Web Start to launch and run PageData, an application that displays information about web pages.
Creating a JNLP File
- Top
- 396 The first thing you must do is package all of an application's class file into a JAR file, along with any other files it needs.
- NetBeans creates a JAR file automatically for each project you build in the IDE.
- 396 Because you've been using one project for all the projects in the preceding 13 days (chapters), a new project is needed:
- Choose File, New Project. The New Project dialog appears.
- Choose Java in the Categories pane and Java Applications in the Projects pane, and then click Next. The New Java Application dialog opens.
- Enter PageData as the Project Name.
- Select the Create Main Class check box.
- Enter PageData in the text field next to Create Main Class.
- Click Finish.
- Top
- 396 The file PageData.java opens in NetBeands' source code editor with some starter code entered for you.
- Delete all this code and enter the code shown in Listing 14.1 as the PageData class in the com.java21days package.
Listing 14.1 The full Text of PageData.java
package com.java21days;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
public class PageData extends JFrame implements ActionListener,
Runnable {
Thread runner;
String[] headers = { "Content-Length", "Content-Type",
"Date", "Public", "Expires", "Last-Modified",
"Server" };
URL page;
JTextField url;
JLabel[] headerLabel = new JLabel[7];
JTextField[] header = new JTextField[7];
JButton readPage, clearPage, quitLoading;
JLabel status;
public PageData() {
super("Page Data");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLookAndFeel();
setLayout(new GridLayout(10, 1));
JPanel first = new JPanel();
first.setLayout(new FlowLayout(FlowLayout.RIGHT));
JLabel urlLabel = new JLabel("URL:");
url = new JTextField(22);
urlLabel.setLabelFor(url);
first.add(urlLabel);
first.add(url);
add(first);
JPanel second = new JPanel();
second.setLayout(new FlowLayout());
readPage = new JButton("Read Page");
clearPage = new JButton("Clear Fields");
quitLoading = new JButton("Quit Loading");
readPage.setMnemonic('r');
clearPage.setMnemonic('c');
quitLoading.setMnemonic('q');
readPage.setToolTipText("Begin Loading the Web Page");
clearPage.setToolTipText("Clear All Header Fields Below");
quitLoading.setToolTipText("Quit Loading the Web Page");
readPage.setEnabled(true);
clearPage.setEnabled(false);
quitLoading.setEnabled(false);
readPage.addActionListener(this);
clearPage.addActionListener(this);
quitLoading.addActionListener(this);
second.add(readPage);
second.add(clearPage);
second.add(quitLoading);
add(second);
JPanel[] row = new JPanel[7];
for (int i = 0; i < 7; i++) {
row[i] = new JPanel();
row[i].setLayout(new FlowLayout(FlowLayout.RIGHT));
headerLabel[i] = new JLabel(headers[i] + ":");
header[i] = new JTextField(22);
headerLabel[i].setLabelFor(header[i]);
row[i].add(headerLabel[i]);
row[i].add(header[i]);
add(row[i]);
}
JPanel last = new JPanel();
last.setLayout(new FlowLayout(FlowLayout.LEFT));
status = new JLabel("Enter a URL address to check.");
last.add(status);
add(last);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if (source == readPage) {
try {
page = new URL(url.getText());
if (runner == null) {
runner = new Thread(this);
runner.start();
}
quitLoading.setEnabled(true);
readPage.setEnabled(false);
}
catch (MalformedURLException e) {
status.setText("Bad URL: " + page);
}
} else if (source == clearPage) {
for (int i = 0; i < 7; i++)
header[i].setText("");
quitLoading.setEnabled(false);
readPage.setEnabled(true);
clearPage.setEnabled(false);
} else if (source == quitLoading) {
runner = null;
url.setText("");
quitLoading.setEnabled(false);
readPage.setEnabled(true);
clearPage.setEnabled(false);
}
}
public void run() {
URLConnection conn;
try {
conn = this.page.openConnection();
conn.connect();
status.setText("Connection opened ...");
for (int i = 0; i < 7; i++)
header[i].setText(conn.getHeaderField(headers[i]));
quitLoading.setEnabled(false);
clearPage.setEnabled(true);
status.setText("Done");
runner = null;
}
catch (IOException e) {
status.setText("IO Error:" + e.getMessage());
}
}
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
// ignore error
}
}
public static void main(String[] arguments) {
PageData frame = new PageData();
}
}
Build the Project
- Top
- 399 Build the Project Instructions
- After you've saved the project, build it in NetBeans by choosing Run, Clean and Build Project.
- This extra step is required because you will deploy this application on the Web instead of simply running it on your computer.
- 399 Explanation of the PageData Application
- The PageData application takes a web address (URL) as input and loads data associated with the page at that address.
- This program uses some networking techniques that will be explored fully during Day 17, "Communicating Across the Internet."
- 399 About the Icon
- Next, the application needs an icon that will be displayed when it is loaded and used in menus and desktops.
- The icon for a Java Web Start application can be in either GIF or JPEG format and should be 64 pixels wide by 64 pixels tall.
- 399 For this project, if you don't want to create a new icon, you can download pagedataicon.gif from the book's website.
- Go to www.java21days.com and open the Day 14 page.
- Right-click the pagedataicon.gif link and save the file to a folder on your computer.
- 399 Continue with the Instructions
- Next, click the Files tab to bring that pane to the front in NetBeans, as shown in Figure 14.4
- 399 Scroll down to the PageData folder icon, and drag pagedataicon.gif from that folder into NetBeans.
- The file appears in the Files listing, as shown in Figure 14.4
- 399 The final thing you must do is create the JNLP file that describes the application.
- Listing 14.2 is a JNLP file used to distribute the PageData application.
Figure 14.4 - Adding a file to a project in NetBeans. - goes here
- Top
- 400 You can create this file in NetBeans:
- Choose File, New File. The New File dialog opens.
- Choose Other in the Categories pane.
- Choose JNLP File in the File Types pane.
- Click Next. The New JNLP File dialog appears.
- Enter PageData in the File Name field. In the Created File field, you see that NetBeans automatically adds the file extension .jnlp to the file name.
- Click Finish.
- 400 NetBeans creates a new JNLP file in the source code editor, starting you with some text in XML format.
- Delete all this text and enter the code shown in Listing 14.2
- Then save the file.
Listing 14.2 The full Text of PageData.jnlp
<?xml version="1.0" encoding="utf-8"?>
<!-- JNLP File for the PageData Application -->
<jnlp
codebase="http://cadenhead.org/book/java-21-days/java"
href="PageData.jnlp">
<information>
<title>PageData Application</title>
<vendor>Rogers Cadenhead</vendor>
<homepage href="http://www.java21days.com"/>
<icon href="pagedataicon.gif"/>
<offline-allowed/>
</information>
<resources>
<j2se version="1.8"/>
<jar href="PageData.jar"/>
</resources>
<security>
<j2ee-application-client-permissions/>
</security>
<application-desc main-class="PageData"/>
</jnlp>
- Top
- 401 Because a JNLP file is structured as XML data, everything within the < and > symbols is a tag.
- Tags are placed around the information that the tag describes.
- There's an opening tag before the information and a closing tag after it.
- 401 For example, line 7 of Listing 14.2 contains the following text:
-
<title>PageData Application</title>
- 401 In order from left to right, this line contains the opening tag <title>, the text Page Data Application, and the closing tag </title>.
- The text between the tags, "PageData Application," is the application's title.
- Java Web Start will display the title as the application is being loaded.
- The title also will be used in menus and shortcuts.
- 401 The difference between opening tags and closing tags is that closing tags begin with a slash character (/), and opening tags do not.
- In line 8, <vendor> is the opening tag, </vendor> is the closing tag, and these tags surround the name of the vendor who created the application.
- I've used my name here.
- Delete it and replace it with your own name, taking care not to alter the <vendor> or </vendor> tags around it.
- Top
- 401 Some tags have an opening tag only, such as line 11:
- 401 The offline-allowed tag indicates that the application can be run even if the user is not connected to the Internet.
- If it were omitted from the JNLP file, the opposite would be true, and the user would be forced to go online before running this application.
- 401 In XML, all tags that do not have a closing tag end with /> instead of >.
- 401 Tags also can have attributes, which are another way to define information in an XML file.
- An attribute is a name inside a tag that is followed by an equal sign and some text within quotes.
- 401 For example, consider line 9 of Listing 14.2:
- <homepage href="http://www.java21days.com"/>
- 401 This is the homepage tag, and it has one attribute, href.
- The text between the quote marks, is used to set the value of this attribute to "http://www.java21days.com".
- This defines the application's home page - the web page that users should visit if they want to read more about the program and how it works.
- Top
- 402 The PageData JNLP file defines a simple Java Web Start application that runs with security restrictions, as defined in lines 17 - 19:
<security>
<j2ee-application-client-permissions/>
</security>
- 402 In addition to the tags that have already been described, Listing 14.2 defines other information required by Java Web Start.
- 402 Line 1 specifies that the file uses XML and the UTF-8 character set.
- This same line can be used on any of the JNLP files you create for applications.
- 402 Line 2 is a comment. Like comments in Java classes, this text is provided solely for the benefit of humans looking at this file.
- Java Web Start ingnores it.
- 402 The jnlp element, which begins on line 3 and ends on line 21, must surround all the other tags that configure Web Start.
- 402 This tag has two attributes, codebase and href, which indicate where the JNLP file for this application can be found.
- The codebase attribute is the uniform resource locator (URL) of the folder that contains the JNLP file.
- The href attribute is the name of the file or a relative URL that includes a folder and the name (such as "pub/PageData.jnlp").
- Top
- 402 In Listing 14.2, the attributes indicate that the application's JNLP file is at the following web address:
http://cadenhead.org/book/java-21-days/java/PageData.jnlp
- 402 The information element (lines 6 - 12) defines information about the application.
- Elements can contain other elements in XML, and in Listing 14.2, the information element contains title, vendor, homepage, icon, and offline-allowed tags.
- 402 The title, vendor, homepage, and offline-allowed elements were described earlier.
- 402 The icon element (line 10) contains an href attribute that indicates the name (or folder location and name) of the program's icon.
- Like all file references in a JNLP file, this element uses the codebase attribute to determine the full URL of the resource.
- In this example, the icon element's href attribute is pagedataicon.gif,
- and the codebase is "http://cadenhead.org/book/java-21-days/java",
- so the icon file is at the following web address:
- http://cadenhead.org/book/java-21-days/java/pagedataicon.gif
- 402 The resources element (lines 13 - 16) defines resources used by the application when it runs.
- Top
- 403 The j2se element has a version attribute that indicates which version of the JVM should run the application.
- This attribute can specify a general version (such as "1.7" or "1.8"), a specific version (such as "1.8.0-ae"), or a reference to multiple versions.
- A general version number can be followed by a plus sign.
- The tag <j2se version="1.6+"> sets up an application to be run by any JVM from version 1.6 upward.
- 403 NOTE: When you use the j2se element to specify multiple versions, Java Web Start does not use a beta version to run an application.
- The only way to run an application with a beta release is to indicate that release specifically.
- 403 The jar element has an href attribute that specifies the application's JAR file.
- This attribute can be a filename or a reference to a folder and filename, and it uses codebase.
- In the PageData example, the JAR file is in http://cadenhead.org/book/java-21-days/java/PageData.jar
- 403 The application-desc element indicates the application's main class file and any arguments that should be used when that class is executed.
- 403 The main-class attribute identifies the name of the class file, which is specified without the .class file extension.
- 403 If the class should be run with one or more arguments, place arguments elements within an opening <application-desc> tag and a closing </application-desc> tag
- Top
- 403 The following XML specifies that the PageData class should be run with two arguments:
- http://java.com and yes:
<application-desc main-class="PageData">
<argument>http://java.com</argument>
<argument>yes</argument>
</application-desc>
- 403 You can test the PageData appli9cation from my web server or upload it to your own and edit the JNLP file accordingly.
- 403 If you are trying it on your own server, after you have created the PageData.jnlp file,
- change line 5 of Listing 14.2 so that it refers to the folder on a web server where your application's JAR file, icon file, and JNLP file will be stored.
- 403 Upload all three of the project's files to this folder, and then run your browser and load the JNLP file using its full web address.
- If your web server is configured to support Java Web Start, the application is loaded and begins running.
- Figure 14.5 shows the output if the web address http://www.java.com/ is required.
Figure 14.5 - Running PageData using Java Web Start. - goes here
- Top
- 404 For this application to be run without restriction, the PageData.jar file must be digitally signed.
- For real-world applications, this requires the services of a certificate-granting authority.
- 404 For testing purposes, there are two programs included with the JDK that can be used to create a key and use it to digitally sign a JAR file.
- To find out how to use them, read Appendix E, "Programming with the Java Development Kit."
- 404 A self-signed JAR file only is suitable for your own testing purposes.
- No current web browser will accept that the JAR file is secure or allow users to run it.
- Top
- 404 NOTE: The only way to establish that your Java Web Start application is trustworthy
- is to go thru one of the professional certificate-granting companies, prove your identity, and purchase a code-signing certificate.
- This certificate will be used when signing your JAR files.
- These companies are called certificate authorities.a useful resource for any programmer who needs code-signing certificates, not just io
- California offers a list of digital signature certification authorities at www.tinyurl.com/califsign
- that's a useful resource for any programmer who needs code-signing certificates, not just in that state.
- At the time of this writing, the lowest-priced code-signing certificates were $95 per year from K Software at http://codesigning.ksoftware.net
- Most other authorities charge $200 or more.
Supporting Web Start on a Server
- Top
- 405 If your server does not support Java Web Start, you might see the text of your JNLP file loaded in a page, and the application will not open.
- 405 A web server must be configured to recognize that JNLP files are a new type of data that should cause a Java application to run.
- This is usually accomplished by setting the MINE type associated with files that have the extension JNLP.
- 405 MIME, which is an acronym for Multipurpose Internet Mail Extensions,
- is a protocol for defining Internet content such as email messages, attached files, and any file that can be delivered by a web server.
- 405 On an Apache web server,
- the server administrator can support JNLP by adding the following line to the server's mime.types ( or .mime.types) file:
application/x-java-jnlp-file JNLP
- 405 If you can't get Java Web Start working on your server, you can test this project on the book's official site.
- Top
- 405 CAUTION: Java Web Start applications should look exactly like applications do when run by other means.
- However, there appear to be a few bugs in how much space is allocated to components on a graphical user interface.
- On a Windows system, you might need to add 50 pixels to the height of an application before emplying it in Java Web Start.
- Otherwise, the text fields are not tall enough to display numbers.
Additional JNLP Elements
- Top
- 405 The JNLP format has other elements that can affect the performance of Java Web Start.
- 405 It can be used to change the title graphic that appears when the application is launched,
- run signed applications that have different security privileges,
- run an application using different versions of the JVM,
- and other options.
Security
- Top
- 405 By default, all Java Web Start applications are denied access to some features of a user's computer unless the user has given permission.
- This is similar to how the functionality of applets is limited.
- 406 If your application's JAR file has been digitally signed to verify its authenticity, you can run it without these security restrictions by using the security element.
- 406 This element is placed inside the jnlp element, and it conatins one element of its own: all-permissions.
- To employ the normal security restrictions for an application run by Web Start, add this to a JNLP file:
<security>
<j2ee-application-client-permission/>
</security>
- 406 If the tag all-permissions had been used instead, the application would have no security restrictions.
- This has major implications for user security, so it should be done with care.
- reserve
Descriptions
- Top
- 406 If you want to provide more information about your application for users of Java Web Start,
- you can place one or more description elements inside the information element.
- 406 Four kinds of descriptions can be provided using the kind attribute of the description element:
- kind="one-line" - A succinct one-line description, used in lists of Web Start applications
- kind="short" - A paragraph-long description, used when space is available
- kind="tooltip" - A ToolTip description
- No kind attribute - A default description, used for any other descriptions not specified.
- Top
- 406 All these are optional.
- Here's an example that provides descriptions for the PageData application:
<description>The PageData application.</description>
<description kind="one-line">An application to learn more about web
servers and pages</description>
<description kind="tooltip">Learn about web services and
pages.</description>
<description kind="short">PageData, a simple Java application that
takes a URL and displays information about the URL and the web
sever that delivered it.</description>
Icons
- Top
- 406 The PageData JNLP file includes a 64x64 icon, pagedataicon.gif, used in two different ways:
- When the PageData application is being loaded by Java Web Start, the icon is displayed in a window next to the program's name and author.
- If a PageData icon is added to a user's desktop, the icon is used at a different size: 32x32.
- 407 When an application is loading, you can use a second icon element to specify a graphic that will be displayed in place of the icon, title, and author.
- This graphic is called the application's splash screen, and it is specified with the kind="splash" attribute, as in this example:
- <icon kind="splash" href="pagedatasplash.gif" width="300"
height="200" />
- 407 The width and height attributes, which also can be used with the other kind of icon graphic, specify the image's display size in pixels.
- 407 The second icon element should be placed inside the information element.
Improving Performance with SwingWorker
- Top
- 407 The responsiveness of a Swing application depends largely on how well the software handles time-consuming tasks in response to user input.
- 407 Applications ordinarily execute tasks in one thread.
- So if something takes a long time to accomplish, such as loading a large file or parsing data from an XML document,
- the user might notice a lag in performance while this is taking place.
- 407 Swing programs also require all user-interface components to be running within the same thread.
- 407 The best way to take care of both requirements is to use SwingWorker,
- a class in the javax.swing package that's designed to run time-consuming tasks in their own worker thread and report the results.
- 408 SwingWorker is an abstract class that must be subclassed by applications that require a worker:
public class DiceWorker extends SwingWorker{
// body of class
}
- Top
- 408 The doInBackground() method should be overridden in the new class to perform the task.
Third Program - Listing 14.3
- Top
- 408 Today's next project is a Swing application that rolls three six-sided dice a user-selected number of times and tabulates the results.
- Sixteen text fields represent the possible values, which range from 3 to 18.
- 408 The application is developed as two classes:
- the DiceRoller frame, which holds the graphical user interface,
- and the DiceWorker Swing worker, which handles the dice rolls.
- 408 Because the application allows the user to roll the dice thousands or even millions of times,
- putting this task in a worker keeps the Swing interface responsive to user input.
- 408 Listing 14.3 contains the worker class, DiceWorker.
- Create this as an empty Java file in NetBeans with that class name and the package com.java21days.
- In the New File dialog, be sure the Project selected is Java21, not PageData.
- Top
- page 408 - 409
package com.java21days;
import javax.swing.*;
public class DiceWorker extends SwingWorker {
int timesToRoll;
// set up the Swing worker
public DiceWorker(int timesToRoll) {
super();
this.timesToRoll = timesToRoll;
}
// define the task the worker performs
protected int[] doInBackground() {
int[] result = new int[16];
for (int i = 0; i < this.timesToRoll; i++) {
int sum = 0;
for (int j = 0; j < 3; j++) {
sum += Math.floor(Math.random() * 6);
}
result[sum] = result[sum] + 1;);
}
// transmit the result
return result;
}
}
- Top
- 409 There's no way to do anything with this class until you create the next one, DiceRoller.
- 409 A Swing worker needs only one method, doInBackground(), which performs the task in the background.
- The method must be the protected level of access control and retun a value produced by the work.
- DiceRoller creates a 16-element integer array that contains dice-roll results.
- 409 Another class can use this worker in three steps:
- Call the worker's DiceWorker(int) constructor with the number of rolls as the argument.
- Call the worker's addPropertyChangeListener(Object) method to add a listener that will be notified when the task is complete.
- Call the worker's execute() method to begin the work.
- 409 The execute() method causes the worker's doInBackground()method to be called.
- 409 A property change listener is an event listener from java.beans, the JavaBeans package that establishes ways in which components on a user interface can interact with each other.
- 409 In this case, a Swing worker wants to announce that its work is finished, which could take place long after the worker began its work.
- Listeners are the best way to handle notifications of this kind because they free a graphical user interface to handle other things.
- 409 The property change listener interface has one method:
public void propertyChange(PropertyChangeEvent event) {
// ...
}
- 409 The DiceRoller class in the com.java21days package, shown in Listing 14.4, presents a graphical user interface that can display dice-roll results and begin a set of rolls.
Fourth Program - Listing 14.4 - The Full Text of DiceRoller.java
package com.java21days;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
public class DiceRoller extends JFrame implements ActionListener,
PropertyChangeListener {
// the table for dice-roll results
JTextField[] total = new JTextField[16];
// the "Roll" button
JButton roll;
// the number of times to roll
JTextField quantity;
// the Swing worker
DiceWorker worker;
public DiceRoller() {
super("Dice Roller");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLookAndFeel();
setSize(850, 145);
// set up top row
JPanel topPane = new JPanel();
GridLayout paneGrid = new GridLayout(1, 16);
topPane.setLayout(paneGrid);
for (int i = 0; i < 16; i++) {
// create a textfield and label
total[i] = new JTextField("0", 4);
JLabel label = new JLabel((i + 3) + ": ");
// create this cell in the grid
JPanel cell = new JPanel();
cell.add(label);
cell.add(total[i]);
// add the cell to the top row
topPane.add(cell);
}
// set up bottom row
JPanel bottomPane = new JPanel();
JLabel quantityLabel = new JLabel("Times to Roll: ");
quantity = new JTextField("0", 5);
roll = new JButton("Roll");
roll.addActionListener(this);
bottomPane.add(quantityLabel);
bottomPane.add(quantity);
bottomPane.add(roll);
// set up frame
GridLayout frameGrid = new GridLayout(2, 1);
setLayout(frameGrid);
add(topPane);
add(bottomPane);
setVisible(true);
}
// respond when the "Roll" button is clicked
public void actionPerformed(ActionEvent event) {
int timesToRoll;
try {
// turn off the button
timesToRoll = Integer.parseInt(quantity.getText());
roll.setEnabled(false);
// set up the worker that will roll the dice
worker = new DiceWorker(timesToRoll);
// add a listener that monitors the worker
worker.addPropertyChangeListener(this);
// start the worker
worker.execute();
} catch (Exception exc) {
System.out.println(exc.getMessage());
exc.printStackTrace();
}
}
// respond when the worker's task is complete
public void propertyChange(PropertyChangeEvent event) {
try {
// get the worker's dice-roll results
int[] result = (int[]) worker.get();
// store the results in text fields
for (int i = 0; i < result.length; i++) {
total[i].setText("" + result[i]);
}
} catch (Exception exc) {
System.out.println(exc.getMessage());
exc.printStackTrace();
}
}
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
// ignore error
}
}
public static void main(String[] arguments) {
new DiceRoller();
}
}
- Top
- 412 This class can be run as an application. Choose Run, Run File in NetBeans.
- 412 Most of DiceRoller creates and lays out the user-interface components: 16 text fields, a Times to Roll text field, and a Roll button.
- 412 The actionPerformed() method responds to a click of the Roll button
- by creating a Swing worker that will roll the dice, adding a property change listener and starting work.
- 412 Calling worker.execute() in line 73 causes the worker's doInBackground() method to be called.
- 412 When the worker is finished rolling the dice, the propertyChange() method of DiceRoller receives a property change event.
- 412 This method receives the results of doInBackground() by calling the worker's get() method (line 84), which must be cast to an integer array:
int[] result = (int[] worker.get(); note: verify the character in front of int[].
- 412 The application is shown in Figure 14.6
Figure 14.6 - Tabulating dice-roll results prepared by DiceWoker. - goes here
Summary
- Top
- 412 The topics covered today are two capabilities that enhance Java's capabilities for application development,
- browser-based program deployment and Swing performance improvements thru the use of threads.
- 413 With Java Web Start, users no longer need to run an installation program to set up a Java application and the JVM that executes the class.
- Web Start takes care of this automatically after the user's browser has been equipped to use the Java Runtime Environment.
- 413 Support for Web Start is offered thru the Java Network Launching Protocol (JNLP),
- an XML file format used to define and set up Java Web Start.
- 413 The SwingWorker class improves Swing application performance by putting a time-consuming task in its own thread.
- The class handles all the work required to start and stop the thread behind the scenes.
- 413 When you create a subclass of SwingWorker, you can focus on the task that must be performed.
Q & A
- Top
- Q I have written a Java applet that I want to make available using Java Web Start. Should I convert it to an application or go ahead and run it as is ?
- A If you would be converting your program to an application simply to run it with Web Start, that's probably unnecessary.
- The purpose of the applet-desc tag is to make it possible to run applets without modification in Java Web Start.
- The only reason to undertake the conversion is if you want to change other things about your program,
- such as the switch from init() to a constructormethod.
- Q How can I make sure that a SwingWorker object has finished working ?
- A Call the worker's isDone() method, which returns true when the task has finished executing.
- Note that this method returns true no matter how the task completes.
- So if it is canceled or interrupted or fails in some other matter, it returns true.
- The isCancelled() method can be used to check whether the task was canceled.
Quiz - Questions
- Top | Review today's material by taking this three-question quiz.
- What interface must be implemented for you to be notified when a SwingWorker has finished executing ?
- ActionListener
- PropertyChangeListener
- SwingListener
- Which XML element is used to identify the name, author, and other details about a Java Web Start-run application ?
- jnlp
- information
- resources
- What security restrictions apply to a Java Web Start application ?
- There are no restrictions.
- The same restrictions that are in place for applications
- The restrictions choosen by the user
Answers
- Top | Note A is 1, B is 2, and C is 3
- B. ThePropertyChangeListener in the java.beans package receives a propertyChange()event when the worker finishes.
- B. The application is described using elements contained within an opening <information> tag and a closing </information> tag.
- C. A Java Web Start application has few restrictions.
- They are limited to important functionality such as saving files or opening Internet connections.
- These restrictions are dropped if a user explicitly grants those privileges as the application runs.
Certification Practice
- Top
- 414 The following question is the kind of thing you could expect to be asked on a Java programming certification test.
- Answer it without looking at today's material or using the Java compiler to test the code.
- The answer is available on the book's website at www.java21days.com
- Given:
import java.awt.*;
import javax.swing.*;
public class SliderFrame extends JFrame {
public SliderFrame() {
super();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JSlider value = new JSlider(0, 255, 100);
setSize(325, 150);
setVisible(true);
}
public static void main(String[] arguments) {
new SliderFrame();
}
}
- What will happen when you attempt to compile and run this souce code ?
- It compiles without error and runs correctly.
- It compiles without error but does not display anything in the frame.
- It does not compile because the content pane is empty.
- It does not compile because of the new SliderFrame() statement.
Exercise
- Top
- To extend your knowledge of the subjects covered today, try the following exercises:
- Turn one of the applications created during the first two weeks into one that can be launched with Java Web Start.
- Create a new JNLP file that runs PageData application useing version 1.3 of the JVM,
- and force users to be connected to the Internet when it is run.