Java Programming
Week 3

Dr. Ernest J. Friedman-Hill

ejfried@herzberg.ca.sandia.gov

http://herzberg.ca.sandia.gov/JavaCourse

 

What We're Doing Today

Old Homework

 

package ejfried.iset;

 

/**

* An ordered set of unique Integers

* Public interface of this class is that of

* a list; privately, it's the links too!

*/

 

public class IntegerSet

{

private Integer m_data;

private IntegerSet m_next, m_iter;

public IntegerSet() {}

 

////////////////////////////////////////////

// Private "link" constructor

private IntegerSet(Integer i) throws LinkException

{

if (i == null)

throw new LinkException();

m_data = i;

}

 

///////////////////////////////////////////

// Iteration methods

public void reset() { m_iter = this.m_next; }

public boolean hasMoreElements()

{

return (m_iter != null);

}

public int nextElement() throws LinkException

{

if (m_iter == null)

throw new LinkException();

int i = m_iter.m_data.intValue();

m_iter = m_iter.m_next;

return i;

}

 

 

///////////////////////////////////////////

// insert a unique integer into the list, sorted

public boolean insert(Integer i) throws LinkException

{

IntegerSet is = new IntegerSet(i);

if (m_next == null)

{

m_next = is;

return true;

}

else

{

IntegerSet next = m_next, prev = this;

while (next != null &&

i.intValue() > next.m_data.intValue())

{

prev = prev.m_next;

next = next.m_next;

}

 

if (next != null)

{

if (next.m_data.intValue()==i.intValue())

return false;

}

is.m_next = next;

 

prev.m_next = is;

return true;

}

}

 

 

 

/////////////////////////////////////////

// remove an integer from the list

public boolean remove(Integer i) throws LinkException

{

if (m_next == null)

return false;

 

IntegerSet next = m_next, prev = this;

while (next != null &&

i.intValue() > next.m_data.intValue())

{

prev = prev.m_next;

next = next.m_next;

}

if (next != null)

{

if (next.m_data.intValue() == i.intValue())

prev.m_next = next.m_next;

return true;

}

else

return false;

}

}

 

public class LinkException extends Exception {}

 

 

/**

* Trivial Card game

* one of the demo programs for IntegerSet

*/

 

import ejfried.iset.*;

 

public class Cards

{

 

static final int NCARDS = 52, HANDSIZE = 7;

public static void main(String [] argv)

{

try

{

IntegerSet deck = new IntegerSet();

for (int i=0; i<NCARDS; i++)

deck.insert(new Integer(i));

// Display full deck

System.out.print("The deck: ");

for (deck.reset(); deck.hasMoreElements(); )

System.out.print(deck.nextElement() + " ");

System.out.println();

IntegerSet hand = new IntegerSet();

int nDealt = 0;

while (nDealt < HANDSIZE)

{

Integer random =

new Integer((int) (Math.random()*NCARDS));

if (hand.insert(random))

{

deck.remove(random);

++nDealt;

}

}

 

 

 

 

 

// Display hand

System.out.print("The hand: ");

for (hand.reset(); hand.hasMoreElements(); )

System.out.print(hand.nextElement() + " ");

System.out.println();

 

// Display rest of deck

System.out.print("The deck now: ");

for (deck.reset(); deck.hasMoreElements(); )

System.out.print(deck.nextElement() + " ");

System.out.println();

}

catch (LinkException le)

{

System.out.println("Not playing with " +

"a full deck!");

}

}

 

}

 

 

 

 

 

/**

* A trivial demo for IntegerSet

* Sorts and Uniquifies an array of ints.

*/

 

import ejfried.iset.*;

 

public class SortInts

{

final static int data[] = { 35, 3, 4, 23, 23, 1,

6, 8, 29, 4, -3, 14 };

public static void main(String[] argv)

{

try

{

IntegerSet is = new IntegerSet();

for (int i=0; i<data.length; i++)

is.insert(new Integer(data[i]));

// display the numbers

for (is.reset(); is.hasMoreElements();)

System.out.print(is.nextElement() + " ");

System.out.println();

}

catch (LinkException le)

{

System.out.println("Link error!");

}

}

 

}

 

Interfaces in Java

class Picture

{

Circle[] circles;

Square[] squares;

Triangle[] triangles;

...

void draw()

{

for(int i=0; i<circles.length; i++)

circles[i].draw();

for(int i=0; i<squares.length; i++)

squares[i].draw();

...

}

Interfaces in Java

interface Shape { void draw(); }

class Circle implements Shape {

void draw() { ... }

...

class Square implements Shape {

void draw() { ... }

...

class Picture implements Shape

{

Shape[] shapes;

...

void draw()

{

for(int i=0; i<shapes.length; i++)

shapes[i].draw();

Interfaces in Java

interface Shape

{

final int BLACK_AND_WHITE = 1;

final int COLOR = 2;

void draw(int style);

}

Interfaces in Java

void print(Shape s) {

if (s instanceof Circle) {

Circle c = (Circle) s;

... but usually you should avoid this.

Interfaces in Java

if (sh instanceof Circle){

Circle c = (Circle) sh;

c.drawCircle();

} else if (x instanceof Square){

Square s = (Circle) sh;

s.drawSquare();

}

sh.draw();

Interfaces in Java

String poly = "com.polywerk.Rhombus";

Shape shape = (Shape) Class.forName(poly).instanceOf();

shape.draw();

Interfaces in Java

Interfaces in Java

interface Animal

{ void walk(); }

interface Flying

{ void fly(); }

interface FlyingAnimal

extends Flying, Animal {}

Class Inheritance

class Circle implements Shape {

double m_x, m_y, m_r; // radius

void moveTo(double x, double y)

{ m_x = x; m_y = y; }

...

 

class Square implements Shape {

double m_x, m_y, m_s; // side

void moveTo(double x, double y)

{ m_x = x; m_y = y; }

...

 

 

Class Inheritance

abstract class Shape {

double m_x, m_y;

abstract void draw();

void moveTo(double x, double y)

{ m_x = x; m_y = y; }

}

class Circle extends Shape {

double m_r;

void draw() { /* body */ }

double radius() { return m_r; }

}

 

Class Inheritance

Class Inheritance

void doSomething(Shape s) {

// double r = s.radius();

double r = ((Circle) s).radius();

// Circle c = s;

Circle c = (Circle) s;

double r = c.radius();

 

if (s instanceof Circle)

{

double r = ((Circle) s).radius();

...

Class Inheritance

More Keywords

More Keywords

Overriding Details

super.moveTo();

The Abstract Window Toolkit (AWT)

Arranging Components

Arranging Components

1) Create a Container

import java.awt.*;

Frame f = new Frame("Test");

2) Set the Container's LayoutManager

f.setLayout(new FlowLayout());

3) Create Components

Button ok = new Button("OK");

Button cancel = new Button("Cancel");

4) Call add() on the Container

f.add(ok);

f.add(cancel);

5) Show the Container

f.pack();

f.show();

Layout Managers

 

 

 

 

 

Arranging Components
Hierarchical Layouts

Frame f = new Frame("Test");

f.setLayout(new BorderLayout());

// A nested Container

Panel p = new Panel();

p.add(new Button("OK"));

p.add(new Button("Cancel"));

f.add("South", p);

f.add("Center",

new TextArea(20, 40));

f.pack();

f.show();

Adding Behaviors

 

 

 

 

Adding Behaviors

package java.awt;

public class Button {

public void

addActionListener(ActionListener al) {...}

public void

removeActionListener(ActionListener al) {...}

}

package java.awt.event;

public interface EventListener {}

public interface ActionListener extends EventListener {

public void

actionPerformed(ActionEvent ae);

}

 

 

 

Adding Behaviors

class QuitAction

implements ActionListener

{

public void

actionPerformed(ActionEvent ae)

{

System.exit(0);

}

}

Button quit = new Button("Quit");

quit.addActionListener(new QuitAction());

 

Adding Behaviors

Adding Behaviors

Adding Behaviors

windowActivated(WindowEvent)

windowClosed(WindowEvent)

windowClosing(WindowEvent)

windowDeactivated(WindowEvent)

windowDeiconified(WindowEvent)

windowIconified(WindowEvent)

windowOpened(WindowEvent)

 

Adding Behaviors

class Closer extends WindowAdapter

{

public void

windowClosing(WindowEvent we)

{

we.getWindow().dispose();

}

}

...

Frame f;

...

f.addWindowListener(new Closer());

 

Inner Classes

 

public class Cat {

private Foot[] f =

new Foot[4];

public Cat()

{ /* create feet */ }

class Foot {

Foot() { ... }

}

}

Inner Classes

import java.sql.*;

class MyConnection

implements Connection {

class MyStatement

implements Statement {

// … statement methods

//omitted

}

public Statement

createStatement(){

return new MyStatement();

}

// … more Connection methods

}

Anonymous Inner Classes

import java.sql.*;

class MyConnection

implements Connection {

public Statement

createStatement() {

return new Statement() {

// … statement methods

//omitted

}

}

// … more Connection methods

}

Inner Classes

 

import java.sql.*;

class MyConnection

implements Connection

{

Socket s;

MyConnection(String host)

{ s = new Socket(host, 1234); }

public Statement

createStatement()

{

return new Statement() {

ResultSet execute(String sql) {

// Uses MyConnection.s !

OutputStream os =

s.getOutputStream();

...

Inner Classes

 

public class Foo {

int m_x = 1,m_y = 1;

Bar m_b = new Bar(); // Normal new

class Bar {

void zero() {m_x = m_y = 0;}

}

}

 

...

 

Foo f = new Foo();

Foo.Bar b = f.new Bar(); // NOTE!

b.zero(); // f.m_x is now 0;

Inner Classes and Protection

Inner Classes and the AWT

Programming Java Applets

Applet Constructors

The init() Method

The start() Method

The stop() Method

Features of NervousText

 

/* NervousText.java 1.1 97/04/01

* Copyright (c) 1994-1996 Sun Microsystems

* Original by Daniel Wyszynski

*/

 

import java.awt.event.*;

import java.awt.*;

import java.applet.*;

 

public class NervousText extends Applet implements Runnable{

char chars[];

Thread runner = null;

boolean threadSuspended = false;

public void init()

{

addMouseListener(new MouseAdapter() {

public void mousePressed(MouseEvent e) {

if (threadSuspended)

runner.resume();

else

runner.suspend();

threadSuspended = !threadSuspended;

}

});

String s = getParameter("text");

if (s == null)

s = "HotJava";

chars = new char [together.length()];

s.getChars(0,together.length(),chars,0);

setFont(new Font("Serif",Font.BOLD,36));

}

 

public void start() {

if(runner == null) {

runner = new Thread(this);

runner.start();

}

}

public void stop() {

runner = null;

}

public void run() {

while (runner != null) {

try {Thread.sleep(100);}

catch (InterruptedException e){}

repaint();

}

}

public void paint(Graphics g) {

int x_coord, y_coord;

for(int i=0;i<chars.length;i++)

{

x_coord = (int) (Math.random()*10+15*i);

y_coord = (int) (Math.random()*10+36);

g.drawChars(chars,i,1,x_coord,y_coord);

}

}

}

 

/*

Here is the HTML to embedd this in a Web page:

<applet code="NervousText.class"

width=200 height=50>

<param name=text value="Worse than blinking!">

</applet>

*/

More about Applets

More about Applets

More about Applets

More about Applets

Third Homework

Write a simple GUI (as an application, not as an Applet) that collects user input in a series of TextFields and/or Choices and does a computation when a button is pressed. The result should be displayed in a scrolling TextArea. The computation can be anything from providing quantities of ingredients for a recipe given the number of people to be served, to computing the optimum temperature for a ceramic kiln given the size and desired appearance of a piece of artwork. Make sure there's a way to quit!

 

Make sure your GUI responds well to any sequence of inputs. Think about how the user might abuse it! Don't expect the boxes to be filled in from top to bottom; be sure to respond appropriately if boxes are blank.

Third Homework