Interfaces & Polymorphism part 2: Collections, Comparators, and More fun with Java graphics

Similar documents
COMP Lecture Notes for Week 4 - Interfaces and Polymorphism. Chapter Topics. Displaying an Image. Displaying an Image

Outline. Anonymous Classes. Annoucements. CS1007: Object Oriented Design and Programming in Java

H212 Introduction to Software Systems Honors

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

Building Graphical User Interfaces. GUI Principles

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

SINGLE EVENT HANDLING

Building Graphical User Interfaces. Overview

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Swing from A to Z Some Simple Components. Preface

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Overview. Building Graphical User Interfaces. GUI Principles. AWT and Swing. Constructing GUIs Interface components GUI layout Event handling

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in

COMPSCI 230. Software Design and Construction. Swing

Outline HW2. Feedback. CS1007: Object Oriented Design and Programming in Java

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

MIT AITI Swing Event Model Lecture 17

encompass a group of features for building Graphical User Interfaces (GUI).

Introduction to the JAVA UI classes Advanced HCI IAT351

Window Interfaces Using Swing Objects

It is a promise that your class will implement certain method with certain signatures.

Part I: Learn Common Graphics Components

Introduction. Introduction

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University

Programmierpraktikum

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Abstract, Interface, GUIs. Ch. 11 & 16

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

Window Interfaces Using Swing Objects

1005ICT Object Oriented Programming Lecture Notes

Graphical User Interfaces (GUIs)

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

JRadioButton account_type_radio_button2 = new JRadioButton("Current"); ButtonGroup account_type_button_group = new ButtonGroup();

Graphical User Interfaces. Comp 152

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

Calculator Class. /** * Create a new calculator and show it. */ public Calculator() { engine = new CalcEngine(); gui = new UserInterface(engine); }

COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) )

GUI Forms and Events, Part II

State Application Using MVC

AP CS Unit 11: Graphics and Events

RAIK 183H Examination 2 Solution. November 11, 2013

Swing Programming Example Number 2

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

GUI Applications. Let s start with a simple Swing application in Java, and then we will look at the same application in Jython. See Listing 16-1.

Graphical User Interface (GUI)

Starting Out with Java: From Control Structures Through Objects Sixth Edition

CSC 1214: Object-Oriented Programming

Agenda. Container and Component

RAIK 183H Examination 2 Solution. November 10, 2014

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

SE1021 Exam 2. When returning your exam, place your note-sheet on top. Page 1: This cover. Page 2 (Multiple choice): 10pts

TTTK Program Design and Problem Solving Tutorial 3 (GUI & Event Handlings)

Graphic User Interfaces. - GUI concepts - Swing - AWT

Using Several Components

EPITA Première Année Cycle Ingénieur. Atelier Java - J5

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski

PART1: Choose the correct answer and write it on the answer sheet:

Part 3: Graphical User Interface (GUI) & Java Applets

We are on the GUI fast track path

CS 170 Java Programming 1. Week 15: Interfaces and Exceptions

Introduction This assignment will ask that you write a simple graphical user interface (GUI).

Graphical User Interfaces

Adding Buttons to StyleOptions.java

GUI and its COmponent Textfield, Button & Label. By Iqtidar Ali

CMP 326 Midterm Fall 2015

Class 16: The Swing Event Model

Parts of a Contract. Contract Example. Interface as a Contract. Wednesday, January 30, 13. Postcondition. Preconditions.

PIC 20A GUI with swing

CS 251 Intermediate Programming GUIs: Components and Layout

Introduction to Graphical Interface Programming in Java. Introduction to AWT and Swing

CSIS 10A Assignment 7 SOLUTIONS

An array is a type of variable that is able to hold more than one piece of information under a single variable name.

Java & Graphical User Interface II. Wang Yang wyang AT njnet.edu.cn

DM503 Programming B. Peter Schneider-Kamp.

Java Help Files. by Peter Lavin. May 22, 2004

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords

Systems Programming Graphical User Interfaces

Chapter 13 Lab Advanced GUI Applications Lab Objectives. Introduction. Task #1 Creating a Menu with Submenus

Graphical interfaces & event-driven programming

GUI (Graphic User Interface) Programming. Part 2 (Chapter 8) Chapter Goals. Events, Event Sources, and Event Listeners. Listeners

Graphical User Interfaces 2

Programming Languages and Techniques (CIS120)

H212 Introduction to Software Systems Honors

Name: Checked: Learn about listeners, events, and simple animation for interactive graphical user interfaces.

Prototyping a Swing Interface with the Netbeans IDE GUI Editor

STRUKTUR PROGRAM JAVA: //Daftar paket yang digunakan dalam program import namapaket;

Assignment #3 (Due 4/4/2017)

Chapter 6 Using Objects

Introduction to GUIs. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2014

Chapter 11: Exceptions Lab Exercises

CS 180 Fall 2006 Exam II

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

Commands. Written commands can be reused, cataloged, etc. Sometimes they also contain "undo" commands, too.

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Together, the appearance and how user interacts with the program are known as the program look and feel.

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components

Transcription:

Interfaces & Polymorphism part 2: Collections, Comparators, and More fun with Java graphics 1

Collections (from the Java tutorial)* A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit Collections are used to store, retrieve and manipulate data, and to transmit data from one method to another Collections typically represent data items that form a natural group * http://java.sun.com/docs/books/tutorial/collections/intro/index.html 2

Java s Collections class Consists of a set of methods that operate on collections (which are classes that implement the Collection interface or one of its descendants or their implementing classes, such as ArrayList) One of these methods is static method sort The sort method works on objects that implement the Comparable interface 3

Comparable interface public interface Comparable { int compareto(object other); Suppose object1 is an object of a class that implements Comparable; then the message object1.compareto(object2) should return: a negative number if object1<object2 zero if they are equal a positive number (if object1>object2) 4

Using Collections.sort The String class implements the Comparable interface; thus, to sort an array of Strings: ArrayList words = new ArrayList(); words.add( fossil ); words.add( burgeoning ); words.add( aspersion ); Collections.sort(words); 5

Using Collections.sort If you have an ArrayList of objects of a new class that you wish to sort, that class should implement the Comparable interface; otherwise, Collections.sort throws an exception Your class should: have implements Comparable in its heading implement the compareto method 6

The Comparator interface Objects of a class that implements Comparable can be sorted using Collections.sort() based on the implementing class s compareto method If more than one type of sorting is desired, it is more convenient to implement the Comparator interface rather than the Comparable interface An alternative version of Collections.sort() works with implementors of Comparator 7

Comparator public interface Comparator { int compare(object a, Object b); Return values from compare() are as follows: returns a negative number if a < b returns 0 if a == b returns a positive number if a > b 8

Using sort() with Comparator The sort() method that works with the Comparator interface expects two arguments: a list to be sorted (e.g. an ArrayList - a descendant of List, which is a descendant of Collections) a Comparator (in other words, an object of an implementing class) 9

Implementing Comparator A key fact about implementing Comparator: the class that does the implementing need not be the basis for the objects to be sorted To create multiple sorting methods, can create multiple Comparator classes, each of which implements compare() in a different way The next several slides exemplify these ideas 10

public class Thing implements Comparable { private String name; private int size; public Thing (String aname, int asize) { name = aname; size = asize; public String getname() { return name; public double getsize() { return size; public int compareto(object otherobject) { Thing other = (Thing) otherobject; if (this.size < other.size) return -1; if (this.size > other.size) return 1; return 0; Exhibit A: a Thing that implements the Comparable interface Implementation of compareto is based on the value of size; no way to compare two Things based on name (or any other attribute we might define for a Thing) 11

Exhibit B: a Comparator for Things (based on name rather than size) Note: could create more Comparators for other attributes of Thing (if there were any more) import java.util.*; public class ThingByName implements Comparator { public int compare(object object1, Object object2) { Thing t1 = (Thing) object1; Thing t2 = (Thing) object2; return t1.getname().compareto(t2.getname()); 12

import java.util.*; public class ThingCompTest { public static void main(string[] args) { ArrayList bunchostuff = new ArrayList(); bunchostuff.add(new Thing("ambergris", 87)); bunchostuff.add(new Thing("gummy bear", 4)); bunchostuff.add(new Thing("Belgium", 30510)); Comparator comp = new ThingByName(); Collections.sort(bunchOStuff, comp); System.out.println("things sorted by name:"); for (int i = 0; i < bunchostuff.size(); i++) { Thing t = (Thing) bunchostuff.get(i); System.out.println(t.getName() + " " + t.getsize()); Collections.sort(bunchOStuff); System.out.println("things sorted by size:"); for (int i = 0; i < bunchostuff.size(); i++) { Thing t = (Thing) bunchostuff.get(i); System.out.println(t.getName() + " " + t.getsize()); Exhibit C: a test class, illustrating both sorting methods OUTPUT: things sorted by name: Belgium 30510.0 ambergris 87.0 gummy bear 4.0 things sorted by size: gummy bear 4.0 ambergris 87.0 Belgium 30510.0 13

Anonymous objects An anonymous object is one that is created on the fly in a method call; we saw an example of this in the HolyIconBatman class: JOptionPane.showMessageDialog(null, "Holy icon Batman!", "BatCave", JOptionPane.INFORMATION_MESSAGE, new HolyIconBatman(40)); An anonymous object is simply an object reference that is not stored in a variable 14

Anonymous objects In the ThingCompTest class, the following lines of code: Comparator comp = new ThingByName(); Collections.sort(bunchOStuff, comp); could be replaced by a single line, using an anonymous object instead of variable comp: Collections.sort(bunchOStuff, new ThingByName()); 15

Anonymous classes Anonymous objects are essentially literal values; since they aren t stored anywhere, they can be used once, but would have to be reconstructed to be used again Like an anonymous object, an anonymous class is an unnamed class, defined on the fly When defining an anonymous class, you must also construct an anonymous object 16

Anonymous classes No need to name objects that are used only once: Collections.sort(bunchOStuff, new ThingByName()); By the same taken, no need to name classes that will only be used once The code below creates an anonymous Comparator class to compare things (could use this instead of creating class ThingByName) Comparator comp = new Comparator() { public int compare(object obj1, Object obj2) { Thing t1 = (Thing)obj1; Thing t2 = (Thing)obj2; return t1.getname().compareto(t2.getname()); ; NOTE THE SEMICOLON 17

Anonymous classes The expression: Comparator comp = new Comparator(){ ; defines a class that implements the Comparator interface type defines method compare() constructs an object of the new (unnamed) class An anonymous class is a special case of an inner class (a class defined inside another) 18

Anonymous classes Commonly used in factory methods: public class Thing { public static Comparator ThingByName() { return new Comparator() { ; public int compare(object o1, Object o2) {... Eliminates need to create separate class whose only purpose is to facilitate sorting of primary class 19

Anonymous classes Can now sort ArrayList a of Thing objects by calling: Collections.sort(a, Thing.ThingByName()); Neat arrangement if multiple comparators make sense (by name, by size, by ranking, etc.) Gives both types of comparison equal preference, rather than arbitrarily choosing one to implement using compareto() 20

Frames We have already seen limited use of graphics programming associated with methods of the JOptionPane class A JOptionPane object is one type of GUI window; the generic window type is the frame Frame window has decorations: title bar borders close box 21

Constructing and displaying a frame window JFrame frame = new JFrame(); frame.pack(); // automatically sizes window frame.setdefaultcloseoperation (JFrame.EXIT_ON_CLOSE); // exits program when window closes frame.setvisible(true); // displays frame Note: requires import statements: import java.awt.*; import javax.swing.*; Can also set size of frame using frame.setsize(w, h); 22

Drawing in a frame The part of the frame below the title bar and between the borders is the content pane of the window; you can add components to this by assigning it to a Container object, then adding elements to this object One such element that can be added is a JLabel object, which can be used for display of text or images (or both) The next slide illustrates this 23

import java.awt.*; import javax.swing.*; public class Me2 { public static void main (String[] args) { JFrame frame = new JFrame(); Icon pic1 = new ImageIcon("me2.gif"); JLabel picture1 = new JLabel(pic1); Icon pic2 = new ImageIcon("3x2x2connector.jpg"); JLabel picture2 = new JLabel(pic2); Container windowcontents = frame.getcontentpane(); windowcontents.setlayout(new FlowLayout()); windowcontents.add(picture1); windowcontents.add(picture2); frame.pack(); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setvisible(true); 24

Notes on example As before, an Icon interface variable holds an ImageIcon reference, which is constructed using the name of a graphics file: Icon pic1 = new ImageIcon("me2.gif"); The JLabel objects picture1 and picture2 are constructed with icons inside them: JLabel picture2 = new JLabel(pic2); These objects are then placed in the JFrame s content pane and displayed 25

More notes on example Note the line: contentpane.setlayout(new FlowLayout()); this generates a layout manager to control how the multiple components will line up within the content pane a FlowLayout lines up components side by side 26

Adding user interface components User interface components such as buttons (instances of JButton) and text fields (instances of JTextField) can also be added to the content pane of a frame The FrameTest example (next slide) illustrates this 27

import java.awt.*; import javax.swing.*; public class FrameTest { public static void main(string[] args) { JFrame frame = new JFrame(); JButton hellobutton = new JButton("Say Hello"); JButton goodbyebutton = new JButton("Say Goodbye"); final int FIELD_WIDTH = 20; JTextField textfield = new JTextField(FIELD_WIDTH); textfield.settext("click a button!"); Container contentpane = frame.getcontentpane(); contentpane.setlayout(new FlowLayout()); contentpane.add(hellobutton); contentpane.add(goodbyebutton); contentpane.add(textfield); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.pack(); frame.setvisible(true); 28

User interface components The FrameTest program displays a window that looks like this: But the buttons don t do anything; the window merely displays them To make the buttons active, we need to incorporate ActionListeners 29

ActionListener interface An ActionListener object is one that implements the ActionListener interface and its single method, actionperformed The actionperformed method requires an ActionEvent parameter; such a parameter is supplied by a user action, such as a mouse click 30

Making buttons work Construct a listener object and add it to the button; this can be accomplished using an anonymous class: hellobutton.addactionlistener(new ActionListener() { ); public void actionperformed(actionevent e) { textfield.settext( hello world! ); 31

Accessing variables from enclosing scope The anonymous class constructed on the previous slide is, as previously noted, an example of an inner class Note that the inner class accesses the textfield object, which is a variable of the outer class When a local variable of an enclosing scope is to be accessed by an inner class, the variable must be declared final 32

Constructing multiple instances of anonymous ActionListener Write helper method that constructs objects Pass variable information as parameters Declare parameters final public static ActionListener creategreetingbuttonlistener( final String message) { return new ActionListener() { public void actionperformed(actionevent event) { textfield.settext(message); ; 33

Complete example continued on import java.awt.*; import java.awt.event.*; import javax.swing.*; next slide public class ActionTest { private static JTextField textfield; public static void main(string[] args){ JFrame frame = new JFrame(); final int FIELD_WIDTH = 20; textfield = new JTextField(FIELD_WIDTH); textfield.settext("click a button!"); JButton hellobutton = new JButton("Say Hello"); hellobutton.addactionlistener(creategreetingbuttonlistener("hello, World!")); JButton goodbyebutton = new JButton("Say Goodbye"); goodbyebutton.addactionlistener(creategreetingbuttonlistener("goodbye, World!")); Container contentpane = frame.getcontentpane(); contentpane.setlayout(new FlowLayout()); 34

Example continued contentpane.add(hellobutton); contentpane.add(goodbyebutton); contentpane.add(textfield); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.pack(); frame.setvisible(true); public static ActionListener creategreetingbuttonlistener(final String message) { return new ActionListener() { public void actionperformed(actionevent event) { textfield.settext(message); ; // ends definition of new ActionListener (& return statement) // ends creategreetingbuttonlistener method // ends class 35