Title: CSI 1101 Lab
1CSI 1101Lab 6 February 28, 2003
- Romelia Plesa
- rplesa_at_site.uottawa.ca
2Agenda
- Midterm discussion
- Graphical User Interface
- Assignment 5
- StopWatch Example
3Midterm Solution Question 1 (38 marks)
- Write an interface called Pair. A pair represents
a group of two elements. The interface must
contain the following methods - Object getFirst()
- Object getSecond()
- void swap()
- Solution (5 marks)
- public interface Pair
- public Object getFirst()
- public Object getSecond()
- public void swap()
4Midterm Solution Question 1 (38 marks)
- (b) Write a linked-list implementation for the
abstract data type Pair. This class, called
LinkedPair, must implement the interface Pair and
use the class Node below to store its elements - class Node
- protected Object value
- protected Node next
- protected Node(Object value, Node next)
- this.value value
- this.next next
-
-
- Variables
- The class LinkedPair must have an instance
variable called first to designate the first node
of the linked-list. No other instance variable is
necessary or allowed.
5Midterm Solution Question 1 (38 marks)
- Constructor
- Write a constructor with two parameters, both
of type Object, that are used to initialize the
first and second elements of the list. - Methods
- Write all the necessary methods so that
LinkedPair implements the interface Pair. - boolean equals(Object obj)
- Override the definition of the method
equals(Object obj) so that the method returns
true - if obj designates an object from a class that
also implements the interface Pair and - both data structures contain equivalent objects,
in the same order.
6Midterm Solution Question 1 (38 marks)
- Solution
- public class LinkedPair
- // 2 marks
- private Node first
- // 4 marks
- public LinkedPair(Object firstValue, Object
secondValue) - first new Node(firstValue, new
Node(secondValue, null)) -
- // 2 marks
- public Object getFirst()
- return first.value
-
- // 3 marks
- public Object getSecond()
- return first.next.value
7Midterm Solution Question 1 (38 marks)
- // 4 marks
- public void swap()
- first.next.next first
- first first.next
- first.next.next null
-
- // 5 marks
- public boolean equals(Object obj)
- if (! (obj instanceof Pair))
- return false
- Pair other (Pair) obj
- return getFirst().equals(other.getFirst())
- getSecond().equals(other.getSecond())
-
8Midterm Solution Question 1 (38 marks)
- c) Write an array-based implementation for the
abstract data type Pair. This class, called
ArrayPair, must implement the interface Pair and
use an array to store its elements. - Variables
- The class ArrayPair must have an instance
variable called elements to designate an array of
two elements. No other instance variable is
necessary or allowed. - Constructor
- Write a constructor with two parameters, both of
type Object, that are used to initialize the
first and second elements of the array. - Methods
- Write all the necessary methods so that ArrayPair
implements the interface Pair. - boolean equals(Object obj)
- Override the definition of the method
equals(Object obj) so that the method returns
true - i) if obj designates an object from a class
that also implements the interface Pair and - ii) both data structures contains equivalent
objects, in the same order.
9Midterm Solution Question 1 (38 marks)
- c) public class ArrayPair implements Pair
- // 2 marks
- private Object elements
- // 4 marks
- public ArrayPair(Object firstValue, Object
secondValue) - elements new Object2
- elements0 firstValue
- elements1 secondValue
-
- // 2 marks
- public Object getFirst()
- return elements0
-
- // 2 marks
- public Object getSecond()
- return elements1
10Midterm Solution Question 1 (38 marks)
- // 3 marks
- public void swap()
- Object tmp elements0
- elements0 elements1
- elements1 tmp
-
- public boolean equals(Object obj)
- if (! (obj instanceof Pair))
- return false
- Pair other (Pair) obj
- return getFirst().equals(other.getFirst())
- getSecond().equals(other.getSecond())
-
11Midterm Solution Question 2 (18 marks)
- Create a class hierarchy to represent vehicles
- All vehicles have a weight (double)
- A car is a specialized vehicle that also has a
number of passengers (int) - A truck is a specialized vehicle that carries a
certain load (double) - A truck can load and unload its payload. Trying
to unload more weight than the total weight of
the payload has no effect (the method must also
return false) - The weight of a truck is the weight of the
vehicle plus its payload. - All the weights are expressed in tones.
12Midterm Solution Question 2 (18 marks)
public class Truck extends Vehicle
private double load Truck(double weight)
super(weight) void load(double
load) this.load load
boolean unload(double load) If (load gt
this.load) return false this.load -
load return true public
double getWeight() return super.getWeight()
load
- Solution
- public class Vehicle
- private double weight
- public double getWeight()
- return weight
-
- Vehicle(double weight)
- this.weight weight
-
-
- public class Car extends Vehicle
- private int passenger
- Car(double weight, int passenger)
- super(weight)
- this.passenger passenger
-
- public int getPassenger()
- return passenger
13Midterm Solution Question 2 (18 marks)
- (b) Complete the definition of the method
calculateFees for the class Ferry below. - The method calculateFees returns the total of all
the fees for each vehicle in the ferry. - the passage fee for a car is 10 per tonne plus
5 per passenger - the passage fee for a truck is 100 per tonne.
- class Ferry
- private Vehicle vehicles
- Ferry(Vehicle vehicles)
- this.vehicles vehicles
-
14Midterm Solution Question 2 (18 marks)
- (b) double calculateFees()
- // complete the method
- // 6 marks
- double total 0
- for (int i0 iltvehicles.length i)
- if (vehiclesi instanceof Truck)
- total 100 vehiclesi.getWeight()
-
- else if (vehiclesi instanceof Car)
- total 10 vehiclesi.getWeight()
5((Car)vehiclesi).getPassenger() -
- return total
-
-
15Midterm Solution Question 3 (18 marks)
- In the class SimpleList below, complete the code
for the Method remove(Object obj) so that it
removes the left most occurrence of obj in the
list. - public class SimpleList
- private static class Node
- private Object value
- private Node next
- Node(Object value, Node next)
- this.value value
- this.next next
-
-
16Midterm Solution Question 3 (18 marks)
- private Node first
- public void remove(Object obj)
- // special case the list is empty
- if (first null) // 2 marks
- return
- // special case obj is the first element
- if (first.value.equals(obj)) // 2 marks
- first first.next // 2 marks
- else
- // general case
- Node p first // 2 marks
- while (p.next ! null ! p.next.value.equals(obj
)) 4 marks - p p.next // 2 marks
-
- p.next p.next.next // 4 marks
-
-
17Midterm Solution Question 4 (10 marks)
- In the class ArrayList below, implement the
method toArray(). The class ArrayList implements
a variable size array so that an unlimited number
of elements can be stored. The method toArray()
returns an array that - has the same size as the number of elements
currently stored in the data-structure and - contains all the same elements, in the same order.
private void increaseSize() Object tmp
elements elements new Objecttmp.length 3
/ 2 for (int i0 i lt last i)
elementsi tmpi public void add(Object
t) if (last elements.length)
increaseSize() elementslast t
last
public class ArrayList private Object
elements private int last public ArrayList(int
capacity) elements new Objectcapacity last
0 public int size() return last
18Midterm Solution Question 4 (10 marks)
- // Solution
- public Object toArray()
- Object result new Objectlast
- for (int i0 iltlast i)
- resulti elementsi
-
- return result
-
19Midterm Solution Question 5 (16 marks)
- Given the following class and interface
definitions - public interface I
- public int i()
-
- public abstract class A implements I
- protected int a 1
- public int get () return a
-
- public class B extends A
- private int b 2
- public int get () return b
- public int i() return a b
20Midterm Solution Question 5 (16 marks)
- a) For each of the following, indicate if the
statements are valid or invalid. - i) I o new B()
- o.i()
- (valid)
- I o new I()
- (invalid)
- I o new B()
- o.get()
- (invalid)
- B o new B()
- (invalid)
21Midterm Solution Question 5 (16 marks)
- b) True or false questions.
- The value 2 will be printed.
- B o null
- System.out.println(o.get())
- (false)
- ii) The value 2 will be printed.
- A o new B()
- System.out.println(o.get())
- (true)
- The value 1 will be printed.
- A o new A()
- System.out.println(o.get())
- (false)
22Midterm Solution Question 5 (16 marks)
- (c) Given the following method definition
- public static void mystery(String s)
- s "NEW"
-
- What should be the output produced by the
following statements - String x "OLD"
- mystery(x)
- System.out.println(x)
- ? prints "OLD"
23GUI(Graphical User Interface)
- Applications with GUI are ultimately based on AWT
(Abstract Window Toolkit) - Swing is an improved toolkit
- Packages for GUI
- jawa.awt - Contains all of the classes for
creating user interfaces and for painting
graphics and images - java.awt.event - Provides interfaces and classes
for dealing with different types of events
fired by AWT components.
24Four categories of classes in AWT
25How to define a GUI
- Add window objects to the Grafical User Interface
under the control of a layout manager - Decide which events each object should handle by
adding listeners for the event to the object - The AWT Component Hierarchy
26Component Methods
27Window
- A Window object is a top-level window with no
borders and no menubar. The default layout for a
window is BorderLayout. - Method
- void addWindowListener (WindowListener l)
- ? Adds the specified window listener to receive
window events from this window
28Frame, Panel, Dialog
- A Frame is a top-level window with a title and a
border. - A Panel is the simplest container class. A panel
provides space in which an application can attach
any other component, such as buttons, text field
and even other panels. - Panel ltpanel namegt new Panel ( )
- ltpanel_namegt.add (myButton)
- A Dialog is a top-level window with a title and a
border that is typically used to take some form
of input from the user. - has a parent (or a owner) window
- is automatically closed when the parent window is
closed - may contain most of the available UI Components
29Grid Layout
- The GridLayout class is a layout manager that
lays out a container's components in a
rectangular grid. The container is divided into
equal-sized rectangles, and one component is
placed in each rectangle. - GridLayout()
- Creates a grid layout with a default of one
column per component, in a single row. - GridLayout(int rows, int cols)
- Creates a grid layout with the specified number
of rows and columns.
X
30Border Layout
- A BorderLayout lays out a container, arranging
and resizing its components to fit in five
regions north, south, east, west, and center. - Each region may contain no more than one
component, and is identified by a corresponding
constant NORTH, SOUTH, EAST, WEST, and CENTER - When adding a component to a container with a
border layout, use one of these five constants. - For example
- Panel p new Panel()
- p.setLayout(new BorderLayout())
- p.add(new Button("OK"), BorderLayout.SOUTH)
31Button
- Class Button ? This class creates a labeled
button. - Button(String label)
- If an application wants to perform some action
based on a button being pressed and released, it
should implement ActionListener and register the
new listener to receive events from this button,
by calling the button's addActionListener method - void addActionListener(ActionListener l)
- Adds the specified action listener to receive
action events from this button (Interface
ActionListener) - Any ActionListener should implement the method
- void actionPerformed(ActionEvent e)
- Invoked when an action occurs.
32Label, TextField, List
- Class Label
- A Label object is a component for placing text in
a container. A label displays a single line of
read-only text. The text can be changed by the
application, but a user cannot edit it directly. - Label (String Text, int alignment)
- Constructs a new label that presents the
specified string of text with the specified
alignment - Class TextField
- A TextField object is a text component that
allows for the editing of a single line of text. - TextField(String Text)
- Constructs a new text field initialized with the
specified text - Class List
- The List component presents the user with a
scrolling list of text items - List (int rows)
- Creates a new scrolling list initialized with the
specified number of visible lines
33Assignment 5
- OBJECTIVES
- learn to create a simple graphical user interface
- furhter understanding of object-oriented
programming - follow the principles presented in class and the
lecture notes 11 - The model (ShoppingCart) must be distinct from
the user interface (view and controller). - Therefore, no change to the class ShoppingCart,
and related classes, is allowed.
34Assignment 5 StopWatchUI.java
- Step 1 instantiate window objects
-
- private Button bTime new Button("Add New
Time") - private Button bQuit new Button("Quit")
- private List output new List(10)
- private Dialog dTime new TimeDialog(this)
35Assignment 5 StopWatchUI.java
- Step 2 instantiate and set the layout
- setLayout(new BorderLayout())
- Panel bottom new Panel()
- bottom.setBackground(Color.white)
- bottom.setLayout(new GridLayout(1,2))
36Assignment 5 StopWatchUI.java
- Step 3 add window objects under the influence of
the layout - add(output, "Center")
- bottom.add(bTime)
- bottom.add(bQuit)
- add(bottom, "South")
37Assignment 5 StopWatchUI.java
- Step 4 It is necessary to tell the buttons where
their listener - code is located. This is done by instantiating
listener objects - and associating them with the buttons (The Java
framework - sends messages to the listener objects when the
buttons are - clicked)
- bTime.addActionListener (new ActionListener()
- public void actionPerformed(ActionEvent e)
- dTime.setVisible(true)
-
- )
38Assignment 5 StopWatchUI.java
- Step 5 a listener is needed to close the window
-
- addWindowListener(new WindowAdapter()
- public void windowClosing(WindowEvent e)
- System.exit(0)
-
- )
39What is more in A5?
- More buttons for adding new StoreItem,
consequently, more dialog windows required, such
as WeighDialog, UnitDialog, PreparedDialog - Remove method
- This method should let user select the intended
item to remove - Solution
- highlight the intended item, using the method
getSelectedIndex defined in List class, it
returns the index of the selected item in this
List object -
40What is more in A5?
- We use linked list to implement ShoppingCart, so
the physical size and logical size are always
equal to each other, its not needed to evaluate
if its already the MAX size of the list. - Dont forget to update
- After adding or removing an item, update is
required for both ShoppingCartUI(the view) and
ShoppingCart(the model) - the amount of Tax and the number of items should
also be updated - Tax amount and number of items are shown by Label
objects - Use setText(String str) method to assign captions
for Label objects