Java Coffee Break Newsletter Vol 1, Issue 8 ISSN 1442-3790 One of our most popular sections is our Q&A, where we answer commonly asked questions about Java programming. We have an even larger Q&A section this issue, covering a wide range of topics. If you'd like more Java information, visit our website, at http://www.davidreilly.com/jcb/ - - - - - - - - - - - - - - - - - - - - - - - - - Java Coffee Break News * Free Articles & Tutorials * Merry Christmas, and a Happy New Year * Java Network Programming FAQ Question & Answer * Q&A : How do I playback multimedia files? * Q&A : How do I execute other applications? * Q&A : How do I use really large numbers in Java? * Q&A : How can I change the cursor shape? * Q&A : How do I make my frames close in response to user requests? * Q&A : How do I use hashtables? * Q&A : Is there any way to access C++ objects, and use their methods? * Q&A : How do I handle timeouts in my networking applications? * Q&A : How do I use a proxy server for HTTP requests? 1. Free Articles & Tutorials We've got free articles and tutorials about Java that teach basic programming concepts, right through to advanced topics like networking, JavaBeans & CORBA. For more information, visit the Java Coffee Break at http://www.davidreilly.com/jcb/ 2. Merry Christmas, and a Happy New Year T'is the season to be jolly. Whether you celebrate Christmas, Chanukah, or Kwanzaz, may your holiday season be bright and festive! And if you find yourself leaving things to the last minute like me, you'll probably want to avoid the hustle and bustle of holiday shopping. Why not consider shopping online this season? Amazon.com, one of the world's largest and most respected book and music retailers makes it easy to buy gifts for friends, collegues and loved ones. You'll also be supporting a great Java newsletter! http://www.davidreilly.com/goto.cgi?id=amazon 3. Java Network Programming FAQ This issue contains some tips from the Java Network Programming FAQ, which answers commonly asked networking programming questions. If you'd like to read more, visit http://www.davidreilly.com/java/java_network_programming/ - - - - - - - - - - - - - - - - - - - - - - - - - Q&A : How do I playback multimedia files? I'd like to display .avi, .mpg, and other movie formats. It'd be a tough task to write routines to playback a wide range of multimedia formats. Then you'd have to keep an eye out for new formats, write new code, and make it all so efficient that it can do real-time playback under a Java Virtual Machine. Fortunately, you don't have to do any of this! Sun has been working on the Java Media Framework API, which offers an easy API to playback multimedia files. The API has been available for some time now, and implementations are now available from Sun, Intel, and others. For more information see http://java.sun.com/products/java-media/jmf/index.html - - - - - - - - - - - - - - - - - - - - - - - - - Q&A : How do I execute other applications? Sometimes a pure java implementation doesn't quite cut it. Maybe you need to call some operating system command, or perhaps another application. If you need to run other applications from within your app (you won't be able to do this from an applet for security reasons), then here's what you need to do. Step One Obtain a java.lang.Runtime instance. The java.lang.Runtime class allows you to execute other applications, but you'll need an object reference before you can begin. // Get runtime instance Runtime r = Runtime.getRuntime(); Step Two Next, you'll make a call to execute your application. The exec call returns a Process object, which gives you some control over the new process. If you just need to start something running, then you might want to discard the returned process. // Exec my program Process p = r.exec ("c:\myprog\inc"); Step Three Now, if you want to do something with your process (perhaps kill it after a certain time period, or wait until its finished), you can use the methods of the java.lang.Process class. Check the Java API documentation for more information - there's plenty of things you can do. Suppose you wanted to wait until its terminated, and then continue with your app. Here's how you'd do it. // Wait till its finished p.waitFor(); Easy huh? - - - - - - - - - - - - - - - - - - - - - - - - - Q&A : How do I use really large numbers in Java? There are many classes of applications that require support for large numbers. When primitive data types like long, and double just won't cut it, Java offers an answer in the form of the java.math package. Whether its whole numbers or decimals you need, java.math has the solution. For whole numbers, use the BigInteger class, and for fractions use the BigDecimal class. Each allows a wide range of mathematical operations, from simple things like addition, subtraction, multiplication and division to more complex operations like logical AND, OR, NOT and powers. - - - - - - - - - - - - - - - - - - - - - - - - - Q&A : How can I change the cursor shape? Any graphical component is capable of changing the mouse cursor. As the user moves the cursor over the component, the cursor will change. Setting a new cusor type is easy - every subclass of java.awt.Component has a setCursor method. Individual components, or even applets can specify their own cursor. // Create an instance of java.awt.Cursor Cursor c = new Cursor ( Cursor.WAIT_CURSOR ); // Create a frame to demonstrate use of setCursor method Frame f = new Frame("Cursor demo"); f.setSize(100,100); // Set cursor for the frame component f.setCursor (c); // Show frame f.show(); There isn't a "global" cursor type, so this means that you can have different cursors for different components. But just remember - using cursors inappropriately will make it difficult for users, so don't put an hourglass wait component unless you actually want the user to wait! A full list of cursor types is available from the documentation for java.awt.Cursor. - - - - - - - - - - - - - - - - - - - - - - - - - Q&A : How do I make my frames close in response to user requests? You need to define an event handler for the "WindowClosing" event. Under JDK1.02, you can add the following code to your Frame subclasses. // Response to close events public void WindowClosing(WindowEvent evt) { // Close application System.exit(0); } If you're using JDK1.1 AWT event handlers, you can use the WindowAdapter class for a similar purpose. Here's a simple application that demonstrates the use of WindowAdapter, as an anonymous inner class. import java.awt.*; import java.awt.event.*; public class Demo { public static void main ( String args[] ) { // Create a frame with a button Frame f = new Frame("Demo"); // Add a new button f.add ( new Button("demo") ); // Resize/pack f.pack(); // Add a window listener f.addWindowListener ( new WindowAdapter () { public void windowClosing ( WindowEvent evt ) { System.exit(0); } }); // Show window f.setVisible(true); } } It doesn't take much code to respond to close events, and makes applications look much more professional. Don't forget in your next application! :) - - - - - - - - - - - - - - - - - - - - - - - - - Q&A : How do I use hashtables? Hashtables are an extremely useful mechanism for storing data. Hashtables work by mapping a key to a value, which is stored in an in-memory data structure. Rather than searching through all elements of the hashtable for a matching key, a hashing function analyses a key, and returns an index number. This index matches a stored value, and the data is then accessed. This is an extremely efficient data structure, and one all programmers should remember. Hashtables are supported by Java, in the form of the java.util.Hashtable class. Hashtables accept as keys and values any Java object. You can use a String, for example, as a key, or perhaps a number such as an Integer. However, you can't use a primitive data type, so you'll need to instead use Char, Integer, Long, etc. // Use an Integer as a wrapper for an int Integer integer = new Integer ( i ); hash.put( integer, data); Data is placed into a hashtable through the put method, and can be accessed using the get method. It's important to know the key that maps to a value, otherwise its difficult to get the data back. If you want to process all the elements in a hashtable, you can always ask for an Enumeration of the hashtable's keys. The get method returns an object, which can then be cast back to the original object type. // Get all values with an enumeration of the keys for (Enumeration e = hash.keys(); e.hasMoreElements();) { String str = (String) hash.get( e.nextElement() ); System.out.println (str); } To demonstrate hashtables, I've written a little demo that adds one hundred strings to a hashtable. Each string is indexed by an Integer, which wraps the int primitive data type.  Individual elements can be returned, or the entire list can be displayed. Note that hashtables don't store keys sequentially, so there is no ordering to the list. import java.util.*; public class hash { public static void main (String args[]) throws Exception { // Start with ten, expand by ten when limit reached Hashtable hash = new Hashtable(10,10); for (int i = 0; i <= 100; i++) { Integer integer = new Integer ( i ); // Put entry into hashtable, with an Integer as a key hash.put( integer, "Number : " + i); } // Get specific value matching a key out from hashtable System.out.println (hash.get(new Integer(5))); // Get specific value matching a key out from hashtable System.out.println (hash.get(new Integer(21))); System.in.read(); // Get all values for (Enumeration e = hash.keys(); e.hasMoreElements();) { System.out.println (hash.get(e.nextElement())); } } } - - - - - - - - - - - - - - - - - - - - - - - - - Q&A : How do I handle timeouts in my networking applications? (Reprinted with permission from the Java Network Programming FAQ) If your application is written for JDK1.1 or higher, you can use socket options to generate a timeout after a read operation blocks for a specified length of time. This is by far the easiest method of handling timeouts. A call to the java.net.Socket.setSoTimeout() method allows you to specify the maximum amount of time a Socket I/O operation will block before throwing an InterruptedIOException. This allows you to trap timeouts, and handle them correctly. If your application must support earlier versions of Java, then another option is the use of threads. Multi-threaded applications can wait for timeouts, and then perform some action (such as resetting a connection or notifying the user). For more information on this topic, see "Dealing with network timeouts in Java", Java Developers Journal Volume 3, Issue 5. - - - - - - - - - - - - - - - - - - - - - - - - - Q&A : How do I use a proxy server for HTTP requests? (Reprinted with permission from the Java Network Programming FAQ) When a Java applet under the control of a browser (such as Netscape or Internet Explorer) fetches content via a URLConnection, it will automatically and transparently use the proxy settings of the browser. If you're writing an application, however, you'll have to manually specify the proxy server settings. You can do this when running a Java application, or you can write code that will specify proxy settings automatically for the user (providing you allow the users to customize the settings to suit their proxy servers). To specify proxy settings when running an application, use the -D parameter : jre -DproxySet=true -DproxyHost=myhost -DproxyPort=myport MyApp Alternately, your application can maintain a configuration file, and specify proxy settings before using a URLConnection : // Modify system properties Properties sysProperties = System.getProperties(); // Specify proxy settings sysProperties.setProperty("proxyHost", "myhost"); sysProperties.setProperty("proxyPort", "myport"); sysProperties.setProperty("proxySet", "true"); - - - - - - - - - - - - - - - - - - - - - - - - - The Java Coffee Break Newsletter is only sent out to email subscribers who have requested it, and to readers of the comp.lang.java.programmer and comp.lang.java.help newsgroups. If you'd like to receive our newsletter, and get the latest Java news, tips and articles from our site, then get your FREE subscription from http://www.davidreilly.com/jcb/newsletter/subscribe.html If you are an email subscriber and no longer wish to receive the JCB Newsletter, please unsubscribe using the WWW form located at http://www.davidreilly.com/jcb/newsletter/unsubscribe.html