Sunday, 7 September 2014

Java Applets and Multimedia

Java Applets and Multimedia

1. Applet Basics

At this point you should be comfortable with using most of the features of the Java programming language, and you have had a pretty thorough introduction to basic graphics programming in Java.
An applet is a special kind of Java program that a Java-enabled browser can download from the Internet and then run. You can find thousands of thousand Java applets are included in websites.

1.1 A Simple Applet

An applet is simply a Java class that extends the java.applet.Applet class and is an AWT component. From now on we are going to use Swing to implement applets.
Read the following simple program. I think there is nothing new to you.
However as there is no main function in this program, so you cannot run this program on the JVM.

1.2 Applet Vewing

To execute the applet, you need to carry out two steps:
  1. Compile your java source files into class file, say TestApplet.class
       
  2. Create an HTML file that tells the browser which class file to load first and how to size the applet displaying area on the webpage.
For our example, the corresponding HTML could be like
Save the above into an HTML file, say TestApplet.html. Then use a browser e.g. MS IE to open the file TestApplet.html, then you will see the message is displayed in the center of display area in the web browser.
Change width = 300, height = 300 in the html file to other width and height values to see what will happen.
Of course, a good style is to test your applet class file in the applet viewer before you view it in a browser.
The program applet viewer is part of the JDK. You can simply view your applet by
>appletviewer TestApplet.html
Please note you should input the html rather than the class file to the viewer program.

1.3 The basic method in Applet class

Every applet is a subclass of the JApplet class,
You don’t implement all the method, but it is better to put all the initialization work in this method.

2. Conversion between Applet and Application

In general, an applet can be converted to an application without loss of functionality. An application can be converted to an application as long as it does not violates the security restrictions imposed on applets.
The differences between an applet and application are
  1. Application is run on the JVM and its has a main frame, but applet don’t have a main frame because the frame will be created by the browser.
       
  2. Application has a main function but the applet does not.
To convert an application program to an applet, you only need to remove the initialization for the main frame and remove the main function and put other initial work into the init() method
To convert an applet to an application, add extra initialization for a frame and put them in a main function.
A possible way is to change the main method to the init() method, and conversely change the init() method to the main method.

3. Parameters to Applets

A parameter can be passed to applets, but the parameter must be declared in the HTML file and must be read by the applet when it is initialized.
Parameters are declared using the  tag of HTML. The  tag must be embedded in the  tag and has no end tag. The syntax for the  tag is given below
The tag specifies a parameter and its corresponding string value.
In your applet code, to read the parameter declared in the HTML file, you need to use the following method defined in the JApplet class
where the parametername must be the name specified in the HTML file.
Read the program in Listing 18.5 first. And then try the following program.
The applet code is:

4. Multimedia

Applets can handle both images and audio. But the image files must be in GIF, PNG and JPEG form, and the audio files in AU, AIFF, WAVE or MIDI form.
Usually the files are specified as a URL.

4.1 Encapsulating URLs

A URL is really nothing more than a description of a resource on the Internet. For example the CSU’s URL ishttp://www.csu.edu.au/index.html on the Internet.
Java uses the URL class to encapsulate a URL address. To make a URL instance in Java is quite simple
URL address = new URL(“http://www.csu.edu.au/index.html”);
That URL specifies the file index.html. Another URL constructor is to use relative URL, like
URL data = new URL(address, “data/student.dat”);
for the file student.dat , located in the data subdirectory of the URL address .
A common way of obtaining a URL is to ask an applet where it came from,
  • What is the URL of the HTML page in which the applet is contained?
  • What is the URL of the applet’s codebase directory?
with the method getDocumentBase and getCodeBase, respectively, in the applet code.

4.2 Getting multimedia files

You can retrieve images and audio files with the getImage and getAudioClip methods. For example
Image me = getImage(getCodeBase(), “images/gaophoto.jpg”);
AudioClip song = getAudioClip(getCodeBase(), “audio/mysong.wav”);
Here, getCode Base method returns the URL from which your applet code is loaded. The second argument is the relative location of the files to the base code URL.
Once you have got the image, then you can use drawImage method of the Graphics calss to show the image.
To play an audio clip, simply invoke Applet ’s play method
play(song);
Or
play(getCodeBase(), “audio/mysong.wav”)

Advanced GUI Topics

Advanced GUI Topics

1. Menus, Toolbars and Dialogs

1.1 Creating Menus

The JFrames we have created so far only have a title bar as shown below (left). However a usual application main frame should look like the one on the right
                     

Creating a menu bar and menus on it is very easy. You simply use the JMenuBar constructor to create an menu bar instance, use theJMenu constructor to create the menus you need and then add the menu onto the menu bar, finally use JFrame’s setJMenuBarmethod to add the bar into the frame. The frame is created by the following code.
import javax.swing.*;
public class TestMenus {
public static void main( String[] argv ) {

JFrame myframe = new JFrame("My First Frame");
JMenuBar jmb = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
JMenu helpMenu = new JMenu("Help");

jmb.add(fileMenu);
jmb.add(editMenu);
jmb.add(helpMenu);

myframe.setJMenuBar(jmb);

myframe.setSize(400, 300);
myframe.setLocationRelativeTo(null);
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myframe.setVisible(true);
}
}
Nothing is more complicated than creating a JButton.
You can add menu items, separators, and submenus to the menu object. Suppose that the above editMenu has menu items Cut, Copy, Paste and a submenu Options with its own menu items Read-only, Insert, Overtype etc. Also there are several separators to groups menu items. See the frame below


To get this frame you only need put the following code before jmb.add(fileMenu) in the above program
JMenuItem cutItem = new JMenuItem("Cut");
JMenuItem copyItem = new JMenuItem("Copy");
JMenuItem pasteItem = new JMenuItem("Paste");

JMenu optionsMenu = new JMenu("Options");
JMenuItem readItem = new JMenuItem("Read-only");
JMenuItem insertItem = new JMenuItem("Insert");
JMenuItem overtypeItem = new JMenuItem("Overtype");
optionsMenu.add(readItem);
optionsMenu.addSeparator();
optionsMenu.add(insertItem);
optionsMenu.add(overtypeItem);
//Submenu done

editMenu.add(cutItem);
editMenu.add(copyItem);
editMenu.add(pasteItem);
editMenu.addSeparator();
editMenu.add(optionsMenu); //add a submenu
Actually you follow the same logic when you create menus, menu items and submenus.

1.2 Decorating Menu Items

You can create a check box or radio button menu item. You simply use for example
helpMenu.add(new JCheckBoxMenuItem(“Check it”));
helpMenu.add(new JRadioButtonMenuItem(“Check it”));
You can specify an image icon with the JMenuItem(String, Icon) to set an icon for the menu item, for example
JMenuItem cutItem = new JMenuItem(“Cut”, new
ImageIcon(‘cut.jpg”));
Similarly you can set a keyboard mnemonics for a menu item. For example
fileMenu.setMnemonic(‘F’);
then there is a underline below “F” in the menu “File” and the user can use ALT+F to choose the menu item or choose the submenu.

1.3 Creating Popup Menus

A pop-up menu is a menu that is not attached to a menu bar but that floats somewhere. You create a pop-up menu similarly to the way you create a regular menu. Unlike the regular menu bar that is always shown at the top of the frame, you must explicitly display a pop-up menu by using the show method. You specify the parent component and the location of the pop-up, using the coordinate system of the parent. For example
JPopupMenu popup = new JPopupMenu();
//creating menu items and add them it the popup menu
popup.show(aParentComponent, x, y);
Read Section 38.3 for more details.

1.4 Creating Toolbars

A toolbar is a button bar that gives quick access to the most commonly used commands in a program. Unlike the menu bar, you can drag the toolbar to elsewhere. When you release the mouse button, the toolbar is dropped into the new location.
Open your JCreator program, on the main window, you can see the toolbar which is just below the menu bar. On the toolbar you can find buttons for creating new files, cutting and pasting, even a combo box etc.
Toolbars are straightforward to program. First you create an tool bar instance with the JToolBar constructor
JToolBar mytoolbar = new JToolBar();
Then consider mytoolbar as a panel (or a container). You can simply add other components like JButtons, Combo Boxes etc into the tool bar object. Nothing is new.
The JToolBar class also has a method to add an Action object into the bar.
You can also separate groups of buttons in the bar with a separator:
mytoolbar.addSeparator();
Then there is a small gap between button groups.
By default, toolbars are initially horizontal. To have a toolbar start out as vertical, sue
JToolBar Mytoolbar = new JToolBar(JToolBar.VERTICAL);
After you have completed your toolbar design, you simply add it to a frame the same as you do for any components.
Read the program in Listing 38.3

1.5 Event Processing Events from Menu and Tool Bar

The menu items generate ActionEvent. You must implement the ActionListener interface’s the actionPerformed method to handle the event from the menu items. Of course you need to register your ActionListener with the menu item so the listener will respond to the menu selection.
    
The commonly added items on a tool bar are buttons. So you process the events from a tool bar in the similar way you handle with the button’s ActionEvent. Nothing is special.
Often menus and tool bars contain some common actions. For example, on the JCreator’s main window, you can save a file by choosing the File menu then Save menu item, or by quickly clicking the save button in the tool bar. In this case you need to register the sameActionListener to the menu items and button on a tool bar. To use a uniform way, Java offers the Action interface.
Read Section 34.5 but focus on what an Action is, how to create an action, how to install an action to menus and toolbars.

2. Dialog Boxes

So far, all our user interface components have appeared inside a frame window. However we usually want separate dialog boxes to pop-up to give a warning if the user is doing wrong thing with the program or to get information from the user.
Swing provides several kind of useful dialog boxes for the purpose. The JOptionPane has four static methods to show these simple dialogs: showMessageDialog, showConfirmDialog, showOptionDialog and showInputDialog

2.1 Message Dialogs

The simplest dialog box is the message dialog which is used to display a message with a OK button to alert the user and wait for the user’s action.
To show a message dialog, you can use one of three versions of the showMessageDialog method. Read the information on pages 1189-10 (8E) or java Swing document.
Test the following program
import javax.swing.*;
public class TestMessageBox {
public static void main( String[] argv ) {
JOptionPane.showMessageDialog(null, new String("This is a
Warning"), "Warning", JOptionPane.ERROR_MESSAGE); 
}
}
  1. Change the ERROR_MESSAGE to INFORMATION_MESSAGE, PLAIN_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE.
       
  2. Change new String(“This is a Warning”) to another object for example new JButton(“Button!”)

2.2 Confirmation Dialogs

A message dialog box displays a message and waits for the user to click the OK button to dismiss the dialog. The method does not return any value. A confirmation dialog usually presents a question with up to three buttons for the user to choose one from. The confirmation dialog box is created by the JOptionPane’s method showConfirmDialog. The method will return an integer to indicate which button the user chose. Then the program can respond to it.
Read the following example

import javax.swing.*;
public class TestMessageBox {
public static void main( String[] argv ) {
int selection = JOptionPane.showConfirmDialog(null,
"Message", "Title", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE); 

if (selection == JOptionPane.CANCEL_OPTION)
JOptionPane.showMessageDialog(null, new String("The
user chose the OK button"), "USER'S CHOICE",
JOptionPane.PLAIN_MESSAGE);
}
}

2.3 Input Dialogs

An input dialog box is pop-uped and used to receive input from the user. The box is created by call the showInputDialog method and the method will return the user’s input or choice.
With the method, you can specify a text field for the user to input, or specify a list of items for the user to choose from. Here is an example
String text = JOptionPane.showInputDialog(null, “Enter something:”, “InputDialog Demo”, JOptionPane.QUESTION_MESSAGE);

2.4 Options Dialogs

Unlike the confirmation dialog boxes with up-to three options, you can custom the number of options (buttons) with an option dialog. Here is an example and it is self-explanatory
int val = JOptionPane.showOptionDialog(null, “Make a choice”,
“Options”, JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE, null, new Object[] {“Choice 0”,
“Choice 1”, “Choice 2”, “Choice 3”}, “Choice 2”);

3. File Dialogs

In most of application software like MS Word, when you choose the File menu then the Open items you are presented in dialog window from which you can browse your file system to choose the file you want to edit. The pop-up window is called a File dialog in Java.

3.1 The JFileChooser class

To get such a window for your application, you can use the JFileChooser class to display a file dialog window similar to the one you use in MS Word.
Under the JFileChooser, you call the showOpenDialog to display a dialog for opening a file or you call the showSaveDialog to display a dialog for saving a file. The button for accepting a file is then automatically labeled Open or Save. Of course, you can change the label to anything you like with the general showDialog method.
Here are the steps needed to put up a file dialog box and recover what the user chooses from the box
  1. Make a JFileChooser object
    JFileChooser mychooser = new JFileChooser();
      
  2. Set the directory with the setCurrentDirectory method as the starting point in the file system. Most of time you should set it to the current working directory
    mychooser.setCurrentDirectory(new File(“.”));
      
  3. Show the dialog box by call the showOpenDialog or showSaveDialog method. You must supply the parent component in these calls
    int result = chooser.showOpenDialog(parent);
    The return value is JFileChooser.APPROVE_OPTION,
    JFileChooser.CANCEL_OPTIION, or JFileChooser.ERROR_OPTION
       
  4. If the return value is JFileChooser.APPROVE_OPTION, then you can get the chosen file name and path by
    String filename = chooser.getSelectedFile().getPath();

3.2 The File Filter

For example, when you want to open a file in MS Word, the file open dialog window will only display the files with extension name .docand .dot etc. To achieve this purpose, you can create a FileFilter first, then set the filter to the JFileChooser. For example if we are going to filter all the files with extension .doc, we can create a file filter in this way
public class DocFilter extends FileFilter {
public Boolean accept(File f) {
return f.getName().toLowerCase().endsWith(“.doc”)  ||
f.isDirectory();
}
public String getDescription()  {
return “Word Document”;
}
}
Then you can set a filter object to the JFileChooser
mychooser.setFileFilter(new DocFilter());
Check the following code and run it

import javax.swing.*;
import java.io.*;
import javax.swing.filechooser.FileFilter;
public class TestFileChooser {
public static void main( String[] argv ) {
JFrame myframe = new JFrame("Test File Chooser");          
myframe.setSize(400, 300);
myframe.setLocationRelativeTo(null);
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myframe.setVisible(true);

JFileChooser chs = new JFileChooser();

chs.setCurrentDirectory(new File("."));
chs.setFileFilter(new DocFilter());

int result = chs.showOpenDialog(myframe);

}
}
class DocFilter extends FileFilter {
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".doc")  ||
f.isDirectory();
}
public String getDescription()  {
return "Word Document";
}
}

4. JTrees

You should be familiar with the visualized tree structures. For example, the Window systems File Manager display the file system as a tree structure of folders, see the left box on the figure below,
This kind of visual structure can be easily created with the assistance of the JTree class in Swing.
JTree is a Swing component that displays data in a treelike hierarchy. The subtrees on the structure can be collapsed or expanded. For example, in the above figure the Dev-Cpp is collapsed, so you cannot see the subfolders of the Dev-Cpp folder, while the Documents and Settings is expanded and its subfolders are displayed.

4.1 Tree terminology

A tree is composed of nodes. There is only one node called the root. Each node is either a leaf node or it has child nodes. Every node exception of the root has exactly one parent. Every one node plus its children, children’s children make up a subtree.

4.2 The JTree classes

The JTree class has seven constructors, please consult to Figure 40.20 for more details. To construct a default tree, you simply use
JTree  tree1 = new JTree();
which create the following tree structure
You can create a tree from an array of Objects such as String.
JTree tree2 = new JTree(new String[] {“Appel”, “Orange”,
“Banana”, “Pear”});
which creete a tree with an invisible root and the elements simply as its children. If you want to see the root, you need usesetRootVisible(true).
Try the following program
import javax.swing.*;
import java.awt.*;
public class TestTree {
public static void main( String[] argv ) {
JFrame myframe = new JFrame("Test File Chooser");  
myframe.setSize(400, 300);

JTree jTree1 = new JTree();
JTree jTree2 = new JTree(new String[] {"Appel", "Orange", "Banana", "Pear"});
jTree2.setRootVisible(true);
myframe.add(jTree1,BorderLayout.NORTH);
myframe.add(jTree2,BorderLayout.CENTER);

myframe.setLocationRelativeTo(null);
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myframe.setVisible(true);
}
}

4.3 The TreeModel

If you have tried the last example, you would see the structure of both trees are quite simple with one root and one level of children. This kind of structural information is contained the TreeModel in which TreeNode stores and manages the tree data, like the labels in the last example.
If you want to get the root of an JTree instance, you first need to get the TreeModel of the tree by the getModel() method, then use thegetRoot method of the model. For example
TreeModel model = jTree1.getModel();
model.getRoot();
From the root, you can get its i-th children by
model.getChild(root, i);
After you have got one of children, consider it as the new root and then you can get this child’s children. The program in Listing 40.13 shows you how to access all the children in a tree.

4.4 The TreeNode Interface

Each node in a tree is represented by TreeNode which storing information of the node. One of the implementation for the TreeNode interface is the DefaultMutableTreeNode class.
With DefaultMutableTreeNode you can build a series of nodes and pack them in a single node. You build up your tree through nodes, you always begin with the leaf nodes. Let us build a JTree for the following actual tree.
For each leaf node, construct a DefaultMutableTreeNode
DefaultMutableTreeNode darlinghabour = new
DefaultMutableTreeNode(“Darling Habour”);
DefaultMutableTreeNode melbourne = new
DefaultMutableTreeNode(“Melboune”);
DefaultMutableTreeNode beijing = new
DefaultMutableTreeNode(“Beijing”);
DefaultMutableTreeNode pudong = new DefaultMutableTreeNode(“Pu Dong”);
DefaultMutableTreeNode huangpu = new DefaultMutableTreeNode(“Huang
Pu”);
Now create a default tree node for Sydney
DefaultMutableTreeNode sydney =
new DefaultMutableTreeNode(“Syndey”);
As the Darling Habour is a children of the Sydney, so we add the darlinghabour node into the sydney node
Sydney.add(darlinghabhour);
Then create a node for Shanghai and add both pudong and huangpu to it
DefaultMutableTreeNode shanghai = new
DefaultMutableTreeNode(“Shanghai”);
shanghai.add(pudong);
shanghai.add(huangpu
);
Then add the syndey and melbourne nodes to australia node by
DefaultMutableTreeNode australia = new
DefaultMutableTreeNode(“Australia”);
australia.add(sydney);
australia.add(melbourne);
Add the beijing and shanghai nodes to china node
DefaultMutableTreeNode china =
new DefaultMutableTreeNode(“China”);
china.add(beijing);
china.add(Shanghai);
Finally add the australia and china nodes to the world
DefaultMutableTreeNode world =
new DefaultMutableTreeNode(“World”);
world.add(australia);
world.add(china);
Now we have packed all the information about the tree nodes and their relations in the node world, finally create the JTree by
JTree World = new JTree(world);

Can you put all the code together to create the tree in a program?

5. JTables

The JTable component displays a two-dimensional grid of objects, like a spreadsheet. Of course, tables are common in user interface.
As with the tree model, a JTable does not store its own data but obtains its data from a table model. JTable also has two other models: a column model and a list-selection model. The column model maintains the columns in the table while the list-selection model is used to access the rows, columns and cells in the table.

5.1 Creating JTables

Like the JTree, there are seven constructors for the JTable. Probably the simplest one is the constructor who accepts a two-dimensional array of objects as its parameter. Then the objects in the array will be displayed in a table.
For example
Object[][] cells =  {
{ “Mercury”, 2440.0, 0, false, Color.yellow },
{“Venus”, 6052.0, 0, false, Color.yellow },
...
};
String[] columnNames = {“Planet”, “Radius”, “Moons”, “Gaseous”,
“Color”};
JTable table = new JTable(cells, columnNames);
As JTable doesn’t directly support scrolling when you have many rows, you need to create a JScrollPane to hold the table. If a table is not placed in a scroll pane, its column header will not be visible. To finish our job, put one more statement
JScrollPane pane = new JScrollPane(table);
The final program is here
import javax.swing.*;
import java.awt.*;
public class TestTable {
public static void main( String[] argv ) {
JFrame myframe = new JFrame("Test Table");  
myframe.setSize(400, 300);

Object[][] cells =  {
{ "Mercury", 2440.0, 0, false, Color.yellow },
{"Venus", 6052.0, 0, false, Color.yellow } };
           String[] columnNames = {"Planet", "Radius", "Moons",
"Gaseous", "Color"};
JTable table = new JTable(cells, columnNames);
JScrollPane pane = new JScrollPane(table);
myframe.add(pane);

myframe.setLocationRelativeTo(null);
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myframe.setVisible(true);

}
}

5.2 The Table Model

The TableModel is an interface. One of basic concrete classes implementing this interface is the DefaultTableModel class. With this class you can add, update and remove table data. To use this model, you can do it in this way
Object[][] cells =  {  .. .. .. };
String[] columnNames = { .. .. .. };
DefaultTableModel model = new DefaultTableMode(cells, columnNames);
JTable table = new JTable(model);
Then you use the model with table like
model.removeRow(1);
model.addColumn(“Distance”);
More methods please consult to the Java document.

5.3 The Table Column Models

The table column models manage columns in a table. For example you can use them to select, add, move and remove table columns.
The table column model of a table can be obtained by the getColumnModel() method of the table instance.

5.4 The ListSelectionModel

The ListSelectionModel should be obtained from the TableColumnModel by using its getSelectionModel() method.

[ITC521 only] Topic 10 Java Socket Programming (for Networking and Communication)

1. The Client/Server Computing

Two or multiple programs can be connected to each other via Internet. If one of them is considered as server and others are considered as client then the communication among themselves happen through server socket and client sockets.
Data transmission through socket:
At the first step the server creates a socket using a port which can be connected by a client socket. Once the protocol establishes a connection, they are able to exchange information. These basic connection mechanisms to create an I/O stream is depicted in the following figure which along with detail description can be found in chapter 33 of the textbook.
 
Server to serve multiple sockets:
 A server can serve multiple sockets as illustrated in following figure:
An example code of the server serving multiple clients is as follows:
1  import java.io.*;
  2  import java.net.*;
  3  import java.util.*;
  4  import java.awt.*;
  5  import javax.swing.*;
  6  
  7  public class MultiThreadServer extends JFrame {
  8    // Text area for displaying contents
  9    private JTextArea jta = new JTextArea();
 10  
 11    public static void main(String[] args) {
 12      new MultiThreadServer();
 13    }
 14  
 15    public MultiThreadServer() {
 16      // Place text area on the frame
 17      setLayout(new BorderLayout());
 18      add(new JScrollPane(jta), BorderLayout.CENTER);
 19  
 20      setTitle("MultiThreadServer");
 21      setSize(500, 300);
 22      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 23      setVisible(true); // It is necessary to show the frame here!
 24  
 25      try {
 26        // Create a server socket
 27        ServerSocket serverSocket = new ServerSocket(8000);
 28        jta.append("MultiThreadServer started at " + new Date() + '\n');
 29  
 30        // Number a client
 31        int clientNo = 1;
 32  
 33        while (true) {
 34          // Listen for a new connection request
 35          Socket socket = serverSocket.accept();
 36  
 37          // Display the client number
 38          jta.append("Starting thread for client " + clientNo +
 39            " at " + new Date() + '\n');
 40  
 41          // Find the client's host name, and IP address
 42          InetAddress inetAddress = socket.getInetAddress();
 43          jta.append("Client " + clientNo + "'s host name is "
 44            + inetAddress.getHostName() + "\n");
 45          jta.append("Client " + clientNo + "'s IP Address is "
 46            + inetAddress.getHostAddress() + "\n");
 47  
 48          // Create a new thread for the connection
 49          HandleAClient task = new HandleAClient(socket);
 50  
 51          // Start the new thread
 52          new Thread(task).start();
 53  
 54          // Increment clientNo
 55          clientNo++;
 56        }
 57      }
 58      catch(IOException ex) {
 59        System.err.println(ex);
 60      }
 61    }
 62  
 63    // Inner class
 64    // Define the thread class for handling new connection
 65    class HandleAClient implements Runnable {
 66      private Socket socket; // A connected socket
 67  
 68      /** Construct a thread */
 69      public HandleAClient(Socket socket) {
 70        this.socket = socket;
 71      }
 72  
 73      /** Run a thread */
 74      public void run() {
 75        try {
 76          // Create data input and output streams
 77          DataInputStream inputFromClient = new DataInputStream(
 78            socket.getInputStream());
 79          DataOutputStream outputToClient = new DataOutputStream(
 80            socket.getOutputStream());
 81  
 82          // Continuously serve the client
 83          while (true) {
 84            // Receive radius from the client
 85            double radius = inputFromClient.readDouble();
 86  
 87            // Compute area
 88            double area = radius * radius * Math.PI;
 89  
 90            // Send area back to the client
 91            outputToClient.writeDouble(area);
 92  
 93            jta.append("radius received from client: " +
 94              radius + '\n');
 95            jta.append("Area found: " + area + '\n');
 96          }
 97        }
 98        catch(IOException e) {
 99          System.err.println(e);
100        }
101      }
102    }
103  }
Note: you are highly encouraged to read chapter 33 thoroughly to understand this topic well.

Java Threads and Java Beans

Java Threads and Java Beans

1. The Concepts of Thread

1.1 What is a Thread?

What exactly is a thread? The term thread is shorthand for thread of control, and a thread of control is, at its simplest, a section of code executed independently of other threads of control within a single program.
A thread is the path taken by a program for running a task. For example, when the computer executes our ordinary programs, the execution follows the path we arranged in the program, from the entry point to the exit of the program. In the program we may need to complete a series of tasks, for example, read data from a file, process the data and write the result to another file, display an image etc. No matter how many tasks to be completed (like a to-do list) we follow the arranged path or order to get them done. Even you are running the program on a powerful computer, for example, multiprocessor computer, you still run the program in the designed order, task by task. If the tasks are not strongly dependent of each other, why don’t we put tasks into two to-do lists, then let the program concurrently do the tasks in the two lists when we have, for example, two processors on a computer. Each processor executes the tasks in one list. If this is true, we say we have two threads in the program.
Of course, not each computer has more than one processors. As the modern computer is very powerful, we can split the time into small slots. On one slot, the program execute the tasks from one listl, on the other slot from the other list. In the point of the user’s view, tasks in the two lists are concurrently executed. This technique is called multitasking. Your window system uses this technique so that you can do tasks like editing files when the IE browser is downloading a large file from the Internet.
That is the core of multithreading. We arrange a program in several threads, and let the program be concurrently run on several threads (paths).
Figure 32.1 in the text shows how multiple threads are concurrently run on single processor and multiprocessor machines, respectively.
Java provides the capability which enables you to design threads for your programs.

1.2  Why Threads?

Actually threads are everywhere. Even if your program never explicitly creates a thread, the system may create threads on your behalf. For example, when your program begins an application, the Java interpreter starts a thread for the main method and a thread for JVM housekeeping tasks (garbage collection, finalization). The AWT and Swing user interface frameworks create threads for managing user interface events. They are running behind your programs concurrently.

2. Creating Tasks and Threads

2.1 Tasks

To efficiently design multithread program for your jobs, you need to identify tasks and the dependence of tasks. Tasks are about what need to be done.
In Java, tasks are considered as objects. To create tasks, you have to first declare a class for tasks. A task class must implement the Runnable interface which only has the run method. The only you need to do is to implement this method for your task class.
Here is the template for defining your own task class
public class MyTasks implements Runnable {
public MyTasks( .. )  {
//The jobs here
}
     public void run() {
//how to do
}
}
Then you can create a task instance by using new operator with the tasks class constructor.

2.2 Creating a Thread for a Task

A task must be executed in a thread. Think about the ordinary programs you have written so far in this way: you define classes and methods (tasks) and then use them in the main method. That is, you put your tasks in the main thread to run.
Similarly once you have created your tasks, you need to put them into a thread to run. The Thread class contains the constructors for you to create threads with tasks and many useful methods for controlling threads.
Creating a thread for a task is very simple
Thread mythread = new Thread(myTask);

2.3 Invoking a Thread to Execute its Task

After you define a thread for a task, you need to tell the JVM that the thread is ready to run by calling its start method
mythread.start();
The program in Listing 32.1 is a good example of using threads.

3. The Thread class

The Thread class defines several useful methods that you can use to control and manipulate threads.
You can use the isAlive() method to test if the thread is currently running or has been dead. The JVM randomly chooses the ready threads to run when the resource is available. However you can change this by setting a higher priority with the methodsetPriority(int p) to the thread you want to be run as soon as possible.  
You can use the yield() method to temporarily release time for other threads and you can put a thread to sleep (don’t do work) for a while with the method sleep(long mills). You can use the join() method to force one thread to wait for another thread to finish.
Please read Section 32.4 carefully and try to understand the meaning of each method in the Thread class.

4. The Thread Synchronization

Here we look at the issue of sharing data between threads. Threads are the execution paths in a major program. The data information in the program may be shared by threads.
As an application example, let us look at the system for the automated teller machine (ATM). You can imagine that the operation of an ATM is a thread in the whole Bank system. Thus the system maintains a lot of threads at the same time. Account information shall be shared among all the threads.
There are scenarios in which it is possible two people to have access to the same account (e.g. a joint account). One day, a husband and wife both decide to empty the same account at the almost same time on two different ATMs (purely by chance). It is possible for two ATMs to confirm that the account has enough cash and dispense it to both parties, because the two users are causing two threads to access the account database at the same time.
It is called a race condition because the action of checking the account and changing the account status is not atomic. The term atomic is related to the atom, once considered the smallest possible unit of the matter, unable to be broken into separate parts. When a routine is considered atomic, it cannot be interrupted during its execution. In our ATM example, if the acts of “checking on the account” and “changing the account status (taking money)” were atomic, it would not be possible for another thread to check same account until the first thread had finished changing the account status.
The Java specification provides certain mechanisms that deal specifically with this problem. The Java language provides the synchronized keyword to force a method or a piece of code to be atomic. In our example, we can define a method which completes the checking andd changing as a synchronized one. Then we can make sure the account data is in the right status.
Read Section 32.9 again.
Except for the synchronized keyword, Java provides many other techniques to make threads safe, for example, Block queues, semaphores etc. If you are interested in the Java concurrent programming, I suggest you should read the Java document on the recent development on the concurrent framework
http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/package-summary.html

5. The JavaBeans Components
    

Readings 

What you need:

  • To work with JavaBeans you need a Builder tool. I suggest you should install the NetBeans IDE to your computer. It is free and can be downloaded from http://www.netbeans.info/downloads/index.php. It can completely replace the JCreator IDE that you have been using so far.

5.1 Introduction to Beans

The official definition of a bean, as given in the JavaBeans specification, is “A bean is a reusable software component based on Sun’s JavaBeans specification that can be manipulated visually in a builder tool”.
Once you implement a bean, others can use it in a builder environment to produce GUI applications more efficiently.

5.2 What does a Bean look like?

A good example of a bean with rich behavior is CalendarBean by Kai Todter. The bean and its source code are freely available fromhttp://www.toedter.com/en/jcalendar. This bean gives users a convenient way of entering dates, simply by locating them in a calendar display. The figure below shows a demo image
The top half shows the appearance of the bean. Do you like it? If you have an application in which you want to the user input dates, would you like to present the user this visual input chart so that the user can input dates by justing clicking mouse? However you don’t want to code this chart from the scratch, do you?
Kai Todter has done everything for you. If you are going to use this component in your application, you only need to drop this bean into your application with Builder tool like the NetBeans. When you open the bean in the Builder tool, you can customer it to your specification, for example, you can set the property Locale to Australia, see the bottom half of the figure as well as other properties to specify your needs. Finally you will have this calendar in your application.

5.3 Where are Beans?

Actually NetBeans IDE provides a method for you to visually design the user interface for your application. After launching the NetBeans IDE you see the main window of the application as shown below
Here I am not going to teach how to use the NetBeans IDE to create an application (or project), but just let you know you can design GUI for your application visually with NetBeans IDE.
If you click on the + sign of Swing in the Palette you will a lot of Swing components like JLabel, JButton etc. That means you can add these components into your application visually and the NetBeans will write the appropriate for you. If you consider a bean as a special component, then using a bean in your project is just like adding a Swing component into your GUI.
You can see Kai’s JDateChooser bean has been in the Beans folder. It is simple to add a bean into NetBeans IDE for later use. Kai’s beans are packed in a jar file. I suppose you have downloaded the jcalendar-1.3.2.jar file. Now click on “Tools” and then choose the Palatte Manager, on the pop-up window choose “Add From JAR” button and specify the location of jcalendar-1.3.2.jar and following the instructions you can add the JDateChooser bean into NetBeans IDE. Then you can use it in any projects that you are going to develop.

6. Creating a Bean

Indeed Kai’s Calender beans are quite complicated. Here I am going to work through all the steps for creating a simple bean. Usually you should follow the following procedures;
  • Writing code for a bean (of course you can use NetBeans to create a bean)
  • Compiling the bean
  • Generating a Java Archive (JAR) file
  • Loading the bean into the GUI Builder of the NetBeans IDE
  • Inspecting the bean's properties and events for later use
The bean we are going to create is an image icon label.

6.1 The code for the Label

import javax.swing.*;
import java.util.*;
import javax.imageio.*;
import java.awt.*;
import java.io.*;
public class MyBean extends JLabel {

public MyBean(){
setBorder(BorderFactory.createEtchedBorder());
try {
file = new File("icon.jpg");
setIcon(new ImageIcon(ImageIO.read(file)));
}
catch (IOException e) {
file = null;
setIcon(null);
}
}

private File file = null;
}

6.2 Creating the Bean

First you can compile the file with either JCreator or NetBeans to get the class file MyBean.class
Then edit a manifest fule MyBean.mf for the bean
Manifest-Version: 1.0
Name: MyBean.class
Java-Bean: True
Note the blank line between the manifest version and bean name.
To make the JAR file, use the command below
jar cvfm MyBean.jar MyBean.mf MyBean.class
Then you can also add other items, such as JPG files for icons to the JAR file. Then bean can be used in any application just as other beans although our bean is so simple (just a label).