JAVA QUICK REFERENCE GUIDE Matt Mahoney, mmahoney@cs.fit.edu http://www.cs.fit.edu/~mmahoney/cse3103/java/java.txt INTRODUCTION This guide introduces enough information to write Java programs. For details, see the tutorial at http://java.sun.com/docs/books/tutorial and full documentation that comes with the JDK at http://www.javasoft.com Please report errors to mmahoney@cs.fit.edu PROGRAM STRUCTURE Each Java source code file has (in order) an optional package statement (default is anonymous package/current directory), 0 or more import statements, and 1 or more classes, exactly one of which must be public and have the same name as the source code file (case sensitive, minus the .java extension). The package statement identifies the subdirectories for the .java file and resulting compiled .class files, relative to the current directory, Java library directory, and directories in CLASSPATH. The public class for which the program is named must have method main() declared exactly as below. For example: /* multiline comment: this is file c:\test\my\pkg\Example.java */ package my.pkg; // in directory my\pkg import java.io.PrintStream; // import a single class in package java.io import java.io.*; // import all classes (but not subpackages) public class Example { public static void main(String args[]) { // start here System.out.println("Hello "+args[0]); } } set CLASSPATH=c:\test javac c:\test\my\pkg\Example.java (produces c:\test\my\pkg\Example.class) java my.pkg.Example world (prints Hello world) TYPES All numbers default to 0 boolean b1=true, b2; // default is false byte z1=127, z2=0377, z3=0x7f; // -128 to 127, 8 bits char c1='a', c2='\n', c3='\ffff'; // unicode character, 16 bits short sh; // -32768 to 32767, 16 bits int i, j; // -2147483648 to 2147483647, 32 bits long l; // signed, 64 bits float f=3.40282e38; // 32 bit IEEE real double d=1.79769313486231e308; // 64 bit IEEE real String s="Hello\n"; // unicode array int[] a=new int[10]; // array a[0] to a[9], all 0's int a[]={0,1,2,3,4,5,6,7,8,9}; // initialized array, a.length is 10 int a2[][]=new int[10][20]; // 2-D array, a[0][0] to a[9][19] T x1=null, x2=new T; // reference to type T, default is null final int k=0; // constant OPERATORS By precedence (like C) 1. i++ // i=i+1, return old i ++i // i=i+1, return new i i--, --i // i=i-1, return old or new i +i // promote byte or short to int -i // negation ~i // bitwise complement !b // negation of boolean (T) i // convert (cast) to type T 2. i*j, i/j, i%j // multiply, divide, remainder 3. i+j, i-j // add, subtract i+s, s+i, s+s // String concatenation with i.toString() 4. i<>j // shift i by j bits to left or right i>>>j // unsigned right shift 5. ij, i>=j // comparisons, return boolean x instanceof T // true if x is type T or derived from T 6. i==j, i!=j // equals, not equals? x==y, x!=y // refer to same, different objects? 7. i&j // bitwise and 8. i^j // bitwise exclusive or 9. i|j // bitwise or 10. b1 && b2 // and then (may not evaluate right side) 11. b1 || b2 // or else (may not evaluate right side) 12. b ? x : y // if b then x else y 13. x=y // assignment x+=y // x=x+y, also += -= *= /= // <<= >>= >>>= &= ^= |= Levels 1, 12, 13 associate right to left, others are left to right. STATEMENTS {e1; e2;} // sequence of declarations and statements {int i; i=3;} // i is local to the block if (b) e; // do e if b is true if (b) e1; else e2; // do e1 if b is true, e2 if false while (b) e; // loop while b is true do e; while (b); // loop 1 or more times for (e1; e2; e3) e4; // e1; while (e2) {e4; e3;} break; // jump out of loop break a; // jump out of labeled loop (a: while) return e; // return from a function with a value // Also, switch and continue as in C. CLASSES class T { // defines a new type int i, j=0; // instance variables, default is 0 T() {i=0;} // constructor, initializes instances T(int x, int y) {i=x; j=y;} // constructor taking parameters T(int x) {this(x, 0);} // calling another constructor void f() {int n=i;} // method with local variable int g(int k) {return i+j+k;} // method taking paramters int h() {return this.i;} // this = current object (return i;) void finalize() {} // destructor static int m; // T.m shared by all instances of T static int s() {return m;} // no this, can be called T.s(); static {m=1;} // static initializer class Inner { /*...*/ } // Java 1.1: nested class T.Inner } T x1=new T(); // create instance of T, x1.i == 0 T x2=new T(3); // create, x2.i == 3 x2.f(); // call method x1.i=x2.g(4); // call with argument, x1.i = 7 T.s(); // call static method INHERITANCE class U extends T { // subclass inherits T's contents void f() {++i;} // overrides T.f() U() {super(1, 2);} // call superclass constructor (T) final void g(); // cannot be overridden } T t=new U(); // base reference to subclass OK t.f(); // calls U.f() U u=(U) t; // conversion to superclass must be cast final class V { //... // cannot be extended abstract class A { // contains 1 or more abstract methods abstract void f(); // no body, override to instantiate } interface B1 { // contains only abstract methods void g(); // "abstract" is implied } class C extends A implements B1, B2 { // may implement multiple interfaces T t = new T() { /* class def */ } // Java 1.1: anonymous subclass DATA HIDING public class T { // in file T.java, visible outside package public void f() {} // visible outside package private int i; // visible only in class (i.e. to f()) int j; // visible in package protected int k; // visible in package and to subclasses } STANDARD PACKAGES - JAVA 1.0 java.lang // automatically imported Object // root of all classes x.equals(y) // Objects x and y equal? if (x instanceof Cloneable) // else throws CloneNotSupportedException y=x.clone(); // copy s=x.toString(); // convert to String x.finalize() {} // destructor class T implements Cloneable // supports clone() Boolean // wrapper for boolean new Boolean(b).booleanValue() // returns boolean b Character // wrapper for char new Character(c).charValue() // returns char c Character.isDigit(c) // c in 0..9? Character.isLowerCase(c) // c in a..z? Character.isUpperCase(c) // c in A..Z? Character.isSpace(c) // whitespace? c=Character.toLowerCase(c) // also toUpperCase Double // wrapper for double new Double(1.23).doubleValue()// 1.23 new Double("1.23") // throws NumberFormatException Integer // wrapper for int new Integer(3).intValue() // 3 new Integer("3") // throws NumberFormatException int i=Integer.parseInt("3"); // convert, throws... // also wrapper classes Long, Float Math // All members are static (Math.E, etc.) E, PI // constants Math.PI = 3.14159265... abs(x), min(x,y), max(x,y) // int, float, long, double sin(x), cos(x), tan(x) // in radians asin(x), acos(x), atan(x) // inverse trig sinh(x), cosh(x), tanh(x) // hyperbolic ceil(x), floor(x) // return integer value as double round(x) // return long random() // double between 0 and 1 exp(x), log(x) sqrt(x) // E to x, natural log, sqrt (double) pow(x,y) // power (double) Runtime Runtime.getRuntime().exec("dir"); // Run system command (IOException) String // constant sequence of Unicode characters String s="abcde"; // create s.charAt(1); // 'b' s.length() // 5 s.substring(2,4) // "cd" s.substring(2) // "cde" s.compareTo("xyz") // >0 if >, <0 if <, 0 if equal s.equals("abcde") // true s.equalsIgnoreCase("AbCdE") // true s+"fgh" // "abcdefgh" 1+s+2 // "1abcde2" s.indexOf("cd") // 2 (-1 if not found), also 'c' String(a, 100, 10) // convert from byte[100..109] System int c=System.in.read(); // input byte, -1 = EOF System.out.print(x); // print String or primitive type to stdout System.out.flush(); // force pending output System.err.println(x); // print to stderr + "\n", flush System.arraycopy(a, 1, b, 2, 10); // copy a[1..10] to b[2..11] long l=System.currentTimeMillis(); // since 0000 GMT Jan. 1 1970 System.exit(1); // exit program Thread // task or process (implements Runnable) class T implements Runnable { // must override void run(); public void run() { sleep(100); // pause 100ms, throws InterruptedException x.wait(100); // wait 100ms (optional) for interrupt synchronized (x) { // only one thread, x is any Object x.wait(100); // wait 100ms (optional) for interrupt x.notify(); // interrupt one other waiting thread x.notifyAll();}} // interrupt all waiting threads synchronized void f() {} // synchronize (this) Thread t = new Thread(new T(), "optional name")); t.start(); // Start T.run() t.interrupt(); // wake if sleeping t.interrupted(); // true after interrupt Throwable class Error extends Throwable // need not be declared class Exception extends Throwable // must be declared with throws: void f() throws Exception; // or may throw a subclass class RuntimeException extends Exception // need not be declared try { // code that might throw exception throw new Exception("msg");}// msg is optional, jump to catch catch (Exception x) { // also catches a subclass System.out.println(x);} // print msg // Some important exceptions Throwable Error // generally do not catch errors LinkageError ThreadDeath // Thread.stop() VirtualMachineError OutOfMemoryError StackOverflowError AWTError // java.awt Exception RuntimeException // "throws" not needed ArithmeticException ClassCastException // test using "instanceof" IndexOutOfBoundsException NullPointerException SecurityException // applets IllegalArgumentException NumberFormatException // The following require a "throws" clause if not caught CloneNotSupportedException InterruptedException // Thread.interrupt() during wait, sleep IOException // java.io EOFException // read past end of file FileNotFoundException InterruptedIOException // interrupt() on blocked read MalformedURLException // java.net SocketException // java.net UnknownHostException // java.net // create exception class public class MyException extends Throwable { // or any subclass of public MyException() {} public MyException(String s) {super(s);} } java.util Bitset // infinite array of boolean Bitset b=new Bitset(10) // initial size optional, will grow b.get(i) // initially false, i is int b.set(i), b.clear(i) // set bit i to true, false b.and(b), b.or(b), b.xor(b) // logical operations to b b.size() // 10? Date d=new Date(System.currentTimeMillis()) // current date and time Date d=new Date(); // same d=new Date(1,2,3,4,5,6) // Feb 3 1901 04:05:06 (4, 5 & 6 optional) d.after(d) // compare? also before, equals d.getDate() // also Year, Month Day, Hours, Minutes, Seconds, also set toGMTString(), toLocaleString() // for display Hashtable // key to value mapping (both Objects) Dictionary h=new Hashtable(); // create h.put(key, value); // associate value with key or update it h.get(key); // value (as an Object) h.remove(key); // remove key and its value for (Enumeration e=h.keys(); e.hasMoreElements(); ) key=e.nextElement() // get all keys Properties extends Hashtable // String to String Hashtable p.getProperty("key", ""); // get "value" or default "" p.load(in); // read from InputStream p.save(out); // save to OutputStream p.list(out); // print Random Random r=new Random(seed); // long seed overrides time r.nextInt(), r.nextLong(); // 32, 64 random bits r.nextFloat(), r.nextDouble(); // 0 to 1 r.nextGaussian(); // mean 0, standard deviation 1 r.setSeed(seed); // reset StringTokenizer // parser st = new StringTokenizer(s, " \n\t", false); // parse s on, discard space while (st.hasMoreElements()) s = nextToken(); // get words Vector // unbounded array of Objects v=new Vector(); // create v.copyInto(a); // copy Object[] v.addElement(x); // append v.size(); // number of elements v.setSize(i); // change size v.elementAt(i); // i'th Object v.insertElementAt(x, i); // put at i v.removeElementAt(i); // remove from i Stack extends Vector // stack s.empty(); // size is 0? s.push(x) // put on top s.peek(); // Object at top s.pop(); // removes top java.io // Input from file or System.in try { // read from file InputStream f=new FileInputStream("filename"); // open file int c=f.read(); // read 1 byte, -1 is EOF int n=f.read(a); // read n bytes into byte[] a n=f.read(a, 100, 10); // read n bytes into a[100..109] n=f.available(); // bytes to read before blocking f.skip(n); // read and discard n bytes f.close(); // close file (in finalize()) FilterInputStream ff=new BufferedInputStream( new FileInputStream("filename")); // faster input if (ff.markSupported()) { // can call mark(), reset()? ff.mark(n); // prepare to go back n bytes to here ff.reset();} // go back to mark } catch (FileNotFoundException x) {} // "filename" not found? catch (IOException x) {} // read error (not EOF) // Read line in Java 1.1 BufferedReader f=new BufferedReader(new InputStreamReader(System.in)); s=f.readLine(); // read line of stdin to String s // System.in may also be new FileInputStream("filename") // Output (Java 1.0+) try { OutputStream f=new FileOutputStream("filename"); // create file f.write(c); // write byte c f.write(a); // write byte[] array a f.write(a, 100, 10); // write a[100..109] f.flush(); // force pending output f.close(); // close file FilterOutputStream ff=new PrintStream(new BufferedOutputStream( new FileOutputStream("filename"))); // faster output with formatting ff.print(x); // like System.out ff.println(x); // like System.out } catch (IOException x) {} // write error File f=new File("filename"); // A file name (not the file itself) if (f.isDirectory()) // also exists(), canWrite(), canRead() // isFile(), mkdir(), mkdirs(), createNewFile(), delete(), // renameTo("newname") long time=f.lastModified(); // when written? long n=f.length(); // how many bytes? File.separator; // "/" or "\" java.net try { // read web page URL url=new URL("http://dot.com/index.html"); // open web page InputStream f=url.openStream();} // use f.read() to read page catch (MalformedURLException x) {} // bad URL catch (IOException) {} // cannot read try { // connect to server Socket s=new Socket("dot.com", 80); // host, TCP port InputStream in=s.getInputStream(); // read from in like a file OutputStream out=s.getOutputStream(); // write like a file s.close();} // disconnect s=new Socket("dot.com", 17, false); // UDP protocol catch (UnknownHostException x) {} // DNS error catch (IOException x) {} // other error try { // run a server ServerSocket ss=new ServerSocket(80); // listen on port 80 Socket s=ss.accept(); // wait for a client InetAddress ia=ss.getInetAddress(); // get client address byte[] ba=ia.getAddress(); // remote IP address as 4 bytes String s=ia.getHostName();} // remote host catch (IOException) {} // socket error try { // send/receive UDP datagrams ia=new InetAddress(InetAddress.getByName("dot.com")); // send to DatagramPacket dp=new DatagramPacket(a, n, ia, 80); new DatagramSocket().send(dp);} // send n bytes of a[] to ia on port 80 dp=new Datagram(a, n); // receive n bytes into a[n] ds=new DatagramSocket(80); // wait on port 80 ds.receive(dp); // wait ia=dp.getAddress(); // sender's address a=dp.getData();} // get dp.getLength() bytes catch (SocketException x) {} // can't get port catch (IOException x) {} // send/receive error java.awt // abstact windows toolkit Component (Applet, Frame) // anything visible on screen // catch mouse events (only x and y are useful) // return true if handled public boolean mouseDown (Event e, int x, int y) {} public boolean mouseDrag (Event e, int x, int y) {} public boolean mouseEnter(Event e, int x, int y) {} public boolean mouseExit (Event e, int x, int y) {} public boolean mouseMove (Event e, int x, int y) {} public boolean mouseUp (Event e, int x, int y) { if (e.metaDown());} // right mouse button public boolean action(Event e, Object x) {} // from child e.target public boolean gotFocus (Event e, Object x) {} // active window public boolean lostFocus (Event e, Object x) {} public boolean keyDown(Event e, int key) {} // from keyboard public boolean keyUp (Event e, int key) {} public boolean handleEvent(Event e) { // general handler if (e.id==Event.WINDOW_DESTROY));} // user closed window? public void paint(Graphics g) {} // need to redraw screen public void print(Graphics g) {} // overrides paint() to printer public void update(Graphics g) { // need to clear and redraw g.setColor(getBackground()); // default is to clear screen... g.fillRect(0, 0, size().width, size().height); // ...and call paint() g.setColor(getForeground()); paint(g);} } c.bounds().width; // size, also height (Java 1.0) c.getBounds().height(); // (Java 1.1) c.resize(width, height); // request size change (Java 1.0) c.setSize(width, height); // (Java 1.1) c.setBounds(x, y, width, height); // req. position/size (Java 1.1) c.setBackground(Color.white); // or black, red, green, blue... c.setForeground(new Color(r, g, b)); // 0 to 255 c.setFont(new Font("Serif", Font.PLAIN, 12)); // 12 point Times Roman // also "SansSerif", "Monospaced", BOLD, ITALIC c.show(true); // make visible on screen c.repaint(); // force paint() Container extends Component (Applet, Frame) // may contain Components c.add(x); // add child Component setLayout(new FlowLayout()); // add in rows, centered setLayout(new FlowLayout(FlowLayout.LEFT)); // or RIGHT justify setLayout(new BorderLayout()); // 5 regions c.add("North", x); // or South, East, West, Center setLayout(new GridLayout(2, 3); // layout in 2 by 3 grid setLayout(new GridLayout(2, 3, 4, 5); // x gap 4 pixels, y gap 5 Panel extends Container // For fine control over layout new Panel(new FlowLayout()); // Java 1.1, default layout Window extends Container (Frame, Dialog) w.pack(); // calculate size before show w.show(); // make visible w.toFront(); // put on top, also toBack() w.dispose(); // call before closing Frame extends Window // standalone application window f=new Frame("title"); // create f.setResizeable(false); // disallow user to resize // extend and use add, event handlers, pack, show public boolean handleEvent(Event e) { // catch window close if (e.id==Event.WINDOW_DESTROY) { dispose(); System.exit(0);} return super.handleEvent(e);} Button b=new Button("label"); // create pushbutton add(b); // add to container public void action(Event e, Object x) { // in container... if (e.target==b) // detect button press Checkbox c=new Checkbox("label"); // create if (c.getState()) // checked? CheckboxGroup // radio buttons cb=new CheckboxGroup(); // only 1 in group can be on c=new Checkbox("label", cb, true); // add c to group, initially on c=cb.getCurrent(); // which Checkbox is on? Choice // option menu ch=new Choice(); // create ch.addItem("label"); // add a choice String s=ch.getSelectedItem(); // "label" selected by user int n=ch.getSelectedIndex(); // position of selected "label" Label // text on the screen l=new Label("text", Label.LEFT); // justify LEFT, CENTER, RIGHT l.setText("new text"); // change label // also setFont, setForeground, setBackground, resize List // multiple choice scrolling menu l=new List(n, true); // n rows shown, allow >1 choices l.addItem("label"); // add a label string[] s=getSelectedItems(); // get all selected labels int[] a=l.getSelectedIndexes(); // get all selected positions // double click on item calls action(e, x), e.target==l Scrollbar s=new Scrollbar(Scrollbar.VERTICAL, 50, 10, 0, 100); // or HORIZONTAL, handle at 50, width 10, range 0 to 100 s.setValue(50); // reposition s.setLineIncrement(1); // move 1 when clicking on arrow s.setPageIncrement(10); // move 10 on page up/down boolean handleEvent(Event e) { // catch scroll movement if (e.target==s) i=((Integer)e.arg).intValue(); // scroll to i TextComponent (TextField, TextArea) String s=getText(); // entered by user s=getSelectedText(); // highlighted by user setText(s); // change text select(getSelectionStart(), getSelectionEnd()); // highlighted text selectAll(); // highlight all setEditable(false); // disallow user editing TextField // one line t=new TextField("", 20); // initial value, 20 columns t.setEchoChar('*'); // password field TextArea // edit window t=new TextArea("", 80, 24); // initial value, columns, rows t.appendText("end"); // t.append("end") in Java 1.1+ t.insertText("middle", i); // insert at i t.replaceText("middle", i, j); // replace i..j Toolkit // system-dependent properties Toolkit.getDefaultToolkit().getScreenSize().width // or height Toolkit.getDefaultToolkit().getFontList() // font names in a String[] Graphics // for drawing Graphics g=component.getGraphics(); // or from paint(g) g.setColor(Color.BLACK); // or new Color(r, g, b) g.drawLine(x1, y1, x2, y2); // 0, 0 at upper left g.drawRect(x, y, width, height); // draw outline g.fillRect(x, y, width, height); // and interior g.drawOval(x, y, width, height); // of enclosing rectangle g.fillOval(x, y, width, height); g.drawPolygon(xp, yp, n); // int xp[n], yp[n] vertices g.fillPolygon(xp, yp, n); g.drawArc(x, y, width, height, a1, a); // oval through a deg. from a1. g.fillArc(x, y, width, height, a1, a); // pie slice g.drawRoundRect(x, y, width, height, arcWidth, arcHeight); // also fill g.setFont(...); // as in Container g.drawString("text", x, y); // draw text g.dispose(); // if from getGraphics() g.drawImage(img, x, y, this); // draw at x, y; this = Component g.drawImage(img, x, y, width, height, this); // stretch g.setXORMode(getBackground()); // drawing twice erases g.setPaintMode(); // undo setXORMode Image // for drawing off-screen Image img=createImage(width, height); // in Component Graphics g=img.getGraphics(); // for drawing into img img.getWidth(this), img.getHeight(this); // in pixels g.dispose(); // when finished drawing // See MediaTracker to wait for images to download Menu // menu for a frame frame.setMenuBar(new Menubar()); // add menu bar menuBar.add(new Menu("name")); // add menu to bar menu.add(new MenuItem("name")); // add item to menu menuItem.addActionListener(...); // add event handler Dialog // Subclass to produce a pop-up window. See also FileDialog d=new Dialog(frame, "title", isModal); // create d.show(); // make visible d.setVisible(false); // make invisible FileDialog // to prompt for a file name to load/save f=new FileDialog(frame, "title", FileDialog.SAVE); // default is LOAD f.show() // prompt f.getDirectory()+f.getFile(); // get full path of answer java.applet An Applet is a program running in a browser (Netscape 3.0 or IE 3.0 or higher). It cannot access the local disk or memory, run another program, or communicate over the network except with the server from which the .class files were downloaded. The HTML is (codebase and params are optional): class MyApplet extends Applet { // extends Component, Container, Panel void init() {...} // initialization, run once void paint(Graphics g) { // applet needs redrawing String s=getParameter("name1"); // "value1" bounds().width;} // 400, height is 300 void start() {} // applet uncovered by a window void stop() {} // applet covered void destroy() {} // page containing applet is gone } Image getImage(getCodeBase(), "picture.gif"); // download .gif or .jpeg play(getCodeBase(), "sound.au"); // play a sound now AudioClip AudioClip ac=new AudioClip(getCodeBase(), "sound.au"); ac.play(); // play sound ac.loop(); // play over and over ac.stop(); // stop playing showStatus("message"); // write to browser status bar JAVA 1.1 java.awt.event // new event handling model // Catch Frame or Dialog closing (user clicks [X]) w.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { e.getWindow().dispose();}}); // close window // A Listener is an interface. An Adapter class extends it with defaults. // All Listeners with 2 or more methods have Adapters. // Event e.getSource() returns the Object that generated it ActionListener // Button, MenuItem, List double click, TextField enter actionPerformed(ActionEvent e) // String e.getActionCommand() is label AdjustmentListener // Scrollbar adjustmentValueChanged(AdjustmentEvent e) // int e.getValue() is position ComponentListener // any Component componentHidden(ComponentEvent e) // e.getCompoent() is e.getSource() componentMoved(ComponentEvent e) componentResized(ComponentEvent e) componentShown(ComponentEvent e) ContainerListener // any Container containerAdded(ContainerEvent e) // e.getChild() is the added Component containerRemoved(ContainerEvent e) FocusListener // any Component focusGained(FocusEvent e) // if (e.isTemporary()) focusLost(FocusEvent e) ItemListener // Checkbox, CheckboxMenuItem, Choice, List itemStateChanged(ItemEvent e) if (e.getStateChange()==ItemEvent.SELECTED) // checked? KeyListener // Keyboard keyPressed(KeyEvent e) keyReleased(KeyEvent e) int k=e.getKeyCode(); // KeyEvent.VK_ENTER, VK_DELETE, etc. keyTyped(KeyEvent e) char c=e.getKeyChar(); // the character typed MouseListener // Mouse mouseClicked(MouseEvent e) mouseEntered(MouseEvent e) mouseExited(MouseEvent e) mousePressed(MouseEvent e) mouseReleased(MouseEvent e) int x=e.getX(), y=e.getY(); // mouse location if (e.isMetaDown()) // right mouse button MouseMotionListener // Mouse mouseDragged(MouseEvent e) // events as in Mouse mouseMoved(MouseEvent e) TextListener // TextField or TextArea textValueChanged(TextEvent e) WindowListener // Dialog or Frame windowActivated(WindowEvent e) windowClosed(WindowEvent e) windowClosing(WindowEvent e) // user clicks on CLOSE [X] windowDeactivated(WindowEvent e) windowDeiconified(WindowEvent e) windowIconified(WindowEvent e) windowOpened(WindowEvent e) e.getWindow() // the window generating the event java.awt ScrollPane // extends Container new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED); // or _NEVER, _ALWAYS add(component) // normally larger than the ScrollPane PrintJob // to print (not from applets) PrintJob pj=Toolkit.getDefaultToolkit().getPrintJob(frame, "job name", new Properties()); // start job pj.getPageDimension().width; // or height, in pixels pj.getPageResolution(); // 72 pixels per inch Graphics g=pj.getPrintJob(); // start a page (draw to g) g.dispose(); // end page pj.end(); // end job and print component.print(g); // override, defaults to paint(g) container.printAll(g); // print everything in a container java.text DateFormat.getInstance().format(new Date()); // Date/time as a string DateFormat.getDateInstance(DateFormat.DEFAULT); // Date only // also FULL, LONG, MEDIUM, SHORT DateFormat.getTimeInstance(DateFormat.DEFAULT); // Time only DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG); // Both JAVA 1.2 (JAVA 2) javax.swing replaces the components in java.awt with improved "lightweight" components (subclassed from Container). Each component (Frame, Applet, Button, Label, etc.) is replaced with a corresponding JFrame, JApplet, JButton, Jlabel, etc. Main differences are: - Replace add() with getContentPane().add() (optional in Java 5) - Replace setLayout() with getContentPane().setLayout() (optional in Java 5) - Replace paint() with paintComponent() - There is no JCanvas, use JPanel for both drawing and layout control. - Drawing is double buffered by default. See http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/ to compare awt and swing.