AP Computer Science Unit 13. Still More Graphics and Animation.

Size: px
Start display at page:

Download "AP Computer Science Unit 13. Still More Graphics and Animation."

Transcription

1 AP Computer Science Unit 13. Still More Graphics and Animation. In this unit you ll learn about the following: Mouse Motion Listener Suggestions for designing better graphical programs Simple game with modeling classes and view classes Keyboard Listener ****************************************** If we want to detect if the user is moving the mouse, then we need to know about the MouseMotionListener interface. It has two methods: void mousedragged(mouseevent e) void mousemoved(mouseevent e) Often we use this with the events handled by the MouseListener interface. Copy and run the first program which consists of the RunMotionFrame and MotionPanel classes. As you move the mouse, points are added to an array list and drawn as circles. If you drag the mouse, nothing should appear. If the user moves the mouse off the panel and then back onto the panel, the array list is cleared. Notice that I moved the main method into the RunMotionFrame class. This is neither better nor worse (in my opinion) that keeping the main method in its own class. The code for these two classes is on the next page. 1

2 import javax.swing.*; import java.awt.*; public class RunMotionFrame extends JFrame { public static void main(string[] args) { RunMotionFrame f = new RunMotionFrame(); f.display(); public RunMotionFrame(){ setdefaultcloseoperation(exit_on_close); settitle( "Graphics" ); MotionPanel mp = new MotionPanel(); mp.setpreferredsize(new Dimension(400, 400)); getcontentpane().add( mp ); pack(); public void display() { EventQueue.invokeLater(new Runnable() { public void run() { setvisible(true); ); Notice: addmousemotionlistener( eek ); Notice: implements both listeners import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.arraylist; public class MotionPanel extends JPanel { private ArrayList<Point> pts = new ArrayList<Point>(); public MotionPanel() { setbackground( Color.ORANGE ); setborder( BorderFactory.createLineBorder(Color.BLACK ) ); Eek eek = new Eek(); addmousemotionlistener( eek ); addmouselistener( eek public void paintcomponent( Graphics g ) { super.paintcomponent( g ); for ( Point p : pts ) g.filloval( p.x-5, p.y-5, 10, 10 ); private class Eek implements MouseListener, MouseMotionListener{ public void mouseentered( MouseEvent e ){ pts.clear(); repaint(); public void mousepressed( MouseEvent e ){ public void mousereleased( MouseEvent e ) { public void mouseexited( MouseEvent e ){ public void mouseclicked( MouseEvent e ){ public void mousedragged( MouseEvent e ){ public void mousemoved( MouseEvent e ){ int x = e.getx(); int y = e.gety(); pts.add( new Point( x, y ) ); repaint(); Notice that the Eek class implements both interfaces and therefore needs to have seven methods, even though it only uses two methods. The MouseAdapter class is an abstract class that implements both the MouseListener and MouseMotionListener interfaces (it also implements the MouseWheelListener interface). These methods in MouseAdapter do nothing. We can simplify the Eek class by making it a subclass of MouseAdapter and then overriding those methods that we actually need. This is shown on the next page. 2

3 private class Eek extends public void mouseentered( MouseEvent e ){ pts.clear(); public void mousemoved( MouseEvent e ){ int x = e.getx(); int y = e.gety(); pts.add( new Point( x, y ) ); repaint(); As you can see this is a lot cleaner than the earlier approach. ALERT. You should always use notation when extending MouseAdapter. Please remind me to say why (as opposed to earlier when we were implementing an interface and it was not as important to Program 1. When the user presses their mouse on a panel, a point appears. As they drag the mouse a line goes from where they pressed to their current location. When the mouse is released, the line is finished. If they press the mouse again, the old line disappears and a new line starts to appear. There are two of these panels in the frame. The inner class should extend MouseAdapter. To generate a thicker line, do the following in the paintcomponent method: Graphics2D g2 = (Graphics2D) g; g2.setstroke(new BasicStroke(5)); g2.drawline(x1, y1, x2, y2 ); Graphics2D is a subclass of the Graphics class so it inherits all the methods of Graphics and adds some new ones as well. Program 2. Similar to exercise 1 except there s an array of points so you can draw pictures (as long as it is all straight lines). If the user right-clicks on a panel, everything is erased. 3

4 Good Design. When you are developing a program that has a graphical interface, it is a very good idea to have some classes whose main responsibility is to display information to the user and other classes that are responsible for modeling the underlying behavior of the program. Example: In this program there are circles moving around the panel at different speeds. When they hit the sides of the panel, they bounce off the walls. Program 3. There are two panels that do the same thing. If the user drags the mouse in a panel, circles are generated and start moving around the panel and bouncing off the walls. If the user moves the mouse (but not dragging) over a circle, the circle is removed. When the mouse exits the panel, the circles stop moving. If the mouse enters the panel, the circles start moving again. The Circle class represents a circle that has a center, color, and velocity. In the version below, the circle only moves left or right. Later you will modify the class so that the circles move in the y direction as well. import java.awt.*; import java.awt.geom.*; // needed for the Point2D and Point2D.Double classes public class Circle{ private double x, y; // coordinates of the circle s center private double dx; // speed in the x direction public static final int RADIUS = 10; private Color color; public Circle( double x, double y ){ this.x = x; this.y = y; dx = 5*Math.random() + 2; if (Math.random() < 0.5 ) dx = -dx; int red = (int)(256*math.random()); int green = (int)(256*math.random()); int blue = (int)(256*math.random()); int alpha = (int)(256*math.random()); color = new Color( red, green, blue, alpha ); 4

5 public void draw( Graphics g ){ Draw a circle with the given center and radius. The edge of the circle should be black and use the color variable for the fill. public Point2D getcenter(){ return new Point2D.Double( x, y ); public boolean contains( Point2D p ){ double diffx2 = (p.getx() - this.x)*(p.getx() - this.x); double diffy2 = (p.gety() - this.y)*(p.gety() - this.y); return diffx2 + diffy2 <= RADIUS*RADIUS; public void updatelocation(){ x += dx; public void changelocation( double x1, double y1 ){ x = x1; y = y1; public double getdx(){ return dx; public void setdx( double d ){ dx = d; Point2D is an abstract class. Point2D.Double is a static nested class of Point2D that extends Point2D The contains method returns true if the p is a point within the circle. We do not take the square root because it is faster to compare the distance^2 values public void slowdown( double amt ){ amt = Math.abs( amt ); if ( Math.abs( dx ) <= amt ) dx = 0; else if ( dx > 0 ) dx = dx - amt; else dx = dx + amt; if ( Math.abs( dx ) < 0.1 ) dx = 0; The slowdown method decreases the circle s speed by whatever value amt is. This method is not used in exercise 3 but it is used in exercise 4. 5

6 The Environment class represents a collection of circles moving in a frictionless rectangular enclosure. import java.util.arraylist; import java.awt.*; import java.awt.geom.*; public class Environment{ private int width, height; // size of the rectangular space private ArrayList<Circle> list = new ArrayList<Circle>(); public Environment( int w, int h ){ width = w; height = h; public void add( int x, int y ){ list.add( new Circle( x, y ) ); public void update( ){ for ( Circle c : list ){ c.updatelocation(); Point2D loc = c.getcenter(); if ( loc.getx() <= 0 loc.getx() >= width ) c.setdx( -c.getdx() ); The update method calls each Circle s updatelocation method. Then it determines if the circle has moved too far left or right. If it has, it flips the circle s velocity from positive to negative or negative to positive as appropriate. public void delete( Point p ){ for ( int k = list.size() - 1; k>= 0; k-- ){ if ( list.get( k ).contains( p ) ) list.remove( k ); public void draw( Graphics g ){ for ( Circle c : list ) c.draw( g ); IMPORTANT. Notice in the design of the Circle and Environment classes, they are not dependent on how they will be shown to the user. We could show them as JLabels or we call the draw method and display them on a JPanel. This makes them easier to code and use. 6

7 Here is the beginning of the Ex3_Panel class that displays the circles: public class Ex3_Panel extends JPanel { private Environment env; private javax.swing.timer timer; public Ex3_Panel( int width, int height ) { env = new Environment( width, height ); setbackground( Color.WHITE ); setborder( BorderFactory.createLineBorder(Color.BLACK ) ); Eek eek = new Eek(); addmousemotionlistener( eek ); addmouselistener( eek ); timer = new javax.swing.timer( 40, new TimerListener() ); public void paintcomponent( Graphics g ) { super.paintcomponent( g ); env.draw( g ); Write the TimerListener class. Its sole method contains two lines of code. The second line is: repaint(); Write the Eek class which extends MouseAdapter. Each method is no more than two lines long. Whenever the mouse is dragged in the panel, add circles at the mouse s location. Whenever the mouse is moved (not dragged) in the panel, remove any circles that the mouse is over. If the mouse exits the panel, stop the timer. If the mouse enters the panel, start the timer. Write a class that extends JFrame and contains two instances of the Ex3_Panel class. After you get this working, go back to the Circle class and change it so a circle also moves in the y direction. This means: (1) adding another instance variable; (2) changing the constructor; (3) changing the updatelocation method; (4) adding mutator and accessor methods for the new instance variable; and (5) modifying the slowdown method. You will also need to modify the Environment class by changing its update method. 7

8 Program 4. This exercise is a variation on the work you did in exercise 3. When the user drags the mouse on a panel, moving circles are added to the panel. However, these circles gradually slow down. When they stop moving they are removed from the panel. The timer for each panel starts when the panel is instantiated and never stops. There are also JLabels below the panels which indicate the number of circles currently in the panel. Use the same Circle class from exercise 3 (with circles moving in both the x and y directions). Write the Friction_Env class which is identical to the Environment class from Exercise 3 except: 1) Add the following method public int numcircles(){ returns the number of circles in the panel 2) Change the update method as follows. public void update( ) Iterate through the list of Circle objects and call each Circle s slowdown method. I suggest you use an argument of 1.0 or less. If a Circle s speed in the x and y directions are both zero, remove that Circle. Call the updatelocation method for all the remaining Circles. Make sure to change a Circle s velocities if it hits one of the walls. The JLabels should NOT be part of the class that extends JPanel and displays the Circles. I suggest that whenever the Timer object generates an action event (in the panel subclass), you update the text on the corresponding JLabel (that s in the class that extends JFrame). 8

9 Last Program. Here we will make a simple game. We move a player around a panel using the arrow keys. You get 10 points for every blue heart you catch. Your health decreases each time you hit the star-like images. You die on the third hit and the game stops. Here is the basic design. There are six classes. RunGame simply contains the main method that we ve been using. GameFrame extends JFrame. It creates a button (at the top), a label (at the bottom), and a GamePanel (in the middle). It also contains a timer and a Game object. GamePanel extends JPanel. This contains a reference to the same Game object that the GameFrame class created. It draws all the objects in the game. The GamePanel also contains a KeyListener that controls how the Player object moves. The Player class models the concept of something/someone moving around the field. It has a location, speed, and health attributes (as well as other attributes). The Guy class models the concept of things moving from right to left across the field. Some Guy objects are good meaning the player should try to get them. Some Guy objects are bad meaning the player should try to avoid them. The Game class models the game s behavior. It contains a Player object and an array list of Guy objects. Important: the GameFrame and GamePanel classes only communicate with the Game object; they never directly communicate with the Player or Guy classes. It has an update method that is called every time the Timer fires off an Action event. In this update method: o the player s move method is called o new Guy objects are spawned o each Guy object is moved o collisions between the player and Guy objects are detected o Guy objects that have moved off the left edge of the panel are removed Copy the files and complete the methods. Download the images. If using BlueJ, put the images in the folder with the java files. If using Eclipse, put the images in the folder than contains the scr and bin folders. Please change the images, speeds, etc. to make the game more interesting to you. Just don t make major changes to the overall design without first discussing it with me. The KeyListener code is discussed on the next page. 9

10 Some words about Key Listener code in this project. The KeyListener interface has three methods. void keypressed(keyevent e) Invoked when a key has been pressed. void keyreleased(keyevent e) Invoked when a key has been released. void keytyped(keyevent e) Invoked when a key has been typed. KeyAdapter is an abstract class that implements the KeyListener interface with three empty methods (same concept as the MouseAdapter class). In this program the inner class extends KeyAdapter. The KeyEvent has a getkeycode method that tells us which key generated the event. Problem. When a key is pressed, a KeyEvent is generated then there is a short pause and then more KeyEvents are generated. For example, if the M key were pressed it would seem like: M (short delay) MMMMMMMMMMMMMM. In a game situation, we don t want that short delay. Also, we need to detect if two or more keys are simultaneously being pressed. The solution is to keep a list of which keys are currently being pressed. So there is an array of boolean values - if an element is true, then that key is currently being pressed. Every time there a key event is generated, the game is notified so that the player s position can be updated. IMPORTANT. When working with a key listener, you must understand the concept of focus. Imagine this situation. There are two text fields and you hit the A key. Where does the A appear? Answer: in the field that has the focus - indicated by a blinking cursor. Only one object can have the focus at any time. So in this focus we need to make sure the GamePanel gets the focus during game play. Here s how we accomplish this. Step one. In the GamePanel constructor we have this statement. setfocusable(true); This means that the panel can get the focus. Step two. When the Program is first displayed, the button will get the focus. However, when the button is clicked (to start the game), we want the focus to shift to the game panel - so that the code we wrote in that class (which handles key events) will actually react to key events. So we add this statement at the end of the actionperformed method. gp.requestfocusinwindow(); This shifts the focus to the game panel, gp. Note. Key Bindings are generally preferred to Key Listeners but since Key Listeners follow the same approach you ve seen with Action Listeners and Mouse Listeners, that s the approach I ve used here. If you are interested in learning about Key Bindings, go ahead and look up some tutorials. 10

AP CS Unit 12: Drawing and Mouse Events

AP CS Unit 12: Drawing and Mouse Events AP CS Unit 12: Drawing and Mouse Events A JPanel object can be used as a container for other objects. It can also be used as an object that we can draw on. The first example demonstrates how to do that.

More information

Advanced Java Unit 6: Review of Graphics and Events

Advanced Java Unit 6: Review of Graphics and Events Advanced Java Unit 6: Review of Graphics and Events This is a review of the basics of writing a java program that has a graphical interface. To keep things simple, all of the graphics programs will follow

More information

Method Of Key Event Key Listener must implement three methods, keypressed(), keyreleased() & keytyped(). 1) keypressed() : will run whenever a key is

Method Of Key Event Key Listener must implement three methods, keypressed(), keyreleased() & keytyped(). 1) keypressed() : will run whenever a key is INDEX Event Handling. Key Event. Methods Of Key Event. Example Of Key Event. Mouse Event. Method Of Mouse Event. Mouse Motion Listener. Example of Mouse Event. Event Handling One of the key concept in

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

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

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

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing. COSC User Interfaces Module 3 Sequential vs. Event-driven Programming Example Programs DemoLargestConsole.java DemoLargestGUI.java Demo programs will be available on the course web page. GUI Program Organization

More information

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline Sequential vs. Event-driven Programming Reacting to the user GUI Program Organization Let s digress briefly to examine the organization of our GUI programs We ll do this in stages, by examining three example

More information

public void mouseexited (MouseEvent e) setminute(getminute()+increment); 11.2 public void mouseclicked (MouseEvent e) int x = e.getx(), y = e.gety();

public void mouseexited (MouseEvent e) setminute(getminute()+increment); 11.2 public void mouseclicked (MouseEvent e) int x = e.getx(), y = e.gety(); 11 The Jav aawt Part I: Mouse Events 11.1 public void mouseentered (MouseEvent e) setminute(getminute()+increment); 53 public void mouseexited (MouseEvent e) setminute(getminute()+increment); 11.2 public

More information

CS 251 Intermediate Programming GUIs: Event Listeners

CS 251 Intermediate Programming GUIs: Event Listeners CS 251 Intermediate Programming GUIs: Event Listeners Brooke Chenoweth University of New Mexico Fall 2017 What is an Event Listener? A small class that implements a particular listener interface. Listener

More information

Programmierpraktikum

Programmierpraktikum Programmierpraktikum Claudius Gros, SS2012 Institut für theoretische Physik Goethe-University Frankfurt a.m. 1 of 18 17/01/13 11:46 Java Applets 2 of 18 17/01/13 11:46 Java applets embedding Java applications

More information

G51PRG: Introduction to Programming Second semester Applets and graphics

G51PRG: Introduction to Programming Second semester Applets and graphics G51PRG: Introduction to Programming Second semester Applets and graphics Natasha Alechina School of Computer Science & IT nza@cs.nott.ac.uk Previous two lectures AWT and Swing Creating components and putting

More information

The AWT Event Model 9

The AWT Event Model 9 The AWT Event Model 9 Course Map This module covers the event-based GUI user input mechanism. Getting Started The Java Programming Language Basics Identifiers, Keywords, and Types Expressions and Flow

More information

Graphical User Interfaces 2

Graphical User Interfaces 2 Graphical User Interfaces 2 CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011 Extending JFrame Dialog boxes Ge?ng user input Overview Displaying message or error Listening for

More information

(listener)... MouseListener, ActionLister. (adapter)... MouseAdapter, ActionAdapter. java.awt AWT Abstract Window Toolkit GUI

(listener)... MouseListener, ActionLister. (adapter)... MouseAdapter, ActionAdapter. java.awt AWT Abstract Window Toolkit GUI 51 6!! GUI(Graphical User Interface) java.awt javax.swing (component) GUI... (container) (listener)... MouseListener, ActionLister (adapter)... MouseAdapter, ActionAdapter 6.1 GUI(Graphics User Interface

More information

Graphical User Interfaces 2

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

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 36 November 30, 2018 Mushroom of Doom Model / View / Controller Chapter 31 Announcements Game Project Complete Code Due: Monday, December 10th NO LATE

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

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 34 April 13, 2017 Model / View / Controller Chapter 31 How is the Game Project going so far? 1. not started 2. got an idea 3. submitted design proposal

More information

Lecture 3: Java Graphics & Events

Lecture 3: Java Graphics & Events Lecture 3: Java Graphics & Events CS 62 Fall 2017 Kim Bruce & Alexandra Papoutsaki Text Input Scanner class Constructor: myscanner = new Scanner(System.in); can use file instead of System.in new Scanner(new

More information

Java Foundations John Lewis Peter DePasquale Joe Chase Third Edition

Java Foundations John Lewis Peter DePasquale Joe Chase Third Edition Java Foundations John Lewis Peter DePasquale Joe Chase Third Edition Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world Visit us on the

More information

Event Driven Programming

Event Driven Programming Event Driven Programming 1. Objectives... 2 2. Definitions... 2 3. Event-Driven Style of Programming... 2 4. Event Polling Model... 3 5. Java's Event Delegation Model... 5 6. How to Implement an Event

More information

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology:

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology: Inheritance 1 Inheritance One class inherits from another if it describes a specialized subset of objects Terminology: the class that inherits is called a child class or subclass the class that is inherited

More information

Lecture 5: Java Graphics

Lecture 5: Java Graphics Lecture 5: Java Graphics CS 62 Spring 2019 William Devanny & Alexandra Papoutsaki 1 New Unit Overview Graphical User Interfaces (GUI) Components, e.g., JButton, JTextField, JSlider, JChooser, Containers,

More information

CSIS 10A Assignment 14 SOLUTIONS

CSIS 10A Assignment 14 SOLUTIONS CSIS 10A Assignment 14 SOLUTIONS Read: Chapter 14 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

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation CSE 331 Software Design & Implementation Hal Perkins Spring 2017 GUI Event-Driven Programming 1 The plan User events and callbacks Event objects Event listeners Registering listeners to handle events Anonymous

More information

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011 GUI DYNAMICS Lecture July 26 CS2110 Summer 2011 GUI Statics and GUI Dynamics 2 Statics: what s drawn on the screen Components buttons, labels, lists, sliders, menus,... Containers: components that contain

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

OBJECT ORIENTED PROGRAMMING. Course 8 Loredana STANCIU Room B613

OBJECT ORIENTED PROGRAMMING. Course 8 Loredana STANCIU Room B613 OBJECT ORIENTED PROGRAMMING Course 8 Loredana STANCIU loredana.stanciu@upt.ro Room B613 Applets A program written in the Java programming language that can be included in an HTML page A special kind of

More information

1.00/1.001 Introduction to Computers and Engineering Problem Solving Spring Quiz 2

1.00/1.001 Introduction to Computers and Engineering Problem Solving Spring Quiz 2 1.00/1.001 Introduction to Computers and Engineering Problem Solving Spring 2010 - Quiz 2 Name: MIT Email: TA: Section: You have 80 minutes to complete this exam. For coding questions, you do not need

More information

Lecture 19 GUI Events

Lecture 19 GUI Events CSE 331 Software Design and Implementation Lecture 19 GUI Events The plan User events and callbacks Event objects Event listeners Registering listeners to handle events Anonymous inner classes Proper interaction

More information

Java for Interfaces and Networks (DT3010, HT10)

Java for Interfaces and Networks (DT3010, HT10) Java for Interfaces and Networks (DT3010, HT10) Mouse Events, Timers, Serialization Federico Pecora School of Science and Technology Örebro University federico.pecora@oru.se Federico Pecora Java for Interfaces

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

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created. + Inheritance + Inheritance Classes that we design in Java can be used to model some concept in our program. For example: Pokemon a = new Pokemon(); Pokemon b = new Pokemon() Sometimes we need to create

More information

Unit 7: Event driven programming

Unit 7: Event driven programming Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Unit 7: Event driven programming 1 1. Introduction 2.

More information

EXCEPTIONS & GUI. Errors are signals that things are beyond help. Review Session for. -Ankur Agarwal

EXCEPTIONS & GUI. Errors are signals that things are beyond help. Review Session for. -Ankur Agarwal Review Session for EXCEPTIONS & GUI -Ankur Agarwal An Exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. Errors are signals

More information

CS 201 Advanced Object-Oriented Programming Lab 10 - Recursion Due: April 21/22, 11:30 PM

CS 201 Advanced Object-Oriented Programming Lab 10 - Recursion Due: April 21/22, 11:30 PM CS 201 Advanced Object-Oriented Programming Lab 10 - Recursion Due: April 21/22, 11:30 PM Introduction to the Assignment In this assignment, you will get practice with recursion. There are three parts

More information

Lab 10: Inheritance (I)

Lab 10: Inheritance (I) CS2370.03 Java Programming Spring 2005 Dr. Zhizhang Shen Background Lab 10: Inheritance (I) In this lab, we will try to understand the concept of inheritance, and its relation to polymorphism, better;

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

CS 106A, Lecture 14 Events and Instance Variables

CS 106A, Lecture 14 Events and Instance Variables CS 106A, Lecture 14 Events and Instance Variables Reading: Art & Science of Java, Ch. 10.1-10.4 This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons

More information

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

CSE 331 Software Design and Implementation. Lecture 19 GUI Events CSE 331 Software Design and Implementation Lecture 19 GUI Events Leah Perlmutter / Summer 2018 Announcements Announcements Quiz 7 due Thursday 8/9 Homework 8 due Thursday 8/9 HW8 has a regression testing

More information

CS2110. GUIS: Listening to Events

CS2110. GUIS: Listening to Events CS2110. GUIS: Listening to Events Also anonymous classes Download the demo zip file from course website and look at the demos of GUI things: sliders, scroll bars, combobox listener, etc 1 mainbox boardbox

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

SAMPLE EXAM Exam 2 Computer Programming 230 Dr. St. John Lehman College City University of New York Thursday, 5 November 2009

SAMPLE EXAM Exam 2 Computer Programming 230 Dr. St. John Lehman College City University of New York Thursday, 5 November 2009 SAMPLE EXAM Exam 2 Computer Programming 230 Dr. St. John Lehman College City University of New York Thursday, 5 November 2009 NAME (Printed) NAME (Signed) E-mail Exam Rules Show all your work. Your grade

More information

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events Objectives Event Handling Animation Discussion of Roulette Assignment How easy/difficult to refactor for extensibility? Was it easier to add to your refactored code? Ø What would your refactored classes

More information

BASICS OF GRAPHICAL APPS

BASICS OF GRAPHICAL APPS CSC 2014 Java Bootcamp Lecture 7 GUI Design BASICS OF GRAPHICAL APPS 2 Graphical Applications So far we ve focused on command-line applications, which interact with the user using simple text prompts In

More information

2IS45 Programming

2IS45 Programming Course Website Assignment Goals 2IS45 Programming http://www.win.tue.nl/~wsinswan/programmeren_2is45/ Rectangles Learn to use existing Abstract Data Types based on their contract (class Rectangle in Rectangle.

More information

Object-oriented programming in Java (2)

Object-oriented programming in Java (2) Programming Languages Week 13 Object-oriented programming in Java (2) College of Information Science and Engineering Ritsumeikan University plan last week intro to Java advantages and disadvantages language

More information

Advanced Java Programming (17625) Event Handling. 20 Marks

Advanced Java Programming (17625) Event Handling. 20 Marks Advanced Java Programming (17625) Event Handling 20 Marks Specific Objectives To write event driven programs using the delegation event model. To write programs using adapter classes & the inner classes.

More information

Java GUI Design: the Basics

Java GUI Design: the Basics Java GUI Design: the Basics Daniel Brady July 25, 2014 What is a GUI? A GUI is a graphical user interface, of course. What is a graphical user interface? A graphical user interface is simply a visual way

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

GUI in Java TalentHome Solutions

GUI in Java TalentHome Solutions GUI in Java TalentHome Solutions AWT Stands for Abstract Window Toolkit API to develop GUI in java Has some predefined components Platform Dependent Heavy weight To use AWT, import java.awt.* Calculator

More information

Events. Dispatch, event-to-code binding. Review: Events Defined 1/17/2014. occurrence.

Events. Dispatch, event-to-code binding. Review: Events Defined 1/17/2014. occurrence. Events Dispatch, event-to-code binding Review: Events Defined 1. An observable occurrence, phenomenon, or an extraordinary occurrence. 2. A message to notify an application that something happened. Examples:

More information

CS 106A, Lecture 14 Events and Instance Variables

CS 106A, Lecture 14 Events and Instance Variables CS 106A, Lecture 14 Events and Instance Variables Reading: Art & Science of Java, Ch. 10.1-10.4 This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons

More information

Computer Science II - Test 2

Computer Science II - Test 2 Computer Science II - Test 2 Question 1. (15 points) The MouseListener interface requires methods for mouseclicked, mouseentered, mouseexited, mousepressed, and mousereleased. Java s MouseAdapter implements

More information

The init() Method. Browser Calling Applet Methods

The init() Method. Browser Calling Applet Methods Chapter 12 Applets and Advanced GUI The Applet Class The HTML Tag Passing Parameters to Applets Conversions Between Applications and Applets Running a Program as an Applet and as an Application

More information

GUI Event Handlers (Part I)

GUI Event Handlers (Part I) GUI Event Handlers (Part I) 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen University 1 Agenda General event

More information

Using Methods. Methods that handle events. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Using Methods. Methods that handle events. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics Using Methods Methods that handle events Produced by: Mairead Meagher Dr. Siobhán Drohan Department of Computing and Mathematics http://www.wit.ie/ Caveat The term function is used in Processing e.g. line(),

More information

GUI Event Handling 11. GUI Event Handling. Objectives. What is an Event? Hierarchical Model (JDK1.0) Delegation Model (JDK1.1)

GUI Event Handling 11. GUI Event Handling. Objectives. What is an Event? Hierarchical Model (JDK1.0) Delegation Model (JDK1.1) Objectives Write code to handle events that occur in a GUI 11 GUI Event Handling Describe the concept of adapter classes, including how and when to use them Determine the user action that originated the

More information

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4. 1 - What if the main method is declared as private? 1. The program does not compile 2. The program compiles but does not run 3. The program compiles and runs properly ( From Lectuer # 2) 4. The program

More information

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING. A Multithreaded program contains two or more parts that can run concurrently.

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING. A Multithreaded program contains two or more parts that can run concurrently. UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING 1. What are Threads? A thread is a single path of execution of code in a program. A Multithreaded program contains two or more parts that can run concurrently.

More information

Heavyweight with platform-specific widgets. AWT applications were limited to commonfunctionality that existed on all platforms.

Heavyweight with platform-specific widgets. AWT applications were limited to commonfunctionality that existed on all platforms. Java GUI Windows Events Drawing 1 Java GUI Toolkits Toolkit AWT Description Heavyweight with platform-specific widgets. AWT applications were limited to commonfunctionality that existed on all platforms.

More information

IT101. Graphical User Interface

IT101. Graphical User Interface IT101 Graphical User Interface Foundation Swing is a platform-independent set of Java classes used for user Graphical User Interface (GUI) programming. Abstract Window Toolkit (AWT) is an older Java GUI

More information

Windows and Events. created originally by Brian Bailey

Windows and Events. created originally by Brian Bailey Windows and Events created originally by Brian Bailey Announcements Review next time Midterm next Friday UI Architecture Applications UI Builders and Runtimes Frameworks Toolkits Windowing System Operating

More information

Which of the following syntax used to attach an input stream to console?

Which of the following syntax used to attach an input stream to console? Which of the following syntax used to attach an input stream to console? FileReader fr = new FileReader( input.txt ); FileReader fr = new FileReader(FileDescriptor.in); FileReader fr = new FileReader(FileDescriptor);

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

2. (True/False) All methods in an interface must be declared public.

2. (True/False) All methods in an interface must be declared public. Object and Classes 1. Create a class Rectangle that represents a rectangular region of the plane. A rectangle should be described using four integers: two represent the coordinates of the upper left corner

More information

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction CSC 160 LAB 8-1 DIGITAL PICTURE FRAME PROFESSOR GODFREY MUGANDA DEPARTMENT OF COMPUTER SCIENCE 1. Introduction Download and unzip the images folder from the course website. The folder contains 28 images

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

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

Computer Science 210: Data Structures. Intro to Java Graphics

Computer Science 210: Data Structures. Intro to Java Graphics Computer Science 210: Data Structures Intro to Java Graphics Summary Today GUIs in Java using Swing in-class: a Scribbler program READING: browse Java online Docs, Swing tutorials GUIs in Java Java comes

More information

PESIT Bangalore South Campus

PESIT Bangalore South Campus INTERNAL ASSESSMENT TEST II Date : 20-09-2016 Max Marks: 50 Subject & Code: JAVA & J2EE (10IS752) Section : A & B Name of faculty: Sreenath M V Time : 8.30-10.00 AM Note: Answer all five questions 1) a)

More information

CS2110. GUIS: Listening to Events

CS2110. GUIS: Listening to Events CS2110. GUIS: Listening to Events Lunch with instructors: Visit pinned Piazza post. A4 due tonight. Consider taking course S/U (if allowed) to relieve stress. Need a letter grade of C- or better to get

More information

Dr. Hikmat A. M. AbdelJaber

Dr. Hikmat A. M. AbdelJaber Dr. Hikmat A. M. AbdelJaber GUI are event driven (i.e. when user interacts with a GUI component, the interaction (event) derives the program to perform a task). Event: click button, type in text field,

More information

Handling Mouse and Keyboard Events

Handling Mouse and Keyboard Events Handling Mouse and Keyboard Events 605.481 1 Java Event Delegation Model EventListener handleevent(eventobject handleevent(eventobject e); e); EventListenerObject source.addlistener(this);

More information

THE UNIVERSITY OF AUCKLAND

THE UNIVERSITY OF AUCKLAND CompSci 101 with answers THE UNIVERSITY OF AUCKLAND FIRST SEMESTER, 2012 Campus: City COMPUTER SCIENCE Principles of Programming (Time Allowed: TWO hours) NOTE: You must answer all questions in this test.

More information

Graphical User Interface (GUI)

Graphical User Interface (GUI) Graphical User Interface (GUI) An example of Inheritance and Sub-Typing 1 Java GUI Portability Problem Java loves the idea that your code produces the same results on any machine The underlying hardware

More information

GUI 4.1 GUI GUI MouseTest.java import javax.swing.*; import java.awt.*; import java.awt.event.*; /* 1 */

GUI 4.1 GUI GUI MouseTest.java import javax.swing.*; import java.awt.*; import java.awt.event.*; /* 1 */ 25 4 GUI GUI GUI 4.1 4.1.1 MouseTest.java /* 1 */ public class MouseTest extends JApplet implements MouseListener /* 2 */ { int x=50, y=20; addmouselistener(this); /* 3 */ super.paint(g); /* 4 */ g.drawstring("hello

More information

CS2110. GUIS: Listening to Events Also anonymous classes versus Java 8 functions. Anonymous functions. Anonymous functions. Anonymous functions

CS2110. GUIS: Listening to Events Also anonymous classes versus Java 8 functions. Anonymous functions. Anonymous functions. Anonymous functions CS2110. GUIS: Listening to Events Also anonymous classes versus Java 8 functions Lunch with instructors: Visit Piazza pinned post to reserve a place Download demo zip file from course website, look at

More information

CS2110. GUIS: Listening to Events. Anonymous functions. Anonymous functions. Anonymous functions. Checkers.java. mainbox

CS2110. GUIS: Listening to Events. Anonymous functions. Anonymous functions. Anonymous functions. Checkers.java. mainbox CS2110. GUIS: Listening to Events Lunch with instructors: Visit pinned Piazza post. A4 due tonight. Consider taking course S/U (if allowed) to relieve stress. Need a letter grade of C- or better to get

More information

ANSWER KEY Exam 2 Computer Programming 230 Dr. St. John Lehman College City University of New York Thursday, 5 November 2009

ANSWER KEY Exam 2 Computer Programming 230 Dr. St. John Lehman College City University of New York Thursday, 5 November 2009 ANSWER KEY Exam 2 Computer Programming 230 Dr. St. John Lehman College City University of New York Thursday, 5 November 2009 1. True or False: (a) T In Alice, there is an event that is processed as long

More information

CS 201 Advanced Object-Oriented Programming Lab 3, Asteroids Part 1 Due: February 17/18, 11:30 PM

CS 201 Advanced Object-Oriented Programming Lab 3, Asteroids Part 1 Due: February 17/18, 11:30 PM CS 201 Advanced Object-Oriented Programming Lab 3, Asteroids Part 1 Due: February 17/18, 11:30 PM Objectives to gain experience using inheritance Introduction to the Assignment This is the first of a 2-part

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

I/O Framework and Case Study. CS151 Chris Pollett Nov. 2, 2005.

I/O Framework and Case Study. CS151 Chris Pollett Nov. 2, 2005. I/O Framework and Case Study CS151 Chris Pollett Nov. 2, 2005. Outline Character Streams Random Access Files Design case study Planning Iterations Character Streams Java internally represents strings as

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

Graphical User Interface (GUI)

Graphical User Interface (GUI) Graphical User Interface (GUI) An example of Inheritance and Sub-Typing 1 Java GUI Portability Problem Java loves the idea that your code produces the same results on any machine The underlying hardware

More information

Event Binding. Different Approaches Global Hooks. 2.5 Event Binding 1

Event Binding. Different Approaches Global Hooks. 2.5 Event Binding 1 Event Binding Different Approaches Global Hooks 2.5 Event Binding 1 Event Dispatch vs. Event Binddling Event Dispatch phase addresses: - Which window receives an event? - Which widget processes it? Positional

More information

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features: Lecture 28 Exceptions and Inner Classes Goals We are going to talk in more detail about two advanced Java features: Exceptions supply Java s error handling mechanism. Inner classes ease the overhead of

More information

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2,

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2, Java Mouse Actions C&G criteria: 5.2.1, 5.4.1, 5.4.2, 5.6.2. The events so far have depended on creating Objects and detecting when they receive the event. The position of the mouse on the screen can also

More information

OOP Assignment V. For example, the scrolling text (moving banner) problem without a thread looks like:

OOP Assignment V. For example, the scrolling text (moving banner) problem without a thread looks like: OOP Assignment V If we don t use multithreading, or a timer, and update the contents of the applet continuously by calling the repaint() method, the processor has to update frames at a blinding rate. Too

More information

Come & Join Us at VUSTUDENTS.net

Come & Join Us at VUSTUDENTS.net Come & Join Us at VUSTUDENTS.net For Assignment Solution, GDB, Online Quizzes, Helping Study material, Past Solved Papers, Solved MCQs, Current Papers, E-Books & more. Go to http://www.vustudents.net and

More information

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1 Block I Unit 2 Basic Constructs in Java M301 Block I, unit 2 1 Developing a Simple Java Program Objectives: Create a simple object using a constructor. Create and display a window frame. Paint a message

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

Programming via Java User interaction

Programming via Java User interaction Programming via Java User interaction We'll now consider programs to get information from the user via the mouse, as supported by the acm.graphics package. Along the way, we'll learn about two more general

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

COSC 123 Computer Creativity. Graphics and Events. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity. Graphics and Events. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity Graphics and Events Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) Draw shapes, text in various fonts, and colors. 2) Build

More information

Events Chris Piech CS106A, Stanford University. Piech, CS106A, Stanford University

Events Chris Piech CS106A, Stanford University. Piech, CS106A, Stanford University Events Chris Piech CS106A, Stanford University Catch Me If You Can We ve Gotten Ahead of Ourselves Source: The Hobbit Start at the Beginning Source: The Hobbit Learning Goals 1. Write a program that can

More information

Twin A Design Pattern for Modeling Multiple Inheritance

Twin A Design Pattern for Modeling Multiple Inheritance Twin A Design Pattern for Modeling Multiple Inheritance Hanspeter Mössenböck University of Linz, Institute of Practical Computer Science, A-4040 Linz moessenboeck@ssw.uni-linz.ac.at Abstract. We introduce

More information

Class 27: Nested Classes and an Introduction to Trees

Class 27: Nested Classes and an Introduction to Trees Introduction to Computation and Problem Solving Class 27: Nested Classes and an Introduction to Trees Prof. Steven R. Lerman and Dr. V. Judson Harward Goals To explain in more detail the different types

More information