12/10/97 1 A Java Crash Course Dan Wallach, Princeton University 12/10/97 Wallach / A Java Crash Course 2 Outline n Applet “Hello, World” u graphics u widgets n AWT event model n Multithreaded programming n Networking n Utilities and tricks 12/10/97 2 12/10/97 Wallach / A Java Crash Course 3 Starting resources n If you own only one book... Java in a Nutshell, David Flanagan (O’Reilly & Associates) http://www.ora.com/catalog/javanut/examples/ (examples online!) n “Whenever possible, steal code.” [Duff] http://www.developer.com (formerly gamelan.com) http://www.acme.com/java/software/ http://java.sun.com 12/10/97 Wallach / A Java Crash Course 4 Normal Hello World n Put in: Hello.java n Compile with: javac Hello.java ò Creates Hello.class n Run with: java Hello public class Hello { public static void main(String args[]) { System.out.println(“Hello, world.”); } } 12/10/97 3 12/10/97 Wallach / A Java Crash Course 5 Applet Hello, world #1 n paint() called by system when refresh is necessary n Graphics class has lines, polygons, text, images, etc. import java.applet.*; // Don’t forget these import statements! import java.awt.*; public class FirstApplet extends Applet { // This method displays the applet. // The Graphics class is how you do all drawing in Java. public void paint(Graphics g) { g.drawString("Hello, world.", 25, 50); } } 12/10/97 Wallach / A Java Crash Course 6 Hello, world #2 n Make a scrolling text area where you can do terminal- like output import java.applet.*; import java.awt.*; import java.io.*; public class HelloWorld2 extends Applet { TextArea textarea; // Create a text area to send our output public void init() { textarea = new TextArea(20, 60); this.add(textarea); Dimension prefsize = textarea.preferredSize(); this.resize(prefsize.width, prefsize.height); } 12/10/97 4 12/10/97 Wallach / A Java Crash Course 7 Hello, world #2 (cont.) n text printed after program is done n TextArea widget redraws itself public void start() { ByteArrayOutputStream os = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(os); try { go(ps); } catch (Throwable t) {} textarea.setText(os.toString()); } public void go(PrintStream ps) { // your program goes here ps.println(“Hello, world.”); } } 12/10/97 Wallach / A Java Crash Course 8 Applets in HTML n codebase/archive tags are optional n argument-passing through param tags 12/10/97 5 12/10/97 Wallach / A Java Crash Course 9 Applet class n java.applet.Applet u you extend this for your applet n java.awt.Panel n java.awt.Container u applet widget can contain other widgets n java.awt.Component u lots of interesting methods here n java.lang.Object 12/10/97 Wallach / A Java Crash Course 10 Basic methods on Applet n init() u called once for your applet n start() u called every time you enter the page n stop() u called every time you leave the page n destroy() u called when your page is discarded 12/10/97 6 12/10/97 Wallach / A Java Crash Course 11 Funky methods on Applet n AudioClip getAudioClip(URL url) n Image getImage(URL url) u starts asynchronous image loading n void showDocument(URL url) u tells browser to load new document u optional second argument for frames n void showStatus(String msg) u writes to browser status line 12/10/97 Wallach / A Java Crash Course 12 Applet repainting n paint() u defaults to nothing n update() u clears screen, calls paint() n repaint() u passes events to Motif/Win32 u don’t mess with this 12/10/97 7 12/10/97 Wallach / A Java Crash Course 13 Applet event handling n boolean handleEvent(Event evt) u mouse, keyboard, all widget events u checks event type, then calls... n mouseUp() / mouseDown() / keyUp() / keyDown() n action(Event evt, Object arg) u evt.target - specific widget u arg - widget-specific result (i.e., new state of a checkbox) 12/10/97 Wallach / A Java Crash Course 14 Applet event handling n Centralized event management u add standard buttons, widgets as children of the top- level applet u custom action() method, checks evt.target n Distributed event management u subclass buttons, widgets u custom action() methods in subclasses 12/10/97 8 12/10/97 Wallach / A Java Crash Course 15 Java and threads n One lock per object plus one per class n synchronized keyword on a method n Mesa-style monitors u wait() / notify() / notifyAll() u must be called within a synchronized block n System classes already thread-safe u HashTable, OutputStream, AWT, etc. 12/10/97 Wallach / A Java Crash Course 16 Thread-safe Message Passing Exercise for reader: barrier sync, bounded-buffer queue, etc. public class SafeBuffer { private Object buffer; public SafeBuffer() {} synchronized public void put(Object o) { while(buffer != null) { try { wait(); } catch (InterruptedException e) {} } buffer = o; notifyAll(); } synchronized public Object get() { while(buffer == null) { try { wait(); } catch(InterruptedException e) {} } Object tmp = buffer; buffer = null; notifyAll(); return tmp; } } 12/10/97 9 12/10/97 Wallach / A Java Crash Course 17 Starting Threads n Thread constructor takes any object which implements Runnable class client implements Runnable { private SafeBuffer b; public client(SafeBuffer b) { this.b = b; } public void run() { String s; ... s = (String) b.get(); ... } } ... SafeBuffer sb = new SafeBuffer(); new Thread(new client(sb)).start(); sb.put("Hello, world."); ... 12/10/97 Wallach / A Java Crash Course 18 Networking n Applet restrictions u Same IP address which loaded applet u UDP support is flakey n Using the browser’s cache u java.net.URL constructor takes normal string argument u InputStream toStream() u only current way to get SSL support 12/10/97 10 12/10/97 Wallach / A Java Crash Course 19 Networking n client: java.net.Socket u constructor takes DNS name, port u getInputStream() / getOutputStream() n server: java.net.ServerSocket u constructor takes local port number u Socket accept() F blocks until success -- use multithreading! 12/10/97 Wallach / A Java Crash Course 20 Utilities and tricks n StringBuffer vs. String u strings are immutable u StringBuffer append() is cheaper n java.util.Hashtable u uses Object.hashCode() and Object.equals() n java.util.StringTokenizer u split string on whitespace / separator chars 12/10/97 11 12/10/97 Wallach / A Java Crash Course 21 Use Javadoc n Literate programming for Java u document as you write code u generates pretty, cross-linked HTML /** * Creates an absolute URL from the specified protocol, * host, port and file. * @param protocol the protocol to use * @param host the host to connect to * @param port the port at that host to connect to * @param file the file on that host * @exception MalformedURLException If an unknown protocol is * found. */ public URL(String protocol, String host, int port, String file) throws MalformedURLException { ... 12/10/97 Wallach / A Java Crash Course 22 Useful tools n Debugging / Development u Microsoft Visual J++ / Symantec Visual Café F Debuggers integrated with IE / Netscape u Kaffe - free JVM with JIT (http://www.kaffe.org) u Jikes - fast Java compiler from IBM http://www.alphaworks.ibm.com (?) u cc-mode for Emacs understands Java ftp://ftp.python.org/pub/emacs/cc-mode.tar.gz n When in doubt… u http://www.developer.com/