Commit 65235aad authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.
Browse files

Initial commit

parents
Loading
Loading
Loading
Loading

README.md

0 → 100644
+15 −0
Changes for README.md: 15 added lines, 0 removed lines.
Original line number Diff line number Diff line
## Example files for the title:  
	  
# Java in a Nutshell 2nd Edition, by David Flanagan
	  
[![Java in a Nutshell 2nd Edition, by David Flanagan](http://akamaicovers.oreilly.com/images/9781565922624/cat.gif)](https://www.safaribooksonline.com/)
	  
The following applies to example files from material published by O’Reilly Media, Inc. Content from other publishers may include different rules of usage. Please refer to any additional usage rights explained in the actual example files or refer to the publisher’s website.
	  
O'Reilly books are here to help you get your job done. In general, you may use the code in O'Reilly books in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from our books does not require permission. Answering a question by citing our books and quoting example code does not require permission. On the other hand, selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Incorporating a significant amount of example code from our books into your product's documentation does require permission.
	  
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN.
	  
If you think your use of code examples falls outside fair use or the permission given here, feel free to contact us at <permissions@oreilly.com>.
	  
Please note that the examples are not production code and have not been carefully testing. They are provided "as-is" and come with no warranty of any kind.

ch01/Scribble.java

0 → 100755
+81 −0
Changes for ch01/Scribble.java: 81 added lines, 0 removed lines.
Original line number Diff line number Diff line
// This example is from the book "Java in a Nutshell, Second Edition".
// Written by David Flanagan.  Copyright (c) 1997 O'Reilly & Associates.
// You may distribute this source code for non-commercial purposes only.
// You may study, modify, and use this example for any purpose, as long as
// this notice is retained.  Note that this example is provided "as is",
// WITHOUT WARRANTY of any kind either expressed or implied.

import java.applet.*;
import java.awt.*;

public class Scribble extends Applet {
  private int last_x, last_y;                // Store the last mouse position.
  private Color current_color = Color.black; // Store the current color.
  private Button clear_button;               // The clear button.
  private Choice color_choices;              // The color dropdown list.

  // This method is called to initialize the applet.
  // Applets don't have a main() method.
  public void init() {
    // Set the background color
    this.setBackground(Color.white);

    // Create a button and add it to the applet.  Set the button's colors
    clear_button = new Button("Clear");
    clear_button.setForeground(Color.black);
    clear_button.setBackground(Color.lightGray);
    this.add(clear_button);

    // Create a menu of colors and add it to the applet.
    // Also set the menus's colors and add a label.
    color_choices = new Choice();
    color_choices.addItem("black");
    color_choices.addItem("red");
    color_choices.addItem("yellow");
    color_choices.addItem("green");
    color_choices.setForeground(Color.black);
    color_choices.setBackground(Color.lightGray);
    this.add(new Label("Color: "));
    this.add(color_choices);
  }

  // This method is called when the user clicks the mouse to start a scribble.
  public boolean mouseDown(Event e, int x, int y)
  {
    last_x = x; last_y = y;
    return true;
  }

  // This method is called when the user drags the mouse.
  public boolean mouseDrag(Event e, int x, int y)
  {
    Graphics g = this.getGraphics();
    g.setColor(current_color);
    g.drawLine(last_x, last_y, x, y);
    last_x = x;
    last_y = y;
    return true;
  }

  // This method is called when the user clicks the button or chooses a color
  public boolean action(Event event, Object arg) {
    // If the Clear button was clicked on, handle it.
    if (event.target == clear_button) {
      Graphics g = this.getGraphics();
      Rectangle r = this.bounds();
      g.setColor(this.getBackground());
      g.fillRect(r.x, r.y, r.width, r.height);
      return true;
    }
    // Otherwise if a color was chosen, handle that
    else if (event.target == color_choices) {
      if (arg.equals("black")) current_color = Color.black;
      else if (arg.equals("red")) current_color = Color.red;
      else if (arg.equals("yellow")) current_color = Color.yellow;
      else if (arg.equals("green")) current_color = Color.green;
      return true;
    }
    // Otherwise, let the superclass handle it.
    else return super.action(event, arg);
  }
}

ch02/throwtest.java

0 → 100755
+117 −0
Changes for ch02/throwtest.java: 117 added lines, 0 removed lines.
Original line number Diff line number Diff line
// This example is from the book "Java in a Nutshell, Second Edition".
// Written by David Flanagan.  Copyright (c) 1997 O'Reilly & Associates.
// You may distribute this source code for non-commercial purposes only.
// You may study, modify, and use this example for any purpose, as long as
// this notice is retained.  Note that this example is provided "as is",
// WITHOUT WARRANTY of any kind either expressed or implied.

// Here we define some exception types of our own.
// Exception classes generally have constructors but no data or 
// other methods.  All these do is to call their superclass constructors.
class MyException extends Exception {
    public MyException() { super(); }
    public MyException(String s) { super(s); }
}
class MyOtherException extends Exception {
    public MyOtherException() { super(); }
    public MyOtherException(String s) { super(s); }
}
class MySubException extends MyException {
    public MySubException() { super(); }
    public MySubException(String s) { super(s); }
}

// This class demonstrates defining, throwing and handling exceptions.
// Try invoking it in the following ways and try to understand the 
// output:
//    java throwtest
//    java throwtest one
//    java throwtest 0
//    java throwtest 1
//    java throwtest 99
//    java throwtest 2
//    java throwtest 3
public class throwtest {
    // This is the main() method.  Note that it uses two
    // catch clauses to handle two standard Java exceptions.
    public static void main(String argv[]) {
        int i;

        // First, convert our argument to an integer
        // Make sure we have an argument and that it is convertible.
        try {
            i = Integer.parseInt(argv[0]);
        }
        catch (ArrayIndexOutOfBoundsException e) { // argv is empty
            System.out.println("Must specify an argument");
            return;
        }
        catch (NumberFormatException e) { // argv[0] isn't an integer
            System.out.println("Must specify an integer argument.");
            return;
        }

        // Now, pass that integer to method a().
        a(i);
    }

    // This method invokes b(), which is declared to throw
    // one type of exception.  We handle that one exception.
    public static void a(int i) {
        try {
            b(i);
        }
        catch (MyException e) {                              // Point 1.
            // Here we handle MyException and 
            // its subclass MyOtherException
            if (e instanceof MySubException)
                System.out.print("MySubException: ");
            else
                System.out.print("MyException: ");
            System.out.println(e.getMessage());
            System.out.println("Handled at point 1");
        }
    }

    // This method invokes c(), and handles one of the
    // two exception types that that method can throw.  The other 
    // exception type is not handled, and is propagated up
    // and declared in this method's throws clause.
    // This method also has a finally clause to finish up 
    // the work of its try clause.  Note that the finally clause
    // is executed after a local catch clause, but before a
    // a containing catch clause or one in an invoking procedure.
    public static void b(int i) throws MyException {
        int result;
        try {
            System.out.print("i = " + i);
            result = c(i);
            System.out.print(" c(i) = " + result);
        }
        catch (MyOtherException e) {                          // Point 2
            // Handle MyOtherException exceptions:
            System.out.println("MyOtherException: " + e.getMessage());
            System.out.println("Handled at point 2");
        }
        finally {
            // Terminate the output we printed above with a newline.
            System.out.print("\n");
        }
    }

    // This method computes a value or throws an exception.
    // The throws clause only lists two exceptions, because
    // one of the exceptions thrown is a subclass of another.
    public static int c(int i) throws MyException, MyOtherException {
        switch (i) {
            case 0: // processing resumes at point 1 above
                throw new MyException("input too low");
            case 1: // processing resumes at point 1 above
                throw new MySubException("input still too low");
            case 99:// processing resumes at point 2 above
                throw new MyOtherException("input too high");
            default:
                return i*i;
        }
    }
}
+46 −0
Changes for ch06/ColorScribble.java: 46 added lines, 0 removed lines.
Original line number Diff line number Diff line
// This example is from the book "Java in a Nutshell, Second Edition".
// Written by David Flanagan.  Copyright (c) 1997 O'Reilly & Associates.
// You may distribute this source code for non-commercial purposes only.
// You may study, modify, and use this example for any purpose, as long as
// this notice is retained.  Note that this example is provided "as is",
// WITHOUT WARRANTY of any kind either expressed or implied.

import java.applet.*;
import java.awt.*;

public class ColorScribble extends Scribble {
  // Read in two color parameters and set the colors.
  public void init() {
    super.init();
    Color foreground = getColorParameter("foreground");
    Color background = getColorParameter("background");
    if (foreground != null) this.setForeground(foreground);
    if (background != null) this.setBackground(background);
  }

  // Read the specified parameter.  Interpret it as a hexadecimal
  // number of the form RRGGBB and convert it to a color.
  protected Color getColorParameter(String name) {
    String value = this.getParameter(name);
    try { return new Color(Integer.parseInt(value, 16)); }
    catch (Exception e) { return null; }
  }

  // Return information suitable for display in an About dialog box.
  public String getAppletInfo() {
    return "ColorScribble v. 0.02.  Written by David Flanagan.";
  }

  // Return info about the supported parameters.  Web browsers and applet
  // viewers should display this information, and may also allow users to
  // set the parameter values.
  public String[][] getParameterInfo() { return info; }

  // Here's the information that getParameterInfo() returns.
  // It is an array of arrays of strings describing each parameter.
  // Format: parameter name, parameter type, parameter description
  private String[][] info = {
    {"foreground", "hexadecimal color value", "foreground color"},
    {"background", "hexadecimal color value", "background color"}
  };
}

ch06/FirstApplet.java

0 → 100755
+17 −0
Changes for ch06/FirstApplet.java: 17 added lines, 0 removed lines.
Original line number Diff line number Diff line
// This example is from the book "Java in a Nutshell, Second Edition".
// Written by David Flanagan.  Copyright (c) 1997 O'Reilly & Associates.
// You may distribute this source code for non-commercial purposes only.
// You may study, modify, and use this example for any purpose, as long as
// this notice is retained.  Note that this example is provided "as is",
// WITHOUT WARRANTY of any kind either expressed or implied.

import java.applet.*;  	// Don't forget this import statement!
import java.awt.*;          // Or this one for the graphics!

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);
  }
}
Loading