63
Financial Engineering Project Course

Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

  • View
    229

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

Financial Engineering Project Course

Page 2: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

Week 7

Java GUI programming and Java Threads

GUI example taken from “Computing Concepts with Java 2” byCay Horstmann

Thread examples taken from “The Java Programming Language”By Arnold and Gosling and from Cay Horstmann’s “Core Java 2 Advanced”

Client-server computing with threads

Page 3: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

An example

import javax.swing.*;import java.awt.event.*;

public class InternetFrameExample {

public static void main(String[] args) {

JFrame f = new InternetFrame("Example"); f.setTitle("Internet browser"); f.show(); }}

Page 4: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

class InternetFrame extends JFrame {

public InternetFrame(String s){

setSize(300,300); WindowCloser listener = new WindowCloser(); addWindowListener(listener); }

private class WindowCloser extends WindowAdapter {

public void windowClosing(WindowEvent e) { System.exit(0); } } }

Page 5: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann
Page 6: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

Adding User Interface Components to a Frame

•Do not draw directly on the surface of a frame.•Frames have been designed to arrange user interface components.•User interface components are such things as buttons, menus, scroll bars, and so on.•If you want to draw on a frame, draw on a separate component and then add that component to the frame. The Swing UI toolkit provides the Jpanel class for this purpose.

Page 7: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

Drawing on a JPanel

To draw on a Jpanel you override the paintComponent method.

Make sure that from within your paintComponent method youcall super.paintComponent(…) so that the superclass method paintComponent has a chance to erase the existing contents,redraw the borders and decorations, etc.

Page 8: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

Adding the Panel to the JFrame

• The surface of a Swing frame is covered with four panes.

• Each of these four has a purpose.• We are interested in getting access to the

JFrame’s content pane.• So, call the getContentPane on the JFrame.• This call returns a Container object.• Add your Panel object to the Container.

Page 9: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

Output first! -- user enters number of eggs and we draw them

Page 10: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

Strategy

Think about • What do we want on the screen?• What events should we listen for?• What should we do when those events occur?• What processing will we do when user input arrives?• What object has responsibilities for what activities?

Think about

• The ‘has-a’ relationship,e.g., the Jframe “has-a” Panel and a TextField.• The ‘is-a’ relationship,e.g., The TextFieldListener ‘is-an’ actionListener.

Page 11: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

// Example// Eggs.java

import java.awt.Container;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.awt.geom.Ellipse2D;import java.util.Random;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JTextField;

We need classes fromthe awt, util, and swingpackages.

Page 12: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

public class Eggs{ public static void main(String[] args) { EggFrame frame = new EggFrame(); frame.setTitle("Enter number of eggs"); frame.show(); }}

This thread is doneafter creating a frame andstarting up the frame thread.

A frame now exists and is running.

Page 13: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

The EggFrame Constructor

• Set the size of the frame• Add a listener to listen for the stop event• Create a JPanel object to draw on and a

JTextField object to interact with the user via the keyboard

• Add a listener for the JTextField• Add the Jpanel and the JTextField to the contentPane container.

Page 14: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

class EggFrame extends JFrame{ private JTextField textField; private EggPanel panel;

public EggFrame() { final int DEFAULT_FRAME_WIDTH = 300; final int DEFAULT_FRAME_HEIGHT = 300; setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT);

addWindowListener(new WindowCloser()); panel = new EggPanel(); textField = new JTextField();

textField.addActionListener(new TextFieldListener()); Container contentPane = getContentPane(); contentPane.add(panel, "Center"); contentPane.add(textField, "South"); }

Page 15: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

The constructor will be called from our main thread.

The other thread operates asynchronously.

What do we mean by asynchronous execution?

Who is running the show?

Don’t programs run sequentially?

We have to think differently.

Event driven programming

Page 16: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

The TextField

The TextField object will call us when it detectsan event.

We don’t ‘read the input’. We set up a babysitter torespond.

The TextField object sends us an event object.

Page 17: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

// Use an inner class to listen on the text field

private class TextFieldListener implements ActionListener { public void actionPerformed(ActionEvent event) { String input = textField.getText(); panel.setEggCount(Integer.parseInt(input)); textField.setText(""); } } We do two things when we

have a textfield event.1) Get the data2) Tell the panel the number of eggs to display

Page 18: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

private class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent event) { System.exit(0); } }}

How do we respond when theclose signal is received?

Page 19: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

How about the panel object

What are the panel object’s responsibilities?

get input? _____ repaint itself? _____ keep track of the egg count? _____ hold the data it needs to repaint itself? _____

Do we want our panel to inherit properties and methods from anyexisting classes? _____

Page 20: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

How about the panel object

What are the panel object’s responsibilities?

get input? No, that’s the TextField’s job. repaint itself? Sure, that’s its main job. keep track of the egg count? Yes, better here where it’s needed hold the data it needs to repaint itself? Yes

Do we want our panel to inherit properties from any existing classes? Sure, we want to re-use existing code and there is much to be done.

Page 21: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

How about the panel object

When should the panel object repaint itself?

What will the panel need to repaint itself?

Who actually calls the paintComponent method?

Page 22: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

How about the panel object

When should the panel object repaint itself? When a new input arrives from the user. When the egg count changes. What will the panel need to repaint itself? A graphics object to draw on.

Who actually calls the paintComponent method? While we have to provide a paintComponent method we don’t call it directly. It’s called by the Java run-time environment after we make a call on repaint.

Page 23: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

class EggPanel extends JPanel{

public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; // draw eggCount ellipses with random centers Random generator = new Random(); for (int i = 0; i < eggCount; i++) { double x = getWidth() * generator.nextDouble(); double y = getHeight() * generator.nextDouble(); Ellipse2D.Double egg = new Ellipse2D.Double(x, y, EGG_WIDTH, EGG_HEIGHT); g2.draw(egg); } }

Page 24: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

public void setEggCount(int count) { eggCount = count; repaint(); }

private int eggCount; private static final double EGG_WIDTH = 30; private static final double EGG_HEIGHT = 50;}

Page 25: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

Java Threads

• Four kinds of thread programming

• Applications– A GUI application– A server application

Page 26: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

Four kinds of thread programming

1) Unrelated threads

2) Related but unsynchronized threads

3) Mutually-exclusive threads

4) Communicating mutually-exclusive

threads

We will look at only the first two kinds.

Page 27: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

class Coffee extends Thread {

Coffee(String name) {super(name);

} public void run() {

for(int n = 1; n <= 3; n++) { System.out.println("I like coffee");

yield();System.out.println(this.getName());yield();

} }}

Unrelated threads

Page 28: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

class Tea extends Thread { Tea(String name) {

super(name); } public void run() { for(int n = 1; n <= 3; n++) {

System.out.println("I like tea");yield();System.out.println(this.getName());yield();

} }}

Page 29: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

public class Drinks {

public static void main(String args[]) { System.out.println("I am main");

Coffee t1 = new Coffee("Wawa Coffee");Tea t2 = new Tea(“Sleepy Time Tea");t1.start();t2.start();

System.out.println("Main is done");}

}

Page 30: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

I am mainMain is doneI like coffeeI like teaWawa CoffeeSleepy Time TeaI like coffeeI like teaWawa CoffeeSleepy Time TeaI like coffeeI like teaWawa CoffeeSleepy Time Tea

Output

Main finishes right away

Threads are sharing time

This program has three threads.

Page 31: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

• Using sleep() in unrelated threads

• The call sleep(millis) puts the currently executing thread to sleep for at least the specified number of milliseconds. "At least“ means there is no guarantee the thread will wake up in exactly the specified time. Other thread scheduling can interfere.

Unrelated Threads Part II

Page 32: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

class Coffee extends Thread {Coffee(String name) {

super(name);}public void run() {

for(int n = 1; n <= 3; n++) { System.out.println("I like coffee");

try { sleep(1000); // 1 second }

catch(InterruptedException e) {} System.out.println(this.getName());

}}

}

Page 33: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

class Tea extends Thread { Tea(String name) {

super(name);}

public void run() { for(int n = 1; n <= 5; n++) {

System.out.println("I like tea");System.out.println(getName());

}}

}

Page 34: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

public class Drinks2 { public static void main(String args[]) { System.out.println("I am main"); Coffee t1 = new Coffee("Wawa Coffee"); Tea t2 = new Tea("China Tea"); t1.start(); t2.start(); System.out.println("Main is done"); }}

Page 35: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

I am mainMain is doneI like coffeeI like teaChina TeaI like teaChina TeaI like teaChina TeaI like teaChina TeaI like teaChina TeaWawa CoffeeI like coffeeWawa CoffeeI like coffeeWawa Coffee

1 second pausing after each “I like coffee”

After “I like coffee”, the coffee thread goes to sleep and the tea thread gets to finish and die.

Page 36: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

Yield() and Sleep()

• Yield() may have no effect on some implementations.

• The thread scheduler might make no effort toward fairness.

• The yielding thread may be picked again even though other threads want a turn.

• It is a good idea to call sleep() instead.

Page 37: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

An Example Without Threads

Black ball bounces for awhile and then stops. If you then click start, a new ball bounces for awhile and then stops. Close only works between balls. If the ball is moving and you click close, the close message is queued.

Page 38: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

// From Cay Horstmann Core Java 2 Advancedimport java.awt.*;import java.awt.event.*;import javax.swing.*;

public class Bounce{ public static void main(String[] args) { JFrame frame = new BounceFrame(); frame.show(); }}

Page 39: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

class BounceFrame extends JFrame{ public BounceFrame() { setSize(300, 200); setTitle("Bounce");

addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } );

Page 40: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

Container contentPane = getContentPane(); canvas = new JPanel(); contentPane.add(canvas, "Center"); JPanel p = new JPanel();

addButton(p, "Start", new ActionListener() { public void actionPerformed(ActionEvent evt) { Ball b = new Ball(canvas); b.bounce(); } });

Page 41: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

addButton(p, "Close", new ActionListener() { public void actionPerformed(ActionEvent evt) { System.exit(0); } }); contentPane.add(p, "South"); } public void addButton(Container c, String title, ActionListener a) { JButton b = new JButton(title); c.add(b); b.addActionListener(a); } private JPanel canvas;}

Page 42: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

class Ball{ public Ball(JPanel b) { box = b; }

public void draw() { Graphics g = box.getGraphics(); g.fillOval(x, y, XSIZE, YSIZE); g.dispose(); }

Page 43: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

public void move() { Graphics g = box.getGraphics(); g.setXORMode(box.getBackground()); g.fillOval(x, y, XSIZE, YSIZE); x += dx; y += dy; Dimension d = box.getSize(); if (x < 0) { x = 0; dx = -dx; } if (x + XSIZE >= d.width) { x = d.width - XSIZE; dx = -dx; } if (y < 0) { y = 0; dy = -dy; } if (y + YSIZE >= d.height) { y = d.height - YSIZE; dy = -dy; } g.fillOval(x, y, XSIZE, YSIZE); g.dispose(); }

Page 44: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

public void bounce() { draw(); for (int i = 1; i <= 1000; i++) { move(); try { Thread.sleep(5); } catch(InterruptedException e) {} } } private JPanel box; private static final int XSIZE = 10; private static final int YSIZE = 10; private int x = 0; private int y = 0; private int dx = 2; private int dy = 2;}

Page 45: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

Bouncing With Threads

The close button works in an instant. Each time the start button is clicked a new ball appears. The screen above shows four fast

moving bouncing balls.

Page 46: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

addButton(p, "Start", new ActionListener() { public void actionPerformed(ActionEvent evt) { Ball b = new Ball(canvas); b.start(); } });

We use start() rather than bounce() on the ball object…

Page 47: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

…and have the Ball class extend Thread and implement run() rather than bounce().

class Ball extends Thread:public void run() { try { draw(); for (int i = 1; i <= 1000; i++) { move(); sleep(5); } } catch(InterruptedException e) {} }

Page 48: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

Ping Pong

•Adapted from "The Java Programming Language", Arnold and Gosling•After a thread is created, you can configure it – set its name, its initial priority, and so on.•The start() method spawns a new thread of control based on the data in the thread object and then returns. Now, the •Java virtual machine invokes the new thread's run method, making the thread active.•When a thread's run method returns, the thread has exited.•The thread may be manipulated with a number of methods, including the interrupt() method as shown in this example.

Page 49: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

public class PingPong extends Thread {

private String word;private int delay;

public PingPong(String whatToSay, int delayTime) {word = whatToSay;delay = delayTime;

}

Page 50: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

public void run() { try {

for(;;) { System.out.println(word+" "); sleep(delay);

} } catch (InterruptedException e) { System.out.println("Interrupted!!!!!");

return; }}

Page 51: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

public static void main(String args[]) {

PingPong t1 = new PingPong("\tping",33); t1.start(); PingPong t2 = new PingPong("Pong",100); t2.start(); try { Thread.sleep(5000); } catch(InterruptedException e) {

// will not be printedSystem.out.println("Good morning");

return; }

Page 52: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

Thread myThread = Thread.currentThread(); for (int t = 1 ; t <= 10; t++) System.out.println("In Main..." + myThread.getName()); t1.interrupt(); }}

Page 53: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

C:\McCarthy\threads\PingPong>java PingPong pingPong ping ping pingPong ping ping pingPong ping ping ping : :

Main is asleep.

For 5 secondsping and pongtake turns sleepingand running

Page 54: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

Pong ping ping pingPongIn Main...mainIn Main...mainIn Main...mainIn Main...mainIn Main...mainIn Main...mainIn Main...mainIn Main...mainIn Main...mainIn Main...mainInterrupted!!!!!PongPongPongPongPong:

“Pongs” foreveror until until ctrl-c

Main wakes up

Main interruptsPing and ping dies.

Page 55: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

A Thread Application --A Simple Web Server

• Responds by sending the same file on each hit

• Creates a new thread on each hit

Page 56: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

// A simple web server// Responds with the same file on each hit

import java.net.*;import java.io.*;import java.util.*;

public class OneFile extends Thread {

static String theData = ""; static String contentType; static int contentLength; Socket theConnection;

Page 57: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

// construct each OneFile object with an existing socket public OneFile(Socket s) { theConnection = s; } // run the following code on each object public void run() { try { // get a PrintStream attached to this socket PrintStream os = new PrintStream( theConnection.getOutputStream()); // get a DataInputStream attached to this socket DataInputStream is = new DataInputStream( theConnection.getInputStream()); // read a line from the socket String request = is.readLine();

Page 58: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

// HTTP/1.0 and later send a MIME header if(request.indexOf("HTTP/") != -1) { // we need to read the rest of the MIME header while(true) { String thisLine = is.readLine(); if(thisLine.trim().equals("")) break; }

// respond to the client os.print("HTTP/1.0 200 OK\r\n"); // send the date Date now = new Date(); os.print("Date: " + now + "\r\n"); // send our name os.print("Server: OneFile 1.0\r\n");

Page 59: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

// send the contentLength os.print("Content-length: " + contentLength + "\r\n"); // send the content type os.print("Content-type: " + contentType + "\r\n\r\n"); }

// send the file in the string os.println(theData); theConnection.close(); } catch(IOException e) { } }

Page 60: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

// main loads the file and creates the object on every hit

public static void main(String args[] ) {

int thePort; ServerSocket ss; Socket theConnection; FileInputStream theFile;

// cache the file try { // open file and create a DataInputStream theFile = new FileInputStream(args[0]); DataInputStream dis = new DataInputStream(theFile);

Page 61: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

// determine the content type of this file if(args[0].endsWith(".html") || args[0].endsWith(".htm") ) { contentType = "text/html"; } else { contentType = "text/plain"; } // read the file into the string theData try { String thisLine; while((thisLine = dis.readLine()) != null) { theData += thisLine + "\n"; } } catch(Exception e) { System.err.println("Error " + e); } }

Page 62: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

catch(Exception e) { System.err.println(e); System.err.println("usage: java onefile filename port"); System.exit(1); } // set the port to listen on try { thePort = Integer.parseInt(args[1]); if(thePort < 0 || thePort > 65535) thePort = 80; } catch(Exception e) { thePort = 80; }

Page 63: Financial Engineering Project Course. Week 7 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann

// create a server socket try { ss = new ServerSocket(thePort); System.out.println("Accepting connections on port " + ss.getLocalPort()); System.out.println("Data to be sent:"); System.out.println(theData); while(true) { // stop and wait for a connection Socket socketTemp = ss.accept(); // we have a socket so create a handler OneFile fs = new OneFile(socketTemp); // start the handler running fs.start(); } } catch(IOException e) {System.out.println("Socket error"); } }}