Blakes 21 Days Chapter 14 Document


Day 14, Developing Swing Applications

Java Web Start

Figure 14.1 - Presenting Web Start applications on a web page. - goes here

Figure 14.2 - Running a Java Web Start application. - goes here

Figure 14.3 - Choosing an application's security privileges. - goes here

Using Java Web Start

Creating a JNLP File

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

Figure 14.4 - Adding a file to a project in NetBeans. - goes here

419

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>

Figure 14.5 - Running PageData using Java Web Start. - goes here

421

Supporting Web Start on a Server

Additional JNLP Elements

Security

Descriptions

Icons

Improving Performance with SwingWorker

Third Program - Listing 14.3

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

Figure 14.6 - Tabulating dice-roll results prepared by DiceWoker. - goes here

434

Summary



Q & A



Quiz - Questions

  1. What interface must be implemented for you to be notified when a SwingWorker has finished executing ?
    1. ActionListener
    2. PropertyChangeListener
    3. SwingListener
  2. Which XML element is used to identify the name, author, and other details about a Java Web Start-run application ?
    1. jnlp
    2. information
    3. resources
  3. What security restrictions apply to a Java Web Start application ?
    1. There are no restrictions.
    2. The same restrictions that are in place for applications
    3. The restrictions choosen by the user

Answers

  1. B. ThePropertyChangeListener in the java.beans package receives a propertyChange()event when the worker finishes.
  2. B. The application is described using elements contained within an opening <information> tag and a closing </information> tag.
  3. C. A Java Web Start application has few restrictions.


Certification Practice

  1. What will happen when you attempt to compile and run this souce code ?
    1. It compiles without error and runs correctly.
    2. It compiles without error but does not display anything in the frame.
    3. It does not compile because the content pane is empty.
    4. It does not compile because of the new SliderFrame() statement.


Exercise