A Java Crash Course
Document Sample


12/10/97
A Java Crash Course
Dan Wallach, Princeton University
Outline
s Applet “Hello, World”
x graphics
x widgets
s AWT event model
s Multithreaded programming
s Networking
s Utilities and tricks
12/10/97 Wallach / A Java Crash Course 2
1
12/10/97
Starting resources
s If you own only one book...
Java in a Nutshell, David Flanagan (O’Reilly &
Associates)
http://www.ora.com/catalog/javanut/examples/
(examples online!)
s “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 3
Normal Hello World
public class Hello {
public static void main(String args[]) {
System.out.println(“Hello, world.”);
}
}
s Put in: Hello.java
s Compile with: javac Hello.java
· Creates Hello.class
s Run with: java Hello
12/10/97 Wallach / A Java Crash Course 4
2
12/10/97
Applet Hello, world #1
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);
}
}
s paint() called by system when refresh is necessary
s Graphics class has lines, polygons, text, images,
etc.
12/10/97 Wallach / A Java Crash Course 5
Hello, world #2
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);
}
s Make a scrolling text area where you can do terminal-
like output
12/10/97 Wallach / A Java Crash Course 6
3
12/10/97
Hello, world #2 (cont.)
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.”);
}
}
s text printed after program is done
s TextArea widget redraws itself
12/10/97 Wallach / A Java Crash Course 7
Applets in HTML
<applet
CODE=“ScrollingText.class”
CODEBASE=“http://www.whatever.com/applets/”
ARCHIVE=“http://www.whatever.com/applets/ScrollingText.zip” (Netscape 3)
WIDTH=500
HEIGHT=500>
<param name=“text” value=“Dan & Drew’s Excellent Java Class”>
<param name=“speed” value=“5”>
<img src=“nojava.gif” alt=“Oh, you don’t have Java. Sorry.”>
</applet>
s codebase/archive tags are optional
s argument-passing through param tags
12/10/97 Wallach / A Java Crash Course 8
4
12/10/97
Applet class
s java.applet.Applet
x you extend this for your applet
s java.awt.Panel
s java.awt.Container
x applet widget can contain other widgets
s java.awt.Component
x lots of interesting methods here
s java.lang.Object
12/10/97 Wallach / A Java Crash Course 9
Basic methods on Applet
s init()
x called once for your applet
s start()
x called every time you enter the page
s stop()
x called every time you leave the page
s destroy()
x called when your page is discarded
12/10/97 Wallach / A Java Crash Course 10
5
12/10/97
Funky methods on Applet
s AudioClip getAudioClip(URL url)
s Image getImage(URL url)
x starts asynchronous image loading
s void showDocument(URL url)
x tells browser to load new document
x optional second argument for frames
s void showStatus(String msg)
x writes to browser status line
12/10/97 Wallach / A Java Crash Course 11
Applet repainting
s paint()
x defaults to nothing
s update()
x clears screen, calls paint()
s repaint()
x passes events to Motif/Win32
x don’t mess with this
12/10/97 Wallach / A Java Crash Course 12
6
12/10/97
Applet event handling
s boolean handleEvent(Event evt)
x mouse, keyboard, all widget events
x checks event type, then calls...
s mouseUp() / mouseDown() / keyUp() / keyDown()
s action(Event evt, Object arg)
x evt.target - specific widget
x arg - widget-specific result (i.e., new state of a
checkbox)
12/10/97 Wallach / A Java Crash Course 13
Applet event handling
s Centralized event management
x add standard buttons, widgets as children of the top-
level applet
x custom action() method, checks evt.target
s Distributed event management
x subclass buttons, widgets
x custom action() methods in subclasses
12/10/97 Wallach / A Java Crash Course 14
7
12/10/97
Java and threads
s One lock per object plus one per class
s synchronized keyword on a method
s Mesa-style monitors
x wait() / notify() / notifyAll()
x must be called within a synchronized block
s System classes already thread-safe
x HashTable, OutputStream, AWT, etc.
12/10/97 Wallach / A Java Crash Course 15
Thread-safe Message Passing
public class SafeBuffer { synchronized public Object get() {
private Object buffer; while(buffer == null) {
try {
public SafeBuffer() {} wait();
} catch(InterruptedException e) {}
synchronized public void put(Object o) { }
while(buffer != null) { Object tmp = buffer;
try { buffer = null;
wait();
} catch (InterruptedException e) {} notifyAll();
} return tmp;
buffer = o; }
}
notifyAll();
}
Exercise for reader: barrier sync, bounded-buffer
queue, etc.
12/10/97 Wallach / A Java Crash Course 16
8
12/10/97
Starting Threads
class client implements Runnable {
private SafeBuffer b; ...
public client(SafeBuffer b) { SafeBuffer sb = new SafeBuffer();
this.b = b; new Thread(new client(sb)).start();
}
sb.put("Hello, world.");
public void run() {
String s; ...
...
s = (String) b.get();
...
}
}
s Thread constructor takes any object which implements
Runnable
12/10/97 Wallach / A Java Crash Course 17
Networking
s Applet restrictions
x Same IP address which loaded applet
x UDP support is flakey
s Using the browser’s cache
x java.net.URL constructor takes normal string argument
x InputStream toStream()
x only current way to get SSL support
12/10/97 Wallach / A Java Crash Course 18
9
12/10/97
Networking
s client: java.net.Socket
x constructor takes DNS name, port
x getInputStream() / getOutputStream()
s server: java.net.ServerSocket
x constructor takes local port number
x Socket accept()
3 blocks until success -- use multithreading!
12/10/97 Wallach / A Java Crash Course 19
Utilities and tricks
s StringBuffer vs. String
x strings are immutable
x StringBuffer append() is cheaper
s java.util.Hashtable
x uses Object.hashCode() and Object.equals()
s java.util.StringTokenizer
x split string on whitespace / separator chars
12/10/97 Wallach / A Java Crash Course 20
10
12/10/97
Use Javadoc
s Literate programming for Java
x document as you write code
x 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 21
Useful tools
s Debugging / Development
x Microsoft Visual J++ / Symantec Visual Café
3 Debuggers integrated with IE / Netscape
x Kaffe - free JVM with JIT (http://www.kaffe.org)
x Jikes - fast Java compiler from IBM
http://www.alphaworks.ibm.com (?)
x cc-mode for Emacs understands Java
ftp://ftp.python.org/pub/emacs/cc-mode.tar.gz
s When in doubt…
x http://www.developer.com/
12/10/97 Wallach / A Java Crash Course 22
11
Get documents about "