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

Size: px
Start display at page:

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

Transcription

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

2 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 * 2

3 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

4 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

5 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

6 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

7 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

8 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

9 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

10 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

11 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

12 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

13 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 ambergris 87.0 gummy bear 4.0 things sorted by size: gummy bear 4.0 ambergris 87.0 Belgium

14 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

15 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

16 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

17 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

18 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

19 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

20 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

21 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

22 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

23 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

24 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

25 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

26 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

27 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

28 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

29 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

30 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

31 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

32 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

33 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

34 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

35 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

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

COMP Lecture Notes for Week 4 - Interfaces and Polymorphism. Chapter Topics. Displaying an Image. Displaying an Image COMP 303 - Lecture Notes for Week 4 - Interfaces and Polymorphism Slides edited from, Object-Oriented Design Patterns, by Cay S. Horstmann Original slides available from: http://www.horstmann.com/design_and_patterns.html

More information

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

Outline. Anonymous Classes. Annoucements. CS1007: Object Oriented Design and Programming in Java Outline CS1007: Object Oriented Design and Programming in Java Lecture #9 Oct 6 Shlomo Hershkop shlomo@cs.columbia.edu Polymorphism Basic graphics Layout managers Customization Reading: 4.5-4.8, 4.9 1

More information

H212 Introduction to Software Systems Honors

H212 Introduction to Software Systems Honors Introduction to Software Systems Honors Lecture #19: November 4, 2015 1/14 Third Exam The third, Checkpoint Exam, will be on: Wednesday, November 11, 2:30 to 3:45 pm You will have 3 questions, out of 9,

More information

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

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling Frames, GUI and events Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling Introduction to Swing The Java AWT (Abstract Window Toolkit)

More information

Building Graphical User Interfaces. GUI Principles

Building Graphical User Interfaces. GUI Principles Building Graphical User Interfaces 4.1 GUI Principles Components: GUI building blocks Buttons, menus, sliders, etc. Layout: arranging components to form a usable GUI Using layout managers. Events: reacting

More information

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

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread G51PGP Programming Paradigms Lecture 008 Inner classes, anonymous classes, Swing worker thread 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals

More information

SINGLE EVENT HANDLING

SINGLE EVENT HANDLING SINGLE EVENT HANDLING Event handling is the process of responding to asynchronous events as they occur during the program run. An event is an action that occurs externally to your program and to which

More information

Building Graphical User Interfaces. Overview

Building Graphical User Interfaces. Overview Building Graphical User Interfaces 4.1 Overview Constructing GUIs Interface components GUI layout Event handling 2 1 GUI Principles Components: GUI building blocks. Buttons, menus, sliders, etc. Layout:

More information

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

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Swing = Java's GUI library Topic 9: Swing Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 5: Will be an open-ended Swing project. "Programming Contest"

More information

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!

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 = Java's GUI library Topic 9: Swing Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Why are we studying Swing? 1. Useful & fun! 2. Good application of OOP techniques

More information

Swing from A to Z Some Simple Components. Preface

Swing from A to Z Some Simple Components. Preface By Richard G. Baldwin baldwin.richard@iname.com Java Programming, Lecture Notes # 1005 July 31, 2000 Swing from A to Z Some Simple Components Preface Introduction Sample Program Interesting Code Fragments

More information

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

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT CSE 143 Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/

More information

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

Overview. Building Graphical User Interfaces. GUI Principles. AWT and Swing. Constructing GUIs Interface components GUI layout Event handling Overview Building Graphical User Interfaces Constructing GUIs Interface components GUI layout Event handling 4.1 GUI Principles AWT and Swing Components: GUI building blocks. Buttons, menus, sliders, etc.

More information

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

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in Lab 4 D0010E Object-Oriented Programming and Design Lecture 9 Lab 4: You will implement a game that can be played over the Internet. The networking part has already been written. Among other things, the

More information

COMPSCI 230. Software Design and Construction. Swing

COMPSCI 230. Software Design and Construction. Swing COMPSCI 230 Software Design and Construction Swing 1 2013-04-17 Recap: SWING DESIGN PRINCIPLES 1. GUI is built as containment hierarchy of widgets (i.e. the parent-child nesting relation between them)

More information

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

Outline HW2. Feedback. CS1007: Object Oriented Design and Programming in Java Outline CS1007: Object Oriented Design and Programming in Java Lecture #8 Oct 4 Shlomo Hershkop shlomo@cs.columbia.edu Unit Testing Sorting Algorithms Polymorphism Interfaces Basic graphics Layout managers

More information

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

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class CHAPTER GRAPHICAL USER INTERFACES 10 Slides by Donald W. Smith TechNeTrain.com Final Draft 10/30/11 10.1 Frame Windows Java provides classes to create graphical applications that can run on any major graphical

More information

MIT AITI Swing Event Model Lecture 17

MIT AITI Swing Event Model Lecture 17 MIT AITI 2004 Swing Event Model Lecture 17 The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the user. But how do GUIs interact with users? How do applications

More information

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

encompass a group of features for building Graphical User Interfaces (GUI). Java GUI (intro) JFC Java Foundation Classes encompass a group of features for building Graphical User Interfaces (GUI). javax.swing.* used for building GUIs. Some basic functionality is already there

More information

Introduction to the JAVA UI classes Advanced HCI IAT351

Introduction to the JAVA UI classes Advanced HCI IAT351 Introduction to the JAVA UI classes Advanced HCI IAT351 Week 3 Lecture 1 17.09.2012 Lyn Bartram lyn@sfu.ca About JFC and Swing JFC Java TM Foundation Classes Encompass a group of features for constructing

More information

Window Interfaces Using Swing Objects

Window Interfaces Using Swing Objects Chapter 12 Window Interfaces Using Swing Objects Event-Driven Programming and GUIs Swing Basics and a Simple Demo Program Layout Managers Buttons and Action Listeners Container Classes Text I/O for GUIs

More information

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

It is a promise that your class will implement certain method with certain signatures. Chapter 4: Interfaces and Polymorphism Chapter Topics Interface Polymorphism The Comparable Interface The Comparator Interface Anonymous Classes GUI Programming Event Handling Simple animation using Timer

More information

Part I: Learn Common Graphics Components

Part I: Learn Common Graphics Components OOP GUI Components and Event Handling Page 1 Objectives 1. Practice creating and using graphical components. 2. Practice adding Event Listeners to handle the events and do something. 3. Learn how to connect

More information

Introduction. Introduction

Introduction. Introduction Introduction Many Java application use a graphical user interface or GUI (pronounced gooey ). A GUI is a graphical window or windows that provide interaction with the user. GUI s accept input from: the

More information

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

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics Topic 9: Swing Outline Swing = Java's GUI library Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 7: Expand moving shapes from Assignment 4 into game. "Programming

More information

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

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1 Java Swing based on slides by: Walter Milner Java Swing Walter Milner 2005: Slide 1 What is Swing? A group of 14 packages to do with the UI 451 classes as at 1.4 (!) Part of JFC Java Foundation Classes

More information

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

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University Java Swing Recitation 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University Announcements Project 8 is out Milestone due on Dec 3rd, 10:00 pm Final due on Dec 10th, 10:00 pm No classes,

More information

Programmierpraktikum

Programmierpraktikum Programmierpraktikum Claudius Gros, SS2012 Institut für theoretische Physik Goethe-University Frankfurt a.m. 1 of 25 17/01/13 11:45 Swing Graphical User Interface (GUI) 2 of 25 17/01/13 11:45 Graphical

More information

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7 PROGRAMMING DESIGN USING JAVA (ITT 303) Graphical User Interface Unit 7 Learning Objectives At the end of this unit students should be able to: Build graphical user interfaces Create and manipulate buttons,

More information

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

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT CSE 331 Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/

More information

Abstract, Interface, GUIs. Ch. 11 & 16

Abstract, Interface, GUIs. Ch. 11 & 16 Abstract, Interface, GUIs Ch. 11 & 16 Abstract A class declared abstract cannot be instan:ated (we can t create an object of its type). A method declared abstract MUST be implemented if a class subclasses

More information

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

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User CSE3461 Control Flow Paradigms: Reacting to the User Control Flow: Overview Definition of control flow: The sequence of execution of instructions in a program. Control flow is determined at run time by

More information

Window Interfaces Using Swing Objects

Window Interfaces Using Swing Objects Chapter 12 Window Interfaces Using Swing Objects Event-Driven Programming and GUIs Swing Basics and a Simple Demo Program Layout Managers Buttons and Action Listeners Container Classes Text I/O for GUIs

More information

1005ICT Object Oriented Programming Lecture Notes

1005ICT Object Oriented Programming Lecture Notes 1005ICT Object Oriented Programming Lecture Notes School of Information and Communication Technology Griffith University Semester 2, 2015 1 20 GUI Components and Events This section develops a program

More information

Graphical User Interfaces (GUIs)

Graphical User Interfaces (GUIs) CMSC 132: Object-Oriented Programming II Graphical User Interfaces (GUIs) Department of Computer Science University of Maryland, College Park Model-View-Controller (MVC) Model for GUI programming (Xerox

More information

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

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Events and Listeners CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides

More information

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

JRadioButton account_type_radio_button2 = new JRadioButton(Current); ButtonGroup account_type_button_group = new ButtonGroup(); Q)Write a program to design an interface containing fields User ID, Password and Account type, and buttons login, cancel, edit by mixing border layout and flow layout. Add events handling to the button

More information

Graphical User Interfaces. Comp 152

Graphical User Interfaces. Comp 152 Graphical User Interfaces Comp 152 Procedural programming Execute line of code at a time Allowing for selection and repetition Call one function and then another. Can trace program execution on paper from

More information

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright GUI Basics Object Orientated Programming in Java Benjamin Kenwright Outline Essential Graphical User Interface (GUI) Concepts Libraries, Implementation, Mechanics,.. Abstract Windowing Toolkit (AWT) Java

More information

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

Calculator Class. /** * Create a new calculator and show it. */ public Calculator() { engine = new CalcEngine(); gui = new UserInterface(engine); } A Calculator Project This will be our first exposure to building a Graphical User Interface (GUI) in Java The functions of the calculator are self-evident The Calculator class creates a UserInterface Class

More information

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 :) )

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 :) ) 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 :) ) Course Evaluations Please do these. -Fast to do -Used to

More information

GUI Forms and Events, Part II

GUI Forms and Events, Part II GUI Forms and Events, Part II Quick Start Compile step once always mkdir labs javac PropertyTax6.java cd labs Execute step mkdir 6 java PropertyTax6 cd 6 cp../5/propertytax5.java PropertyTax6.java Submit

More information

State Application Using MVC

State Application Using MVC State Application Using MVC 1. Getting ed: Stories and GUI Sketch This example illustrates how applications can be thought of as passing through different states. The code given shows a very useful way

More information

AP CS Unit 11: Graphics and Events

AP CS Unit 11: Graphics and Events AP CS Unit 11: Graphics and Events This packet shows how to create programs with a graphical interface in a way that is consistent with the approach used in the Elevens program. Copy the following two

More information

RAIK 183H Examination 2 Solution. November 11, 2013

RAIK 183H Examination 2 Solution. November 11, 2013 RAIK 183H Examination 2 Solution November 11, 2013 Name: NUID: This examination consists of 5 questions and you have 110 minutes to complete the test. Show all steps (including any computations/explanations)

More information

Swing Programming Example Number 2

Swing Programming Example Number 2 1 Swing Programming Example Number 2 Problem Statement (Part 1 and 2 (H/w- assignment) 2 Demonstrate the use of swing Label, TextField, RadioButton, CheckBox, Listbox,Combo Box, Toggle button,image Icon

More information

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions G51PGP Programming Paradigms Lecture 009 Concurrency, exceptions 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals = new Animal[6]; animals[0]

More information

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.

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. GUI Applications The C implementation of Python comes with Tkinter for writing Graphical User Interfaces (GUIs). The GUI toolkit that you get automatically with Jython is Swing, which is included with

More information

Graphical User Interface (GUI)

Graphical User Interface (GUI) Graphical User Interface (GUI) Layout Managment 1 Hello World Often have a static method: createandshowgui() Invoked by main calling invokelater private static void createandshowgui() { } JFrame frame

More information

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

Starting Out with Java: From Control Structures Through Objects Sixth Edition Starting Out with Java: From Control Structures Through Objects Sixth Edition Chapter 12 A First Look at GUI Applications Chapter Topics 12.1 Introduction 12.2 Creating Windows 12.3 Equipping GUI Classes

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

Agenda. Container and Component

Agenda. Container and Component Agenda Types of GUI classes/objects Step-by-step guide to create a graphic user interface Step-by-step guide to event-handling PS5 Problem 1 PS5 Problem 2 Container and Component There are two types of

More information

RAIK 183H Examination 2 Solution. November 10, 2014

RAIK 183H Examination 2 Solution. November 10, 2014 RAIK 183H Examination 2 Solution November 10, 2014 Name: NUID: This examination consists of 5 questions and you have 110 minutes to complete the test. Show all steps (including any computations/explanations)

More information

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

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing CSEN401 Computer Programming Lab Topics: Graphical User Interface Window Interfaces using Swing Prof. Dr. Slim Abdennadher 22.3.2015 c S. Abdennadher 1 Swing c S. Abdennadher 2 AWT versus Swing Two basic

More information

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

SE1021 Exam 2. When returning your exam, place your note-sheet on top. Page 1: This cover. Page 2 (Multiple choice): 10pts SE1021 Exam 2 Name: You may use a note-sheet for this exam. But all answers should be your own, not from slides or text. Review all questions before you get started. The exam is printed single-sided. Write

More information

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

TTTK Program Design and Problem Solving Tutorial 3 (GUI & Event Handlings) TTTK1143 - Program Design and Problem Solving Tutorial 3 (GUI & Event Handlings) Topic: JApplet and ContentPane. 1. Complete the following class to create a Java Applet whose pane s background color is

More information

Graphic User Interfaces. - GUI concepts - Swing - AWT

Graphic User Interfaces. - GUI concepts - Swing - AWT Graphic User Interfaces - GUI concepts - Swing - AWT 1 What is GUI Graphic User Interfaces are used in programs to communicate more efficiently with computer users MacOS MS Windows X Windows etc 2 Considerations

More information

Using Several Components

Using Several Components Ch. 16 pt 2 GUIs Using Several Components How do we arrange the GUI components? Using layout managers. How do we respond to event from several sources? Create separate listeners, or determine the source

More information

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

EPITA Première Année Cycle Ingénieur. Atelier Java - J5 EPITA Première Année Cycle Ingénieur marwan.burelle@lse.epita.fr http://www.lse.epita.fr Overview 1 2 Different toolkits AWT: the good-old one, lakes some features and has a plateform specific look n

More information

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

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski CS 190 - Java Introduction to Java Andy Mroczkowski uamroczk@cs.drexel.edu Department of Computer Science Drexel University March 10, 2008 / Lecture 8 Outline Course Status Course Information & Schedule

More information

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

PART1: Choose the correct answer and write it on the answer sheet: PART1: Choose the correct answer and write it on the answer sheet: (15 marks 20 minutes) 1. Which of the following is included in Java SDK? a. Java interpreter c. Java disassembler b. Java debugger d.

More information

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

Part 3: Graphical User Interface (GUI) & Java Applets 1,QWURGXFWLRQWR-DYD3URJUDPPLQJ (( Part 3: Graphical User Interface (GUI) & Java Applets EE905-GUI 7RSLFV Creating a Window Panels Event Handling Swing GUI Components ƒ Layout Management ƒ Text Field ƒ

More information

We are on the GUI fast track path

We are on the GUI fast track path We are on the GUI fast track path Chapter 13: Exception Handling Skip for now Chapter 14: Abstract Classes and Interfaces Sections 1 9: ActionListener interface Chapter 15: Graphics Skip for now Chapter

More information

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

CS 170 Java Programming 1. Week 15: Interfaces and Exceptions CS 170 Java Programming 1 Week 15: Interfaces and Exceptions Your "IC" or "Lab" Document Use Word or OpenOffice to create a new document Save the file as IC15.doc (Office 97-2003 compatible) Place on your

More information

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

Introduction This assignment will ask that you write a simple graphical user interface (GUI). Computing and Information Systems/Creative Computing University of London International Programmes 2910220: Graphical Object-Oriented and Internet programming in Java Coursework one 2011-12 Introduction

More information

Graphical User Interfaces

Graphical User Interfaces Graphical User Interfaces CSCI 136: Fundamentals CSCI 136: Fundamentals of Computer of Science Computer II Science Keith II Vertanen Keith Vertanen Copyright 2011 Overview Command line versus GUI apps

More information

Adding Buttons to StyleOptions.java

Adding Buttons to StyleOptions.java Adding Buttons to StyleOptions.java The files StyleOptions.java and StyleOptionsPanel.java are from Listings 5.14 and 5.15 of the text (with a couple of slight changes an instance variable fontsize is

More information

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

GUI and its COmponent Textfield, Button & Label. By Iqtidar Ali GUI and its COmponent Textfield, Button & Label By Iqtidar Ali GUI (Graphical User Interface) GUI is a visual interface to a program. GUI are built from GUI components. A GUI component is an object with

More information

CMP 326 Midterm Fall 2015

CMP 326 Midterm Fall 2015 CMP 326 Midterm Fall 2015 Name: 1) (30 points; 5 points each) Write the output of each piece of code. If the code gives an error, write any output that would happen before the error, and then write ERROR.

More information

Class 16: The Swing Event Model

Class 16: The Swing Event Model Introduction to Computation and Problem Solving Class 16: The Swing Event Model Prof. Steven R. Lerman and Dr. V. Judson Harward 1 The Java Event Model Up until now, we have focused on GUI's to present

More information

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

Parts of a Contract. Contract Example. Interface as a Contract. Wednesday, January 30, 13. Postcondition. Preconditions. Parts of a Contract Syntax - Method signature Method name Parameter list Return type Semantics - Comments Preconditions: requirements placed on the caller Postconditions: what the method modifies and/or

More information

PIC 20A GUI with swing

PIC 20A GUI with swing PIC 20A GUI with swing Ernest Ryu UCLA Mathematics Last edited: November 22, 2017 Hello swing Let s create a JFrame. import javax. swing.*; public class Test { public static void main ( String [] args

More information

CS 251 Intermediate Programming GUIs: Components and Layout

CS 251 Intermediate Programming GUIs: Components and Layout CS 251 Intermediate Programming GUIs: Components and Layout Brooke Chenoweth University of New Mexico Fall 2017 import javax. swing.*; Hello GUI public class HelloGUI extends JFrame { public HelloGUI ()

More information

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

Introduction to Graphical Interface Programming in Java. Introduction to AWT and Swing Introduction to Graphical Interface Programming in Java Introduction to AWT and Swing GUI versus Graphics Programming Graphical User Interface (GUI) Graphics Programming Purpose is to display info and

More information

CSIS 10A Assignment 7 SOLUTIONS

CSIS 10A Assignment 7 SOLUTIONS CSIS 10A Assignment 7 SOLUTIONS Read: Chapter 7 Choose and complete any 10 points from the problems below, which are all included in the download file on the website. Use BlueJ to complete the assignment,

More information

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

An array is a type of variable that is able to hold more than one piece of information under a single variable name. Arrays An array is a type of variable that is able to hold more than one piece of information under a single variable name. Basically you are sub-dividing a memory box into many numbered slots that can

More information

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

Java & Graphical User Interface II. Wang Yang wyang AT njnet.edu.cn Java & Graphical User Interface II Wang Yang wyang AT njnet.edu.cn Outline Review of GUI (first part) What is Event Basic Elements of Event Programming Secret Weapon - Inner Class Full version of Event

More information

DM503 Programming B. Peter Schneider-Kamp.

DM503 Programming B. Peter Schneider-Kamp. DM503 Programming B Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm503/! ADVANCED OBJECT-ORIENTATION 2 Object-Oriented Design classes often do not exist in isolation from each

More information

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

Java Help Files. by Peter Lavin. May 22, 2004 Java Help Files by Peter Lavin May 22, 2004 Overview Help screens are a necessity for making any application user-friendly. This article will show how the JEditorPane and JFrame classes, along with HTML

More information

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

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords Goals By the end of this lesson, you should: Lecture 7 More GUI programming 1. Be able to write Java s with JTextField, JList, JCheckBox and JRadioButton components 2. Be able to implement a ButtonGroup

More information

Systems Programming Graphical User Interfaces

Systems Programming Graphical User Interfaces Systems Programming Graphical User Interfaces Julio Villena Román (LECTURER) CONTENTS ARE MOSTLY BASED ON THE WORK BY: José Jesús García Rueda Systems Programming GUIs based on Java

More information

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

Chapter 13 Lab Advanced GUI Applications Lab Objectives. Introduction. Task #1 Creating a Menu with Submenus Chapter 13 Lab Advanced GUI Applications Lab Objectives Be able to add a menu to the menu bar Be able to use nested menus Be able to add scroll bars, giving the user the option of when they will be seen.

More information

Graphical interfaces & event-driven programming

Graphical interfaces & event-driven programming Graphical interfaces & event-driven programming Lecture 12 of TDA 540 (Objektorienterad Programmering) Carlo A. Furia Alex Gerdes Chalmers University of Technology Gothenburg University Fall 2017 Pop quiz!

More information

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

GUI (Graphic User Interface) Programming. Part 2 (Chapter 8) Chapter Goals. Events, Event Sources, and Event Listeners. Listeners GUI (Graphic User Interface) Programming Part 2 (Chapter 8) Chapter Goals To understand the Java event model To install action and mouse event listeners To accept input from buttons, text fields, and the

More information

Graphical User Interfaces 2

Graphical User Interfaces 2 Graphical User Interfaces 2 CSCI 136: Fundamentals CSCI 136: Fundamentals of Computer of Science Computer II Science Keith II Vertanen Keith Vertanen Copyright 2011 Extending JFrame Dialog boxes Overview

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 32 April 9, 2018 Swing I: Drawing and Event Handling Chapter 29 HW8: Spellchecker Available on the web site Due: Tuesday! Announcements Parsing, working

More information

H212 Introduction to Software Systems Honors

H212 Introduction to Software Systems Honors Introduction to Software Systems Honors Lecture #15: October 21, 2015 1/34 Generic classes and types Generic programming is the creation of programming constructs that can be usedwith many different types.

More information

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

Name: Checked: Learn about listeners, events, and simple animation for interactive graphical user interfaces. Lab 15 Name: Checked: Objectives: Learn about listeners, events, and simple animation for interactive graphical user interfaces. Files: http://www.csc.villanova.edu/~map/1051/chap04/smilingface.java http://www.csc.villanova.edu/~map/1051/chap04/smilingfacepanel.java

More information

Prototyping a Swing Interface with the Netbeans IDE GUI Editor

Prototyping a Swing Interface with the Netbeans IDE GUI Editor Prototyping a Swing Interface with the Netbeans IDE GUI Editor Netbeans provides an environment for creating Java applications including a module for GUI design. Here we assume that we have some existing

More information

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

STRUKTUR PROGRAM JAVA: //Daftar paket yang digunakan dalam program import namapaket; STRUKTUR PROGRAM JAVA: //Daftar paket yang digunakan dalam program import namapaket; //Membuat Kelas public class namakelas //Metode Utama public static void main(string[] args) perintah-perintah;... LATIHAN

More information

Assignment #3 (Due 4/4/2017)

Assignment #3 (Due 4/4/2017) Assignment #3 (Due 4/4/2017) As a follow up to Assignment #2, modify the CheckingAccount class to add the following instance members: an array (self-expanding type) or ArrayList of Transaction objects

More information

Chapter 6 Using Objects

Chapter 6 Using Objects *** Chapter 6 Using Objects This chapter explains: the use of private instance variables; the use of library classes; the use of new and constructors; event-handling; the Random class; the Swing label,

More information

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

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

More information

Chapter 11: Exceptions Lab Exercises

Chapter 11: Exceptions Lab Exercises Chapter 11: Exceptions Lab Exercises Topics Exceptions File Input and Output Mnemonics Tooltips Disabling Buttons Combo Boxes Scroll Panes Lab Exercises Exceptions Aren t Always Errors Placing Exception

More information

CS 180 Fall 2006 Exam II

CS 180 Fall 2006 Exam II CS 180 Fall 2006 Exam II There are 20 multiple choice questions. Each one is worth 2 points. There are 3 programming questions worth a total of 60 points. Answer the multiple choice questions on the bubble

More information

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

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson) Graphics programming COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson) Overview Aims To provide an overview of Swing and the AWT To show how to build

More information

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

Commands. Written commands can be reused, cataloged, etc. Sometimes they also contain undo commands, too. Commands A command is something you want someone else to perform. Instead of directly issuing a command, we can write it down and give it to someone to perform. Written commands can be reused, cataloged,

More information

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming Objectives: Last revised 1/15/10 1. To introduce the notion of a component and some basic Swing components (JLabel, JTextField, JTextArea,

More information

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

Together, the appearance and how user interacts with the program are known as the program look and feel. Lecture 10 Graphical User Interfaces A graphical user interface is a visual interface to a program. GUIs are built from GUI components (buttons, menus, labels etc). A GUI component is an object with which

More information

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

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components CS112-Section2 Hakan Guldas Burcin Ozcan Meltem Kaya Muge Celiktas Notes of 6-8 May Graphics Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how

More information