KeyListener and Keyboard Events Another type of listener listens for keyboard entry – the KeyListener which generates KeyEvents –to implement KeyListener,

Slides:



Advertisements
Similar presentations
In this tutorial, we are going to create: A race car that the user can control with the arrow keys for direction and speed. A simulated road with a striped.
Advertisements

2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Mouse Listeners We continue our examination of GUIs by looking at how to interact with the mouse –Just as Java creates Events when the user interacts with.
Graphics You draw on a Graphics object The Graphics object cannot directly be created by your code, instead one is generated when the method paintComponent.
Event-Driven Programming You might have realized in creating a GUI and clicking on the JButtons that nothing happens Clicking on a JButton causes the JVM.
COMPUTER PROGRAMMING I Essential Standard 5.02 Understand Breakpoint, Watch Window, and Try And Catch to Find Errors.
Code Club Session 3 Shark Eats Fish. Picture of finished product here.
Jan Event Handling -1.1 Yangjun Chen Dept. Business Computing University of Winnipeg.
Mrs. Chapman. Tabs (Block Categories) Commands Available to use Script Area where you type your code Sprite Stage All sprites in this project.
Mouse Events and Keyboard Events
Cosc 5/4730 Game Design. A short game design primer. A game or animation is built on an animation loop. – Instance variables of “objects” are updated.
IAT 800 Lab 1: Loops, Animation, and Simple User Interaction.
Event Handling Events and Listeners Timers and Animation.
1 Flash Actionscript Animation. 2 Introduction to Sprites We will now look at implementing Sprites in Flash. We should know enough after this to create.
Event Handling. In this class we will cover: Keyboard Events Mouse Events Focus Events Action Interface Multicasting.
ABC’s of PowerPoint (Office 2007) Part 1: Basic Vocabulary Part 2: Cursors Part 3: Insert Your Text Part 4: Insert Your Pictures Part 5: Basic Tools &
Animation To animate our programs, that is, to have real time interactions where objects move on the screen, we want to call repaint( ) every few milliseconds.
Mr. Wortzman. Tabs (Block Categories) Available Blocks Script Area Sprite Stage All sprites in this project.
Animation Most games have moving components, how do we make things move? –We will track the location of an object using an x,y coordinate –We will draw.
GAME:IT Junior Bouncing Ball Objectives: Create Sprites Create Sounds Create Objects Create Room Program simple game.
Mouse Events. Handling Mouse Events Java provides two listener interfaces to handle mouse events: MouseListener;  MouseListener;  MouseMotionListener.
GAME:IT Bouncing Ball Objectives: Create Sprites Create Sounds Create Objects Create Room Program simple game.
Welcome to CIS 083 ! Events CIS 068.
Introducing Graphics There are generally two types of graphics facilities in Java –Drawing –GUIs We concentrate on drawing here We will draw on a Graphics.
Visual Basic .NET BASICS
KeyListener and Keyboard Events Just as we can implement listeners to handle mouse events, we can do the same for keyboard events (keypresses) –to implement.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Event Driven Programming, The.
(c) University of Washington07b-1 CSC 143 Java Events, Event Handlers, and Threads Reading: Ch. 17.
7/3/00SEM107- © Kamin & ReddyClass 11 - Events - 1 Class 11 - Events r A couple of odds & ends m Component sizes  switch statement r Event types r Catching.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
Copyright © 2002, Systems and Computer Engineering, Carleton University b-Gui2.ppt * Object-Oriented Software Development Part 18-b Building.
MSc Workshop - © S. Kamin, U.Reddy Lect 4 - Events - 1 Lecture 4 – Event Handling r Painting r Event types r Catching different event types.
CSE 219 Computer Science III Image Manipulation. HW 1 Has been posted on Blackboard Making a Game of Life with limited.
Game Maker Terminology
 Definition: An event is an object thrown in response to a user of programmatic action  Definition: A listener is a series of methods that executes in.
1 ball, 2 ball, red ball, blue ball By Melissa Dalis Professor Susan Rodger Duke University June 2011.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
UID – Event Handling and Listeners Boriana Koleva
CIS 3.5 Lecture 2.2 More programming with "Processing"
Animation To animate our programs, that is, to have real time interactions where objects move on the screen, we want to call repaint( ) every few milliseconds.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Event-Driven Programming 1.
Agenda Introduction. Event Model. Creating GUI Application. Event Examples.
Index Event Handling Events Event Source Event Listener Event Classes Action Event Class Adjustment event Class Event Source Event Listener Interface Using.
Java Dynamic Graphics.
COSC 4126 User Interaction User Interaction capturing and responding to input events.
Mouse Listeners Moving the mouse will also generate events like the Timer –To have your program respond, you must implement either or both of MouseListener.
Arrays and Logic Let’s generate 6 lotto numbers using a loop and the random number generator – but we don’t want to duplicate any numbers – how do we know.
(c) by Elizabeth Sugar Boese.1 Chapter 6 Events - Lecture Slides.
SCRIPT PROGRAMMING WITH FLASH Introductory Level 1.
More GUI Components We finish off our examination of GUI components today by looking at a few that we haven’t seen yet –we start off with the JSlider the.
Creating User Interfaces Event-Driven Programming.
KeyListener and Keyboard Events Just as we can implement listeners to handle mouse events, we can do the same for keyboard events (keypresses) –to implement.
Jaeki Song ISQS6337 JAVA Lecture 10 Applets. Jaeki Song ISQS6337 JAVA Applet Applets run within the Web browser environment –Applets bring dynamic interaction.
Tank Game Part 2 of 6. Firing Shells Coming up… Players Scores Large Explosions Small Explosions Damage Health Bars Parent Shell Destructible Walls Reappear.
GUI Tutorial Day 4. More GUI action  adding a Mouse Listener  SimpleDots  Simple mouse listener  Draw an oval where the mouse is clicked  Box example.
Creating a Simple Game in Scratch Barb Ericson Georgia Tech May 2009.
Mouse, Keyboard, Sounds, and Images JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
Game Maker Tutorials Introduction Clickball IntroductionClickball Where is it? Shooting Where is it?Shooting.
Scratch Programming Cards
Keyboard Input.
Multimedia in Java Multimedia combines graphics, animation and sound
Programming in Java Event Handling
Miscellaneous Topics #6: Polygons GUI Components and Event Handlers
Project Snake. Project Snake Snake For this project, we’re going to make Snake This includes Making the overall game logic (using a 2D array) Handling.
More programming with "Processing"
Events, Event Handlers, and Threads
User Input Keyboard input.
Presentation transcript:

KeyListener and Keyboard Events Another type of listener listens for keyboard entry – the KeyListener which generates KeyEvents –to implement KeyListener, you must implement three methods: keyPressed, keyReleased and keyTyped all three methods receive a KeyEvent we typically will only implement one of these, probably keyPressed (the other two must be defined but their bodies can be { }) the KeyEvent includes information about which key was pressed getKeyChar – method to get the character pressed (e.g., ‘a’, ‘d’, ‘ ’) – cannot be used for some keys like the arrow keys or enter key getKeyCode – method to get a constant that defines the key, we compare it against constants like KeyEvent.VK_LEFT or KeyEvent.VK_ENTER (left arrow, enter key) –the JPanel which is to watch for keyboard entry must also be focused on the keyboard using panel.setFocusable(true);

Using Keyboard Input What will keyboard entry be used for? –Select keys will control movement in a game move around a maze move the “sights” of a gun or a missile launcher move a paddle (for instance in Pong or Breakout) –We need to designate certain keys for use –We will then place our logic to move the item in one of the keyListener methods such as keyPressed –For instance, if a key is typed, in keyPressed we get the key’s character and see if it was ‘a’ to move left or ‘d’ to move right and then adjust an x coordinate –We might then call repaint(); if we do not have a Timer, otherwise, the Timer will call actionPerformed which will call repaint();

Moving Objects Let’s assume we have an object at coordinates x, y –We define a set of keys for data movement for instance, the arrow keys or a, w, d, x for left, up, right, down –In keyPressed (or keyReleased or keyTyped), we test for the character and make the proper movement in x or y if(e.getKeyChar( ) = = ‘a’) x--; else if(e.getKeyChar( ) = = ‘w’) y--; else if(e.getKeyChar( ) = = ‘d’) x++; else if(e.getKeyChar( ) = = ‘x’) y++; –Notice that we are not using an else statement here because this method is called whenever ANY key is pressed, so the statement else y++; would move the object down whenever any key which is not ‘a’, ‘w’ or ‘d’ is pressed –We follow the above code with repaint( );

Borders Imagine our drawing area is 500x500 –We start at x=250,y=250 For each of a, w, d, x, we move the object accordingly –What happens if the user presses x 250 times? x will be 500, can we draw something there? –Yes, but we will not see it When we move the object in the keyPressed method, we want to make sure it does not sound the object beyond a border We need to add code like this: –if(x>480) x=480; to force the object to “stop” moving –or if(x>480) x=20; to “wrap-around” to the other side of the screen

Etch a Sketch Program Let’s use the keyboard input to control the drawing of short lines like the old etch a sketch game –This program requires a Graphics object to draw on and a KeyListener –We use a single JPanel (we do not need a second JPanel with GUI components as we do not need them for this program), we will call this JPanel ESPanel –ESPanel requires the current x,y coordinate of the line being drawn and the direction we want to extend the line (up, down, left, right) –The direction will be controlled by the keyboard by using the up, down, left or right arrows –The enter key will be used to “erase” the image, for this we will set a boolean, setClear, to true upon pressing enter and in paintComponent, if true, we will do super.paintComponent(g) to erase the Graphics image

Methods public void keyPressed(KeyEvent e) { if(e.getKeyCode()==KeyEvent.VK_LEFT) direction = 0; else if(e.getKeyCode()==KeyEvent.VK_UP) direction = 1; else if(e.getKeyCode()==KeyEvent.VK_RIGHT) direction = 2; else if(e.getKeyCode()==KeyEvent.VK_DOWN) direction = 3; else if(e.getKeyCode()==KeyEvent.VK_ENTER setClear = true; repaint( ); } public void paintComponent(Graphics g) { if(setClear) { boolean super.paintComponent(g); setClear = false; } else { g.setColor(Color.black); if(direction==0) {g.drawLine(x, y, x-2, y); x-=2; if (x < 10) x = 10;} else if(direction==1) { g.drawLine(x, y, x, y-2); y-=2; if (y < 10) y = 10; } else if(direction== 2) { g.drawLine(x, y, x+2, y); x+=2; if (x > 290) x = 290;} else if(direction==3) { g.drawLine(x, y, x, y+2); y+=2; if (y > 290) y = 290; } }

Typewriter Program Another example is to allow the user to “type” on the Graphics area while the mouse can be used to reposition the cursor –We use x,y for the coordinate of the cursor –A KeyListener is used to receive any key entries –In paintComponent, g.drawString outputs the latest input character at the x, y coordinate and then the x coordinate is moved to the right –If the mouse is clicked, we retrieve its x, y coordinate and reposition the cursor there –We do not need a Timer, the only change to the Graphics area is when the user types something or uses the mouse, so both the keyPressed (or keyTyped) and mousePressed (or mouseClicked) methods call repaint The class needs these variables –x, y for the coordinates of where the next character should appear –c the latest character obtained by a KeyEvent We need to implement MouseListener and KeyListener on one JPanel

Methods public void mouseClicked(MouseEvent e) { int tempX = e.getX(); int tempY = e.getY(); if(tempX > 10 && tempX 10 && tempY < 290) { x = tempX; y = tempY; } public void keyTyped(KeyEvent e) { key = e.getKeyChar(); repaint(); } public void paintComponent(Graphics g) { String temp = "" + key; g.setColor(Color,black); drawString(temp, x, y); x+=7; if(x>290) { x=10; y+=12; } We can also show the cursor by drawing a small triangle just below x, y g.setColor(Color.red); g.drawLine(x-1,y+1,x,y); g.drawLine(x,y,x+1,y+1); g.drawLine(x-1,y+1,x+1,y+1);

Maze Today we have two projects, one is to implement a maze –The maze will be drawn via paintComponent We use a 2-D array of int values to indicate the path (0) versus a wall (1) versus the exit (2) For instance: – – – – – – –The user moves around the maze using keyboard input Aside from making sure the user doesn’t move off the screen (out of the array), we have to make sure the user doesn’t move into a wall

More Aside from the array, we need the current location of the user (x, y) When the user presses a key, we have to verify that the move is available: –Moving in that direction does not move the user out of the maze (beyond a border) –Moving in that direction does not take the user into a wall –If the move passes both of those checks, then we change the x or y coordinate appropriate and call repaint, for instance, to move left, we use ‘a’ if(key==‘a’&&x>1&&maze[x-1][y]==0) x--; this says: “if the key is ‘a’, and the user is not on the leftmost border, and the square being moved into is 0 (an opening) then move to that square

Maze Program This program will need a JPanel for drawing and keyboard interaction –the JPanel class will implement KeyListener requiring keyTyped (or keyPressed) be implemented –the JPanel class will contain a paintComponent method to draw the maze (use maybe a 10x10 fillRect for each array location where the color is set by the array value, 0 might be white, 1 might be black and 2 might be red) –store x, y – the current location where x, y starts off as the “entry” point of the maze We also have to set the JPanel to be focusable – we do this in main –MazePanel panel = new MazePanel( ); –panel.setFocusable(true); –frame.add(panel);

Missile Launcher Game Another project is to finish the missile launcher –We have a missile launcher at the bottom of the screen which can move left/right –Press left arrow to start it moving left, right arrow for right, space bar to launch a missile, and enter to stop it moving –If we have 1 missile only, then we have to wait for the missile to go off the screen before launching another – or we can have an array of missiles (see the next slide) –Next, add an object to shoot at which can fly randomly on the screen (use the Spaceship1 or Spaceship2 code) –Finally, determine if your missile hits the spaceship and if so, add 1 to your score and reset the spaceship to randomly be somewhere else

1 Missile vs Array of Missiles 1 missile requires its mx, my coordinate –it will move up at a constant speed, so at each Timer event, we might do my=my-2; –its movement laterally might be 0 (its mx coordinate stays the same once launched) or it might take on the same change in x that the missile launcher has (that is, mdx=dx) –we have to keep track of the missile so that once missile hits a border (left, right, top), we reset mx to -1 so that we don’t draw it any more and can launch a new missile For any number of missiles, make mx and my int arrays and add a variable called numMissiles which indicates which missile was the last to be launched Use a for loop and an if statement to move and draw the missiles: –for(int i=0;i<numMissiles;i++) if(mx[i]!=-1) {…}