Commit 435ccbcf authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.
Browse files

Initial commit

parents
Loading
Loading
Loading
Loading
+162 KiB

File added.

No diff preview for this file type.

+229 −0
Changes for 1st_edition/examples/AllComponents.java: 229 added lines, 0 removed lines.
Original line number Diff line number Diff line
// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples

import java.awt.*;
import java.awt.event.*;

/** A program that uses all the standard AWT components */
public class AllComponents extends Frame implements ActionListener {
  TextArea textarea;  // Events messages will be displayed here.

  /** Create the whole GUI, and set up event listeners */
  public AllComponents(String title) {
    super(title);  // set frame title.

    // Arrange to detect window close events
    this.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) { System.exit(0); }
    });

    // Set a default font
    this.setFont(new Font("SansSerif", Font.PLAIN, 12));

    // Create the menubar.  Tell the frame about it.
    MenuBar menubar = new MenuBar();
    this.setMenuBar(menubar);

    // Create the file menu.  Add to menubar.
    Menu file = new Menu("File");
    menubar.add(file);

    // Create two items for the file menu, setting their label, shortcut,
    // action command and listener.  Add them to File menu.
    // Note that we use the frame itself as the action listener
    MenuItem open = new MenuItem("Open", new MenuShortcut(KeyEvent.VK_O));
    open.setActionCommand("open");
    open.addActionListener(this);
    file.add(open);
    MenuItem quit = new MenuItem("Quit", new MenuShortcut(KeyEvent.VK_Q));
    quit.setActionCommand("quit");
    quit.addActionListener(this);
    file.add(quit);

    // Create Help menu; add an item; add to menubar
    // Display the help menu in a special reserved place.
    Menu help = new Menu("Help");
    menubar.add(help);
    menubar.setHelpMenu(help);

    // Create and add an item to the Help menu
    MenuItem about = new MenuItem("About", new MenuShortcut(KeyEvent.VK_A));
    about.setActionCommand("about");
    about.addActionListener(this);
    help.add(about);

    // Now that we've done the menu, we can begin work on the contents of
    // the frame.  Assign a BorderLayout manager with margins for this frame.
    this.setLayout(new BorderLayout(10, 10));

    // Create two panels to contain two columns of components.  Use our custom
    // ColumnLayout layout manager for each.  Add them on the west and
    // center of the frame's border layout
    Panel column1 = new Panel();
    column1.setLayout(new ColumnLayout(5, 10, 2, ColumnLayout.LEFT));
    this.add(column1, "West");
    Panel column2 = new Panel();
    column2.setLayout(new ColumnLayout(5, 10, 2, ColumnLayout.LEFT));
    this.add(column2, "Center");

    // Create a panel to contain the buttons at the bottom of the window
    // Give it a FlowLayout layout manager, and add it along the south border
    Panel buttonbox = new Panel();
    buttonbox.setLayout(new FlowLayout(FlowLayout.CENTER, 100, 10));
    this.add(buttonbox, "South");

    // Create pushbuttons and add them to the buttonbox
    Button okay = new Button("Okay");
    Button cancel = new Button("Cancel");
    buttonbox.add(okay);
    buttonbox.add(cancel);

    // Handle events on the buttons
    ActionListener buttonlistener = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        textarea.append("You clicked: " +
                        ((Button)e.getSource()).getLabel() + "\n");
      }
    };
    okay.addActionListener(buttonlistener);
    cancel.addActionListener(buttonlistener);

    // Now start filling the left column.
    // Create a 1-line text field and add to left column, with a label
    TextField textfield = new TextField(15);
    column1.add(new Label("Name:"));
    column1.add(textfield);

    // Handle events on the TextField
    textfield.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        textarea.append("Your name is: " +
                         ((TextField)e.getSource()).getText() + "\n");
      }
    });
    textfield.addTextListener(new TextListener() {
      public void textValueChanged(TextEvent e) {
        textarea.append("You have typed: " +
                         ((TextField)e.getSource()).getText() + "\n");
      }
    });

    // Create a dropdown list or option menu of choices
    Choice choice = new Choice();
    choice.addItem("red");
    choice.addItem("green");
    choice.addItem("blue");
    column1.add(new Label("Favorite color:"));
    column1.add(choice);

    // Handle events on this choice
    choice.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent e) {
        textarea.append("Your favorite color is: " + e.getItem() + "\n");
      }
    });

    // Create checkboxes, and group them in a CheckboxGroup to give them
    // "radio button" behavior.
    CheckboxGroup checkbox_group = new CheckboxGroup();
    Checkbox[] checkboxes = new Checkbox[3];
    checkboxes[0] = new Checkbox("vanilla", checkbox_group, false);
    checkboxes[1] = new Checkbox("chocolate", checkbox_group, true);
    checkboxes[2] = new Checkbox("strawberry", checkbox_group, false);
    column1.add(new Label("Favorite flavor:"));
    for(int i = 0; i < checkboxes.length; i++) column1.add(checkboxes[i]);

    // Handle events on the checkboxes
    ItemListener checkbox_listener = new ItemListener() {
      public void itemStateChanged(ItemEvent e) {
        textarea.append("Your favorite flavor is: " +
                        ((Checkbox)e.getItemSelectable()).getLabel() + "\n");
      }
    };
    for(int i = 0; i < checkboxes.length; i++)
      checkboxes[i].addItemListener(checkbox_listener);

    // Create a list of choices.
    List list = new List(4, true);
    list.addItem("Java"); list.addItem("C"); list.addItem("C++");
    list.addItem("Smalltalk"); list.addItem("Lisp");
    list.addItem("Modula-3"); list.addItem("Forth");
    column1.add(new Label("Favorite languages:"));
    column1.add(list);
    // Handle events on this list
    list.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent e) {
        textarea.append("Your favorite languages are: ");
        String[] languages = ((List)e.getItemSelectable()).getSelectedItems();
        for(int i = 0; i < languages.length; i++) {
          if (i > 0) textarea.append(",");
          textarea.append(languages[i]);
        }
        textarea.append("\n");
      }
    });

    // Create a multi-line text area in column 2
    textarea = new TextArea(6, 40);
    textarea.setEditable(false);
    column2.add(new Label("Messages"));
    column2.add(textarea);

    // Create a scrollpane that displays portions of a larger component
    ScrollPane scrollpane = new ScrollPane();
    scrollpane.setSize(300, 150);
    column2.add(new Label("Scrolling Window"));
    column2.add(scrollpane);

    // Create a custom MultiLineLabel with a really big font and make it
    // a child of the ScrollPane container
    String message =
      "/*************************************************\n" +
      " * AllComponents.java                            *\n" +
      " * Written by David Flanagan                     *\n" +
      " * Copyright (c) 1997 by O'Reilly & Associates   *\n" +
      " *                                               *\n" +
      " *************************************************/\n";
    MultiLineLabel biglabel =  new MultiLineLabel(message);
    biglabel.setFont(new Font("Monospaced", Font.BOLD + Font.ITALIC, 24));
    scrollpane.add(biglabel);
  }

  /** This is the action listener method that the menu items invoke */
  public void actionPerformed(ActionEvent e) {
    String command = e.getActionCommand();
    if (command.equals("quit")) {
      YesNoDialog d = new YesNoDialog(this, "Really Quit?",
                                      "Are you sure you want to quit?",
                                      "Yes", "No", null);
      d.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          if (e.getActionCommand().equals("yes")) System.exit(0);
          else textarea.append("Quit not confirmed\n");
        }
      });
      d.show();
    }
    else if (command.equals("open")) {
      FileDialog d = new FileDialog(this, "Open File", FileDialog.LOAD);
      d.show();  // display the dialog and block until answered
      textarea.append("You selected file: " + d.getFile() + "\n");
      d.dispose();
    }
    else if (command.equals("about")) {
      InfoDialog d = new InfoDialog(this, "About",
                                "This demo was written by David Flanagan\n" +
                                "Copyright (c) 1997 O'Reilly & Associates");
      d.show();
    }
  }

  public static void main(String[] args) {
    Frame f = new AllComponents("AWT Demo");
    f.pack();
    f.show();
  }
}
+59 −0
Changes for 1st_edition/examples/Averager.java: 59 added lines, 0 removed lines.
Original line number Diff line number Diff line
// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples

/**
 * A class to compute the running average of numbers passed to it
 **/
public class Averager {
  // Private fields to hold the current state.
  private int n = 0;
  private double sum = 0.0, sumOfSquares = 0.0;

  /** 
   * This method adds a new datum into the average.
   **/
  public void addDatum(double x) {
    n++;
    sum += x;
    sumOfSquares += x * x;
  }

  /** This method returns the average of all numbers passed to addDatum() */
  public double getAverage() { return sum / n; }

  /** This method returns the standard deviation of the data */
  public double getStandardDeviation() {
     return Math.sqrt(((sumOfSquares - sum*sum/n)/n));
  }

  /** This method returns the number of numbers passed to addDatum() */
  public double getNum() { return n; }

  /** This method returns the sum of all numbers passed to addDatum() */
  public double getSum() { return sum; }

  /** This method returns the sum of the squares of all numbers. */
  public double getSumOfSquares() { return sumOfSquares; }

  /** This method resets the Averager object to begin from scratch */
  public void reset() { n = 0; sum = 0.0; sumOfSquares = 0.0; }

  /** 
   * This nested class is a simple test program we can use to check that 
   * our code works okay.
   **/
  public static class Test {
    public static void main(String args[]) {
      Averager a = new Averager();
      for(int i = 1; i <= 100; i++) a.addDatum(i);
      System.out.println("Average: " + a.getAverage());
      System.out.println("Standard Deviation: " + a.getStandardDeviation());
      System.out.println("N: " + a.getNum());
      System.out.println("Sum: " + a.getSum());
      System.out.println("Sum of squares: " + a.getSumOfSquares());
    }
  }
}
+143 −0
Changes for 1st_edition/examples/Bank.java: 143 added lines, 0 removed lines.
Original line number Diff line number Diff line
// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples

import java.rmi.*;
import java.util.Vector;

/**
 * This class is a placeholder that simply contains other classes and 
 * for interfaces remote banking.
 **/
public class Bank {
  /**
   * This is the interface that defines the exported methods of the 
   * bank server.
   **/
  public interface RemoteBank extends Remote {
    /** Open a new account, with the specified name and password */
    public void openAccount(String name, String password) 
         throws RemoteException, BankingException;

    /** Close the named account */
    public FunnyMoney closeAccount(String name, String password) 
         throws RemoteException, BankingException;

    /** Deposit money into the named account */
    public void deposit(String name, String password, FunnyMoney money)
         throws RemoteException, BankingException;

    /** Withdraw the specified amount of money from the named account */
    public FunnyMoney withdraw(String name, String password, int amount) 
         throws RemoteException, BankingException;

    /** Return the amount of money in the named account */
    public int getBalance(String name, String password) 
         throws RemoteException, BankingException;

    /** 
     * Return a Vector of Strings that list the transaction history 
     * of the named account 
     **/
    public Vector getTransactionHistory(String name, String password) 
         throws RemoteException, BankingException;
  }

  /**
   * This simple class represents a monetary amount.  This implementation
   * is really nothing more than a wrapper around an integer.  It is a useful
   * to demonstrate that RMI can accept arbitrary non-String objects as
   * arguments and return them as values, as long as they are Serializable.
   * A more complete implementation of this FunnyMoney class might bear
   * a serial number, a digital signature, and other security features to 
   * ensure that it is unique and non-forgable.
   **/
  public static class FunnyMoney implements java.io.Serializable {
    public int amount;
    public FunnyMoney(int amount) { this.amount = amount; }
  }

  /**
   * This is a type of exception used to represent exceptional conditions
   * related to banking, such as "Insufficient Funds" and  "Invalid Password"
   **/
  public static class BankingException extends Exception {
    public BankingException(String msg) { super(msg); }
  }

  /**
   * This class is a simple stand-alone client program that interacts
   * with a RemoteBank server.  It invokes different RemoteBank methods
   * depending on its command-line arguments, and demonstrates just how
   * simple it is to interact with a server using RMI.
   **/
  public static class Client {
    public static void main(String[] args) {
      try {
        // Set the standard RMI security manager so that we can safely load
        // untrusted RemoteBank stub code over the network.
        System.setSecurityManager(new RMISecurityManager());

        // Figure out what RemoteBank to connect to by reading a system
        // property (specified on the command line with a -D option to java)
        // or, if it is not defined, use a default URL.  Note that by default
        // this client tries to connect to a server on the local machine
        String url = System.getProperty("bank", "rmi:///FirstRemote");

        // Now look up that RemoteBank server using the Naming object, which
        // contacts the rmiregistry server.  Given the url, this call returns
        // a RemoteBank object whose methods may be invoked remotely
        RemoteBank bank = (RemoteBank) Naming.lookup(url);
        
        // Convert the user's command to lower case
        String cmd = args[0].toLowerCase();

        // Now, go test the command against a bunch of possible options
        if (cmd.equals("open")) {           // Open an account
          bank.openAccount(args[1], args[2]);
          System.out.println("Account opened.");
        }
        else if (cmd.equals("close")) {     // Close an account
          FunnyMoney money = bank.closeAccount(args[1], args[2]);
          // Note that FunnyMoney currency is denominated in wooden nickels
          System.out.println(money.amount+" wooden nickels returned to you.");
          System.out.println("Thanks for banking with us.");
        }
        else if (cmd.equals("deposit")) {   // Deposit money
          FunnyMoney money = new FunnyMoney(Integer.parseInt(args[3]));
          bank.deposit(args[1], args[2], money);
          System.out.println("Deposited " + money.amount + " wooden nickels.");
        }
        else if (cmd.equals("withdraw")) {  // Withdraw money
          FunnyMoney money = bank.withdraw(args[1], args[2], 
                                           Integer.parseInt(args[3]));
          System.out.println("Withdrew " + money.amount + " wooden nickels.");
        }
        else if (cmd.equals("balance")) {   // Check account balance
          int amt = bank.getBalance(args[1], args[2]);
          System.out.println("You have "+amt+" wooden nickels in the bank.");
        }
        else if (cmd.equals("history")) {   // Get transaction history
          Vector transactions = bank.getTransactionHistory(args[1], args[2]);
          for(int i = 0; i < transactions.size(); i++)
            System.out.println(transactions.elementAt(i));
        }
        else System.out.println("Unknown command");
      }
      // Catch and display RMI exceptions
      catch (RemoteException e) { System.err.println(e); }
      // Catch and display Banking related exceptions
      catch (BankingException e) { System.err.println(e.getMessage()); }
      // Other exceptions are probably user syntax errors, so show usage.
      catch (Exception e) { 
        System.err.println(e);
        System.err.println("Usage: java [-Dbank=<url>] Bank$Client " + 
                           "<cmd> <name> <password> [<amount>]");
        System.err.println("where cmd is: open, close, deposit, " + 
                           "withdraw, balance, history");
      }
    }
  }
}
+1 −0
Changes for 1st_edition/examples/BorderLayoutExample.html: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
<APPLET CODE="BorderLayoutExample.class" WIDTH=350 HEIGHT=200></APPLET>
Loading