/** Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ // Further simplified getURL method. public URL getURL() { if (url != null) { return(url); } System.out.print("Enter URL: "); System.out.flush(); BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); String urlString = null; try { urlString = in.readLine(); url = new URL(urlString); } catch(MalformedURLException mue) { System.out.println(urlString + " is not valid.\n" + "Try again."); getURL(); } catch(IOException ioe) { System.out.println("IOError when reading input: " + ioe); ioe.printStackTrace(); // Can skip return(null) now } finally { return(url); } } import java.net.*; // For URL, MalformedURLException import java.io.*; // For BufferedReader /** A small class to demonstrate try/catch blocks. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class URLTest { public static void main(String[] args) { URLTest test = new URLTest(); test.getURL(); test.printURL(); } private URL url = null; /** Read a string from user and create a URL from it. If * reading fails, give up and report error. If reading * succeeds but URL is illegal, try again. */ public URL getURL() { if (url != null) { return(url); } System.out.print("Enter URL: "); System.out.flush(); BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); String urlString; try { urlString = in.readLine(); } catch(IOException ioe) { System.out.println("IOError when reading input: " + ioe); ioe.printStackTrace(); // Show stack dump. return(null); } try { url = new URL(urlString); } catch(MalformedURLException mue) { System.out.println(urlString + " is not valid.\n" + "Try again."); getURL(); } return(url); } /** Print info on URL. */ public void printURL() { if (url == null) { System.out.println("No URL."); } else { String protocol = url.getProtocol(); String host = url.getHost(); int port = url.getPort(); if (protocol.equals("http") && (port == -1)) { port = 80; } String file = url.getFile(); System.out.println("Protocol: " + protocol + "\nHost: " + host + "\nPort: " + port + "\nFile: " + file); } } } /** Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ // Simplified getURL method. public URL getURL() { if (url != null) { return(url); } System.out.print("Enter URL: "); System.out.flush(); BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); String urlString = null; try { urlString = in.readLine(); url = new URL(urlString); } catch(MalformedURLException mue) { System.out.println(urlString + " is not valid.\n" + "Try again."); getURL(); } catch(IOException ioe) { System.out.println("IOError when reading input: " + ioe); ioe.printStackTrace(); // Show stack dump return(null); } return(url); }
Aug 29
URLTest.java Demonstrates try/catch blocks.
Aug 29
ExecTest.java illustrates use of the Exec class.
/** A test of the Exec class. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class ExecTest { public static void main(String[] args) { // Note: no trailing "&" -- special shell chars not // understood, since no shell started. Besides, exec // doesn?t wait, so the program continues along even // before Netscape pops up. Exec.exec("/usr/local/bin/netscape"); // Run commands, printing results. Exec.execPrint("/usr/bin/ls"); Exec.execPrint("/usr/bin/cat Test.java"); // Don?t print results, but wait until this finishes. Exec.execWait("/usr/java1.3/bin/javac Test.java"); // Now Test.class should exist. Exec.execPrint("/usr/bin/ls"); } }
Aug 29
DropBall.java Uses a while loop to determine how long it takes a ball to fall from the top of the Washington Monument to the ground.
/** Simulating dropping a ball from the top of the Washington * Monument. The program outputs the height of the ball each * second until the ball hits the ground. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * . * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class DropBall { public static void main(String[] args) { int time = 0; double start = 550.0, drop = 0.0; double height = start; while (height > 0) { System.out.println("After " + time + (time==1 ? " second, " : " seconds,") + "the ball is at " + height + " feet."); time++; drop = freeFall(time); height = start - drop; } System.out.println("Before " + time + " seconds could " + "expire, the ball hit the ground!"); } /** Calculate the distance in feet for an object in * free fall. */ public static double freeFall (float time) { // Gravitational constant is 32 feet per second squared return(16.0 * time * time); // 1/2 gt^2 } }
Aug 29
Loading Images
JavaMan1.java Applet that loads an image from a relative URL. ************************************************************* import java.applet.Applet; import java.awt.*; /** An applet that loads an image from a relative URL. * >>>>>>>>>>>>>>>>>>> public class JavaMan1 extends Applet { private Image javaMan; public void init() { javaMan = getImage(getCodeBase(),"images/Java-Man.gif"); } public void paint(Graphics g) { g.drawImage(javaMan, 0, 0, this); } } >>>>>>>>>>>>>>>>>>>> JavaMan2.java Illustrates loading an image from an absolute URL. ******************** import java.applet.Applet; import java.awt.*; import java.net.*; /** An applet that loads an image from an absolute * URL on the same machine that the applet came from. * *********************** public class JavaMan2 extends Applet { private Image javaMan; public void init() { try { URL imageFile = new URL("http://www.corewebprogramming.com" + "/images/Java-Man.gif"); javaMan = getImage(imageFile); } catch(MalformedURLException mue) { showStatus("Bogus image URL."); System.out.println("Bogus URL"); } } public void paint(Graphics g) { g.drawImage(javaMan, 0, 0, this); } } >>>>>>>>>>>>>>>>>>>>> # JavaMan3.java An application that loads an image from a local file. Uses the following image and two files: * Java-Man.gif which should be placed in images subdirectory. * WindowUtilities.java Simplifies the setting of native look and feel. * ExitListener.java WindowListener to support terminating the application. ******************* JavaMan3.java ******************* import java.awt.*; import javax.swing.*; /** An application that loads an image from a local file. * Applets are not permitted to do this. * ********************** class JavaMan3 extends JPanel { private Image javaMan; public JavaMan3() { String imageFile = System.getProperty("user.dir") + "/images/Java-Man.gif"; javaMan = getToolkit().getImage(imageFile); setBackground(Color.white); } public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(javaMan, 0, 0, this); } public static void main(String[] args) { JPanel panel = new JavaMan3(); WindowUtilities.setNativeLookAndFeel(); WindowUtilities.openInJFrame(panel, 380, 390); } } >>>>>>>>>>>>>>>>>> Preload.java An application that demonstrates the effect of preloading an image before drawing. Specify -preload as a command-line argument to preload the image. In this case, the prepareImage method is called to immediately start a thread to load the image. Thus, the image is ready to display when the user later selects the Display Image button. >>>>>>>>>>>>>>>>>>> import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.net.*; /** A class that compares the time to draw an image preloaded * (getImage, prepareImage, and drawImage) vs. regularly * (getImage and drawImage). * * The answer you get the regular way is dependent on the * network speed and the size of the image, but if you assume * you load the applet "long" (compared to the time the image * loading requires) before pressing the button, the drawing * time in the preloaded version depends only on the speed of * the local machine. * ********************** public class Preload extends JPanel implements ActionListener { private JTextField timeField; private long start = 0; private boolean draw = false; private JButton button; private Image plate; public Preload(String imageFile, boolean preload) { setLayout(new BorderLayout()); button = new JButton("Display Image"); button.setFont(new Font("SansSerif", Font.BOLD, 24)); button.addActionListener(this); JPanel buttonPanel = new JPanel(); buttonPanel.add(button); timeField = new JTextField(25); timeField.setEditable(false); timeField.setFont(new Font("SansSerif", Font.BOLD, 24)); buttonPanel.add(timeField); add(buttonPanel, BorderLayout.SOUTH); registerImage(imageFile, preload); } /** No need to check which object caused this, * since the button is the only possibility. */ public void actionPerformed(ActionEvent event) { draw = true; start = System.currentTimeMillis(); repaint(); } // Do getImage, optionally starting the loading. private void registerImage(String imageFile, boolean preload) { try { plate = getToolkit().getImage(new URL(imageFile)); if (preload) { prepareImage(plate, this); } } catch(MalformedURLException mue) { System.out.println("Bad URL: " + mue); } } /** If button has been clicked, draw image and * show elapsed time. Otherwise, do nothing. */ public void paintComponent(Graphics g) { super.paintComponent(g); if (draw) { g.drawImage(plate, 0, 0, this); showTime(); } } // Show elapsed time in textfield. private void showTime() { timeField.setText("Elapsed Time: " + elapsedTime() + " seconds."); } // Time in seconds since button was clicked. private double elapsedTime() { double delta = (double)(System.currentTimeMillis() - start); return(delta/1000.0); } public static void main(String[] args) { JPanel preload; if (args.length == 0) { System.out.println("Must provide URL"); System.exit(0); } if (args.length == 2 && args[1].equals("-preload")) { preload = new Preload(args[0], true); } else { preload = new Preload(args[0], false); } WindowUtilities.setNativeLookAndFeel(); WindowUtilities.openInJFrame(preload, 1000, 750); } } <<<<<<<<<<<<<<<<<<
Aug 29
Basic template for a Java applet
AppletTemplate.java >>>>>>>>>>>>>>>>>>>> import java.applet.Applet; import java.awt.*; ******************** public class AppletTemplate extends Applet { // Variable declarations. public void init() { // Variable initializations, image loading, etc. } public void paint(Graphics g) { // Drawing operations. } } >>>>>>>>>>>>>>>>>>>>>
Aug 29
ForwardSnippet.java Partial servlet illustrating how to use a RequestDispatcher to forward requests
ForwardSnippet.java Partial servlet illustrating how to use a RequestDispatcher to forward requests public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String operation = request.getParameter("operation"); if (operation == null) { operation = "unknown"; } if (operation.equals("operation1")) { gotoPage("/operations/presentation1.jsp", request, response); } else if (operation.equals("operation2")) { gotoPage("/operations/presentation2.jsp", request, response); } else { gotoPage("/operations/unknownRequestHandler.jsp", request, response); } } private void gotoPage(String address, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(address); dispatcher.forward(request, response); }
Aug 29
Example illustrating inheritance and abstract classes
*********************************** # Example illustrating inheritance and abstract classes. * Shape.java The parent class (abstract) for all closed, open, curved, and straight-edged shapes. * Curve.java An (abstract) curved Shape (open or closed). * StraightEdgedShape.java A Shape with straight edges (open or closed). * Measurable.java Interface defining classes with measurable areas. * Circle.java A circle that extends Shape and implements Measurable. * MeasureUtil.java Operates on Measurable instances. * Polygon.java A closed Shape with straight edges; extends StraightEdgedShape and implements Measurable. * Rectangle.java A rectangle that satisfies the Measurable interface; extends Polygon. * MeasureTest.java Driver for example. ************************************** ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Shape.java ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** The parent class for all closed, open, curved, and * straight-edged shapes. * ############################ public abstract class Shape { protected int x, y; public int getX() { return(x); } public void setX(int x) { this.x = x; } public int getY() { return(y); } public void setY(int y) { this.y = y; } } ############################# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Curve.java An (abstract) curved Shape (open or closed) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** A curved shape (open or closed). Subclasses will include * arcs and circles. * *********************** public abstract class Curve extends Shape {} ############################## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ StraightEdgedShape.java A Shape with straight edges (open or closed). ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** A Shape with straight edges (open or closed). Subclasses * will include Line, LineSegment, LinkedLineSegments, * and Polygon. * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public abstract class StraightEdgedShape extends Shape {} ################################ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Measurable.java Interface defining classes with measurable areas ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** Used in classes with measurable areas. * ************** public interface Measurable { double getArea(); } ################################# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Circle.java A circle that extends Shape and implements Measurable. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** A circle. Since you can calculate the area of * circles, class implements the Measurable interface. * *********************************** public class Circle extends Curve implements Measurable { private double radius; public Circle(int x, int y, double radius) { setX(x); setY(y); setRadius(radius); } public double getRadius() { return(radius); } public void setRadius(double radius) { this.radius = radius; } /** Required for Measurable interface. */ public double getArea() { return(Math.PI * radius * radius); } } ############################ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MeasureUtil.java Operates on Measurable instances ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** Some operations on Measurable instances. * ************************ public class MeasureUtil { public static double maxArea(Measurable m1, Measurable m2) { return(Math.max(m1.getArea(), m2.getArea())); } public static double totalArea(Measurable[] mArray) { double total = 0; for(int i=0; i ~~~~~~~~~~~~~~~~~~~~~~
Aug 29
Speedboat.java Illustrates inheritance from Ship class
***************************** Speedboat.java Illustrates inheritance from Ship class. See SpeedboatTest.java for a test. ***************************** /** A fast Ship. Red and going 20 knots by default. * *********************** public class Speedboat extends Ship { private String color = "red"; /** Builds a red Speedboat going N at 20 knots. */ public Speedboat(String name) { super(name); setSpeed(20); } /** Builds a speedboat with specified parameters. */ public Speedboat(double x, double y, double speed, double direction, String name, String color) { super(x, y, speed, direction, name); setColor(color); } /** Report location. Override version from Ship. */ public void printLocation() { System.out.print(getColor().toUpperCase() + " "); super.printLocation(); } /** Gets the Speedboat's color. */ public String getColor() { return(color); } /** Sets the Speedboat's color. */ public void setColor(String colorName) { color = colorName; } } ********************** SpeedboatTest.java ********************** /** Try a couple of Speedboats and a regular Ship. * ***************************** public class SpeedboatTest { public static void main(String[] args) { Speedboat s1 = new Speedboat("Speedboat1"); Speedboat s2 = new Speedboat(0.0, 0.0, 2.0, 135.0, "Speedboat2", "blue"); Ship s3 = new Ship(0.0, 0.0, 2.0, 135.0, "Ship1"); s1.move(); s2.move(); s3.move(); s1.printLocation(); s2.printLocation(); s3.printLocation(); } } *****************************
Aug 29
Demonstrates overloading methods in class Ship4
********************* class Ship4 { public double x=0.0, y=0.0, speed=1.0, direction=0.0; public String name; // This constructor takes the parameters explicitly. public Ship4(double x, double y, double speed, double direction, String name) { this.x = x; this.y = y; this.speed = speed; this.direction = direction; this.name = name; } // This constructor requires a name but lets you accept // the default values for x, y, speed, and direction. public Ship4(String name) { this.name = name; } private double degreesToRadians(double degrees) { return(degrees * Math.PI / 180.0); } // Move one step. public void move() { move(1); } // Move N steps. public void move(int steps) { double angle = degreesToRadians(direction); x = x + (double)steps * speed * Math.cos(angle); y = y + (double)steps * speed * Math.sin(angle); } public void printLocation() { System.out.println(name + " is at (" + x + "," + y + ")."); } } public class Test4 { public static void main(String[] args) { Ship4 s1 = new Ship4("Ship1"); Ship4 s2 = new Ship4(0.0, 0.0, 2.0, 135.0, "Ship2"); s1.move(); s2.move(3); s1.printLocation(); s2.printLocation(); } } ************************
Aug 29
HelloWWW.java Basic Hello World (Wide Web) Applet
********************* import java.applet.Applet; import java.awt.*; ********************* public class HelloWWW extends Applet { private int fontSize = 40; public void init() { setBackground(Color.black); setForeground(Color.white); setFont(new Font("SansSerif", Font.BOLD, fontSize)); } public void paint(Graphics g) { g.drawString("Hello, World Wide Web.", 5, fontSize+5); } } <<<<<<<<<<<<<<<<<<<<<