Wednesday, February 28, 2007

Lecture 19

JButton myButton = new JButton("x");
myListener m = new myListener;
myButton.addActionListener(m);
-------------------------------
/* can be replaced with
below */
-------------------------------
myButton.addActionListener(new myListener());


public myJFrame()
{
super("title of Window");
.
.
.
JButton myButton = new JButton("title of button");
myButton.addActionListener( new myListener());
}

What happens when you have multiple buttons?

  • Bad way
    • define different listener classes for each button
    • register the appropriate class to the appropriate button
  • Good way
    • examine e
      • object of type ActionEvent
      • ActionEvent has a method returning the label of the button pressed

public String getActionCommand()
/* Andrew drew a picture of two buttons labeled different things then pointed out that when you click the button "one" e.getActionCommand returns "One"*/

  • These implement the interface LayoutManager
    • BorderLayout
    • FlowLayout
    • GridLayout

  • A window (JFrame) is a container
    • allowed to contain objects and have layouts
  • a window can be divided into regions using LayoutManager
    • each region can be made into a container by declaring it a JPanel
  • a panel is a Container

  1. Declare a LayoutManager
    1. setLayout(new BorderLayout());
  2. Add a apanel to as many regions as you want
    1. JPanel myPanel = new JPanel();
    2. add(MyPanel, BorderLayout, North);
  3. Declare a layout to the panel
    1. myPanel.SetLayout(new.FlowLayout());

Monday, February 26, 2007

Lecture 18

  1. Create the component

  2. Create a listener

  3. Create an instance of the listener

  4. Add (“register”) the listener to the component

  5. Add the component to the JFrame



  • You can skip steps 2 – 4 if your program doesn’t require an action



  • How does this work?

    • Create a visual interface

    • A JFrame

    • A button

  • Then implement a listener

    • this is the code which you wish to perform once the button Is pressed

  • register the listener to the button

    • when the button is pressed

    • Java calls ActionPerformed

      • You do not call ActionPerformed

      • ActionPerformed is an automation in Java

  • Registration tells Java to call it when the button is pressed

    • And then reads the listener



Labels

  • can add a line of text using JLabel component

    1. create a component

    2. JLabel MyLabel = new JLabel(“My Label”);

    3. Skip

    4. Skip

    5. Skip

    6. Add the component to the JFrame

      • MyWindow.add(MyLabel);



Layouts

  • We require a way to arrange multiple objects within a window

  • Java technique which accomplishes that is the layout

    • BorderLayout

    • GridLayout

      • FlowLayout

  • JFrame contains a method setLayout()

  • MyWindow.setLayout(Layout l);

  • Executing this sets the layout of the window to the layout object l.

  • Andrew is not sure that setLayout take a Layout as its param, he will find out for next class

BorderLayout

  • When Adding a component also specify a region in which It goes

    • MyWindow.add(MyButton, BorderLayout.North/East/South/West/Center)



GridLayout

GridLayout GL;

GL = new GridLayout (2, 3)

//2 = rows, 3 = columns

MyWindows.setLayout(GL);

JLabel Label 1 = new JLabel (“1”)

MyWindow.add (Label 1);



Flow Layout

flowLayout FL;

FL = newFlowLayout ();

MyWindow.setLayout (FL);

// add components

Good JFrame Practice

  • Up to now, everything has been done in main

  • This is bad practice because the window is an object

  • It should be treated as such

  • We are creating a modification of JFrame

  • Use inheritance


Friday, February 23, 2007

Lecture 17

  • JFrame is the class that handles windows in Java
    • import 'javax.Swing.JFrame;
    • creating a window is equivalent to creating an object of type JFrame
    • JFrame has an extensive public interface

public void setSize(int width, int height)
public void setTitle(String title)
public JFrame(String title)
public void setVisible(boolean v)
public void add(Component x)

  • notice that the program didn't end when the window closes by default
  • default window close behaviour is to hide the window (but not exit the program)
  • we have to handle the event where the user clicks close

public void setDefaultCloseOperation(int x)
  • we can use
JFrame.EXIT_ON_CLOSE
JFrame.HIDE_ON_CLOSE
JFrame.DO_NOTHING_ON_CLOSE

  • These are given integer values (in order) 3,0,1
    • do not use these values as Java might change those numbers in an update


Action Listeners and Action Events

  • each component must register the listener that handles its events
  • Java interface ActionListener
    • event type is a class called ActionEvent
      • a listener you define must implement the interface ActionListener
public void actionPerform(ActionEvent e)
{

}

  1. Create the component
    1. JButton myButton = new JButton(" ");
  2. Write a listener class
    1. public void myListener implements ActionListener
      {
      public void actionPerformed(ActionEvent c)
      {
      }
      }
  3. Create an instance of the listener
    1. MyListener m = new myListener();
  4. register the listener with the component
    1. myButton.addActionListener(m)
  5. add the component to the JFrame
    1. myWindow.add(MyButton);

Wednesday, February 21, 2007

Finished Test 2 Impressions

Just wrote the test yesterday...
  • had to make an
    • abstract class
    • a child extended class from that class
    • an array which takes in args parameters and inputs them into the class
  • i found it to be somewhat simple
    • but the time we had i didn't feel was enough
    • and Andrew's API was quite unfinished
      • and seemed to have a typo in a method description in his API
    • being given a test that had to support an unfinished API
      • and had to start from scratch
    • was VERY difficult for me to get done
  • still felt the test was fair, for what it tested
  • but my advice to those who haven't written it
    • practice your speed
    • be sure of your coding practice

later
Jake

Lecture 16

  • polymorphism is a very powerful tool because many related classes can be handled the same way and through the same public interface.
  • java figures out which overridden method is the public interface to use

Student
  • Undergrad
  • Graduate
  • all 'students' have a routine for calculating letter grades

public string getLetterGrade()

public void printTranscript(Student s)
{
System.out.println(s.getLetterGrade());
}

  • u - undergraduate
  • g - graduate student
  • q - special student
    • these are all classes which have getLetterGrade overrides
      • print transcript(u)
      • print transcript(g)
      • print transcript(q)
Polymorphism and Arrays

  • consider an array of students
    • conglomeration of undergraduate students, graduate students and others.
  • how do we create the array?
Arrays vs. non-arrays
Student[] s; Student S;
s = new Student[5]; S= new Student(); // not legal


Graphical User Interfaces (GUI)

  • so for our programs we have started on the first line, gone through every line in sequence, and terminated at the end
  • windows does not work that way
  • the programmer doesn't determine the order of events
  • the program 'listens' for user-generated events and passes them to the event handler
  • A GUI program consists largely of event handlers that respond to events
  • you would almost never call event handler methods instead java calls them when the even happens

Monday, February 19, 2007

Lab Test 2 Impressions

Here you can post how you felt the test went, give pointers to those who haven't taken it and so on.

Lecture 15

Things to know for the next Lab:

Inheritance, Arrays, Interface

Things to know for the Midterm:


everything we have covered until this class (Feb 19 2007) is fair game for the midterm
this is unofficially true but the only thing Andrew has told pertaining to Test Content.


Aggregation
  • keeps a reference to an external object
  • external object outlives the aggregate
Composition
  • keeps a copy of object it contains
  • contained object lives and dies with the composition
Polymorphism and Arrays

public class Parent{}

public class Child extends Parent{}

Parent P;
Child c;
c = new Child();
p = c;

  • this is legal
  • P is a reference to C
  • P is of type parent
  • P is a reference to C and is treated like an object of type Parent
  • remember
    • C inherits all of P's methods
    • C can use anything inherited from P
      • public methods ...etc
  • but when p=c
    • p can only access inherited methods from C
      • in other words only methods which exist in both classes can be used in p
  • suppose C has an overridden method
public class Parent
{
public void myMethod()
{
System.out.println("parent");
}
}
public class Child extends Parent()
{
public void myMethod()
{
System.out.println("child");
}
}
-------------------------------------------------

Child c;
Parent p;
c = new Child();
p = c
c.myMethod(); /* prints "child" */
p.myMethod(); /* prints "child" */
  • p.myMethod prints "child"
    • this is because java remembers that P started out as C which is type child
      • this is called "Late Binding"
Summary

Child c;
Parent p;
c = new Child();
c.myMethod(); /* prints "child" because of overriding*/
p = c;
p.myMethod(); /* prints "child" because of polymorphism / late binding*/
p = new Parent();
p.myMethod(); /* prints "parent" because it is not an object reference anymore*/

Wednesday, February 14, 2007

More On Arrays

Review of Arrays

  • Declaring
    • double[] testmark;
  • Assign Space
    • testMark = new double[5]
  • Use Elements in Array
    • testMark[3] = 720;
  • an array is a table of values stored in memory
  • the array name (testMark) is a reference to the array, just like object references
  • to refer the ith member of the array
    • testMark[i]
  • Very Important
    • array indices start at zero, not one.
  • use testMark.length
    • length is the keyword to get the length of the array
  • arrays are objects
    • they should be treated as such
  • because we can change the elements of an array and because arrays are objects we have to treat them as mutable objects
    • deep copy, defensive copy
  • look again at testMark

double[]copyMarks; // create a copy of testMarks
copyMarks = testmarks //BAD!!!
  • both references (copyMarks and testMarks) point to the same thing
  • remember this also happens with object references
  • how do we create a copy of an array?
    1. allocate new space
    2. individually copy elements

testMark = new double[5]
int i;
for (i=0, i < testMark.length, i++)
{
copyMark[i] = testMark[i];
}
  • Summary
    • Arrays are mutable objects which means Defensive copying
    • copy on object containing an array
      • deep copy
    • so i do deep copy test mark
    • testMark == copyMark
      • this is not the same reference
    • unfortunately equals() does not exist for arrays
    • there exist java utilities for array equals
      • java.util.arrays
        • equals
        • fill
        • sort

Lecture 14

Midterm Feb 25 2007


Command Line Arguments

public static void main (String[]args)
{
}


  • argument passed to main is an ARRAY of STRINGS
  • args is an array of Strings consisting of arguments typed on the command line when Java was executed
console - java -cp . ArgsTest one two three
  • that is 3 arguments
    • one
    • two
    • three
      • NOTE: args are seperated by empty spaces, NOT COMMAS, i tested this code myself after class
  • how many parameters?
    • args.length
  • this is useful for automation and for quick input to a program
  • can you pass array objects to a method as a parameter?
    • yes
public void method (double[]myArray)
{}
  • can you return an array?
    • yes
public double[] method()
{
}
  • remember to defensively copy

Aggregates and Compositions
  • a composition is like an aggregate but stronger
  • here the parts only exist in the context of the whole and vice versa
    • a car is not a car without an engine
    • a book is not a book without pages
  • An aggregation relationship
    • aggregate does not keep a private copy of its member objects
    • refers to them by reference
      • investments which contain stocks
public class Investment
{
private Stock x;
private int num;
}
public class Stock
{
private String name;
private double price;
}

  • who creates the stock?
    • investments constructor should not create a stock
    • should already exist when Investment is created
  • should Investment keep a local copy of the Stock?
    • No
      • the stock is under outside control
  • stock outlives the Investment and exists outside the Investment
  • this is an aggregation
  • a composition relationship
    • private copies are kept
    • contained objects do not exist outside of the composition
    • objects live and die with composition
public class CreditCard
{
private String name;
private int cardNum;
private GregorianCalendar dateOfIssue;

//this is a composition relationship

Wednesday, February 7, 2007

Lecture 13

Inner Classes

  • an inner class is a class defined within another class

Example

public class outerClass
{
private class innerClass
{
}
}
  • inner classes provide extra 'class-like' functionality to your class
    • makes your class look self contained
  • inner classes have access to private members of the outer class
    • and vice versa
  • inner classes can be made public and are then visible outside of the outer class

Access

public class outerClass
{
private int y;
private int x;

private class innerClass
{
private int y;

public void method()
{x=0 //if no private member in inner class named x
}
}
  • if no private member in innerClass is named x , it can refer to x in the outer class by name
  • to gain access to the outer class y
    • outerClass.this.y

public class outerClass
{
private int x;
private int y;
private class innerClass
{
private int y;
public void method()
{
x = 0; // refers to the outerClass x
y = 0; //refers to the innerClass y
outerClass.this.y; // refers to outerClass y
}
}
}

  • creating a public Object of an inner class type
public class outerClass
{
public class innerClass
{
}
}
  • first create an object of type outerClass
  • then create an object of type innerClass
outerClass a = new outerClass();
outerClass.innerClass b = a.new innerClass();

Aggregates Compositions and Arrays


Arrays

  • in undergrad say we want to store the grades for all the term tests instead of just the final raw grade
  • an array lets us refer the collections of variables of the same type using a single name and number
Very Important

  • Arrays in java always have their first object at zero (0)
  • if you don't know the length of an array
    • all arrays have a special public field called 'length'
testArray.length
  • Alternative Array Declaration
    • (with initialization)
double[]testArray = {0.0,0.0,0.0,0.0,0.0}
  • this array has 5 elements

Monday, February 5, 2007

Lab 3

Please Post your ideas for Lab 3 here! I haven't started yet, my labs are on tuesday!

For Lab Instructions: Click

Friday, February 2, 2007

SSH Tips and Tricks

I'm tired of programming in prism, i want to program at home.

Andrew uses an SSH client in class to mimic a Linux environment in Windows and to access example files from his login...

I want to do this, but i don't know how!

I spoke to Andrew he said any SSH client will work (putty...etc)
and that everything has to be saved and edited at york to do it through that client

does anyone use SSH at home?
if so can you put the URL for YorkU's SSH portal in the comments of this post?
as well anything you know about SSH that others will find useful would be great...

Later
Jake

Lecture 12

Abstract Classes
  • Abstract class is a class that cannot be instantiated
    • only its children can be instantiated


Abstract Method
  • a method that is not defined in the abstract class
    • only its head is given

Interfaces
  • can be thought of as an extreme abstract class
  • used to group together classes with similar features into a 'type'
  • interfaces contain only abstract method headers
    • no instance fields
  • an interface is a description of how to interact with a group of related classes

Syntax

public interface myInterface

{
/*any method in here is abstract, it is assumed that it is abstract so you don't have to write the keyword 'abstract'*/

public void method(int a);
public int method2();
}

  • any class that implements the interface must override method, and method2

public class MyClass implements MyInterface
{

private int f;
public void method1(int a)
{

System.out.println(a)

}
public int method2()
{
return f;
}

}

  • you can create objects of type MyClass and treat them as type myInterface if necessary

public void interfaceMethod(myInterface in, int a)
{

int b;
in.method1(a);
b = in.method2();

}

  • it is possible to implement multiple interfaces

public class MyClass implements interface1, interface2
{
}

/* this would force MyClass to have all methods from both interface before it will compile */


  • it is possible to have inheritance within interfaces

public interface MyInterface

{

public void M1();
public void M2();

}

public interface myChild extends myInterface

{
public void M3();
}

  • a class that implements an interface but doesn't override one or more interface methods must be an abstract class
  • all unimplemented methods are automatically abstract