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.

Slides:



Advertisements
Similar presentations
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.
Advertisements

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.
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
Bar Graph Design. Left-side/Right-side mechanical processing creative, abstract reasoning.
CompSci Today’s topics Java Recursion in Graphics Writing a Class Simple Animation Upcoming Simulation Reading Great Ideas, Chapters 5.
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.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Jan Event Handling -1.1 Yangjun Chen Dept. Business Computing University of Winnipeg.
Mouse Events and Keyboard Events
Event Handling Events and Listeners Timers and Animation.
© The McGraw-Hill Companies, 2006 Chapter 18 Advanced graphics programming.
Chapter Day 10. © 2007 Pearson Addison-Wesley. All rights reserved4-2 Agenda Day 10 Questions from last Class?? Problem set 2 posted  10 programs from.
Graphical User Interfaces Allow for interaction with –Buttons –Menus –Text Fields Two Java Libraries to assist in GUI Programming –AWT –Swing.
Event Handling. In this class we will cover: Keyboard Events Mouse Events Focus Events Action Interface Multicasting.
Chapter Day 9. © 2007 Pearson Addison-Wesley. All rights reserved4-2 Agenda Day 8 Questions from last Class?? Problem set 2 posted  10 programs from.
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.
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.
Introduction to GUI Java offers a great number of pre-defined classes to support the development of graphical user interfaces –These are broken down into.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
CIS 068 Welcome to CIS 083 ! Introduction to GUIs: JAVA Swing.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
CSE 219 Computer Science III Images. HW1 Has been posted on Blackboard Making a Game of Life with limited options.
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.
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Adding Graphics to a Frame Application Applets: Can generate drawings by overriding paint Frame: Do not draw directly on a frame. Draw graphics on a JPanel.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Event Driven Programming, The.
KeyListener and Keyboard Events Another type of listener listens for keyboard entry – the KeyListener which generates KeyEvents –to implement KeyListener,
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
Java Event Handling CSIS 3701: Advanced Object Oriented Programming.
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.
Session 10 CannonGame and Event-driven Programming.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
 2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(1/20) More Swing Widgets and Listeners Joel Adams and Jeremy Frens Calvin.
MSc Workshop - © S. Kamin, U.Reddy Lect 4 - Events - 1 Lecture 4 – Event Handling r Painting r Event types r Catching different event types.
Alice in Action with Java Chapter 14 Events and GUIs.
12/5/00SEM107, Kamin & ReddyReview - 34 Events Event types Catching different event types Getting information from components and events Distinguishing.
 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.
Concurrent Programming and Threads Threads Blocking a User Interface.
Lec 16 Adding Mouse and KeyEvent handlers to an Applet Class.
EVENTS Wiring together objects, code, and actions.
Java Classes, Objects, and Events: A Preview JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria.
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action.
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.
Agenda Introduction. Event Model. Creating GUI Application. Event Examples.
Practical Session 10: Animation. Animation kinds There are three basic kinds of animation: 1. Moving object 2. Changing pictures 3. Combination of 1 and.
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.
Review_6 AWT, Swing, ActionListener, and Graphics.
Applets Java code is compiled into byte code instead of machine language –Languages like C, C++, Pascal and others are compiled into machine language so.
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.
Ajmer Singh PGT(IP) JAVA IDE Programming - I. Ajmer Singh PGT(IP) GUI (Graphical User Interface) It is an interface that uses a graphic entities along.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
1/18H212Mouse and Timer Events H212 Introduction to Software Systems Honors Lecture #16: Mouse and Timer Events October 26, 2015.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Event Handling CS 21a: Introduction to Computing I First Semester,
Jaeki Song ISQS6337 JAVA Lecture 10 Applets. Jaeki Song ISQS6337 JAVA Applet Applets run within the Web browser environment –Applets bring dynamic interaction.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Mouse, Keyboard, Sounds, and Images JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
Modular Event Handling
GUIs and Events Rick Mercer.
GUI Programming using Java - Key Events
Multimedia in Java Multimedia combines graphics, animation and sound
Miscellaneous Topics #6: Polygons GUI Components and Event Handlers
Event Handling CS 21a: Introduction to Computing I
Events, Event Handlers, and Threads
Presentation transcript:

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 KeyListener, you must implement three methods: keyPressed, keyReleased and keyTyped all three methods receive a KeyEvent to determine which key was pressed you can pass the event the message getKeyChar( ) –in order for your Java program to watch for key presses, you also have to get your container (probably a JPanel) to watch the keyboard, this is done by saying panel.setFocusable(true); We will look at code that uses KeyListener to implement a “typewriter” and an “etch-a-sketch” type program –you might also use KeyListener for a computer game where the user uses the keyboard to control movement in the game

Building a Key-controlled Game Let’s build a game where you use the keys to control an object on the screen (say an image) –We will use the keys ‘a’, ‘w’, ‘d’, ‘x’ to go left, up, right, down and ‘s’ to stop the motion –The game will require a Graphics JPanel which implements ActionListener for the Timer and KeyListener for keyboard interaction –In the constructor, instantiate the timer (t=new Timer(10, this); and start the timer (t.start( );) and add the keyboard listener (addKeyListener(this);) –In the main method, add a keyboard focus instruction panel.setFocusable(true); Now we need to implement actionPerformed, keyPressed, keyTyped, keyReleased and paintComponent

Continued For actionPerformed, move the object on the screen (x+=dx; y+=dy) and check to see if the object has hit a boundary, and then call repaint(); –In paintComponent, do super.paintComponent(g) and then redraw the object on the screen For keyPressed, do the following: –char c=e.getKeyChar( ); –if(e==‘a’) dx--; –else if(e==‘w’) dy--; –… we will leave keyTyped and keyReleased blank (that is, implement them as { })

JSlider Another GUI component is the Jslider –the JSlider is a bar with a mouse-movable controller –you slide the controller from left to right or right to left We will use the JSlider to control things like –speed (as you move it to the right, the Timer’s delay can be shortened, thus speeding up your game –colors, we will see how to do this in a couple of slides where 3 JSliders control the background color We create a JSlider by initializing it with 3 values –the minimum value (left-hand side or lower limit), maximum value (right-hand side or upper limit), and initial value –JSlider redSlider = new JSlider(0, 255, 0);

More on JSliders You can also create vertical sliders by adding JSlider.VERTICAL at the beginning of the parameters in the instantiation –JSlider slide = new JSlider(JSlider.VERTICAL, 0, 100, 50); // initial value is 50 To use a JSlider, you need to assign the JSlider a listener (just like you did with a JButton and other GUI components) –the listener needs to implement ChangeListener, so our class’ definition that contains a JSlider will look like this: –public static class JSliderExample extends JPanel implements ChangeListener To implement a ChangeListener, you need to implement the method stateChanged, which will receive a ChangeEvent ChangeEvent has a method getValue( ) which will return the current position of the JSlider

JSlider Example public static class SliderPanel extends JPanel implements ChangeListener { private JSlider redSlider, greenSlider, blueSlider; private int red, green, blue; public SliderPanel() { red = green = blue = 0; redSlider = new JSlider(0, 255, 0); greenSlider = new JSlider(0, 255, 0); blueSlider = new JSlider(0, 255, 0); redSlider.addChangeListener(this); greenSlider.addChangeListener(this); blueSlider.addChangeListener(this); JPanel sliderPanel = new JPanel(new GridLayout(3, 1)); sliderPanel.add(redSlider); sliderPanel.add(greenSlider); sliderPanel.add(blueSlider); add(sliderPanel); // Add the panels to the main panel. }

Continued public void stateChanged(ChangeEvent e) { if(e.getSource()==redSlider) red = redSlider.getValue(); else if(e.getSource()==greenSlider) green = greenSlider.getValue(); else if(e.getSource()==blueSlider) blue = blueSlider.getValue(); repaint(); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(new Color(red, green, blue)); g.fillRect(0, 0, getWidth(), getHeight()); } Notice that we use e.getSource( ) to identify the source of the Change Event (which JSlider was used?)

JSpinners A JSpinner is used to control a numeric selection –it contains a textfield that has a number, and two arrows to increase or decrease the number –the user can select a value by clicking the arrows To create a JSpinner, you have to do two things –SpinnerNumberModel mod = new SpinnerNumberModel(init, min, max, step); –JSpinner spin = new JSpinner(mod); –the Model is needed to first define the range of values for the spinner –init is the initial value, min is the smallest value in the range, max is the largest value in the range, and step is the number of values that the value goes up or down by with every arrow press For instance, we might use 3 JSpinners to allow the user to change the color instead of (or addition to) the JSliders –in which case, we might define 3 JSpinners as: SpinnerNumberModel mod = new SpinnerNumberModel(0, 0, 255, 1); JSpinner redSpinner = new JSpinner(mod); JSpinner greenSpinner = new JSpinner(mod); JSpinner blueSpinner = new JSpinner(mod);

More on JSpinners The JSpinner will also use a ChangeListener like the JSlider which means that you must add implements ChangeListener to the class, add the listener to each JSpinner, and implement a stateChanged event –the ChangeEvent passed to the stateChanged method will include both a value and the source, just like the JSlider You can also create spinners that show lists of strings: String[] classes = {“Freshman”, “Sophmore”, “Junior”, “Senior”, “Graduate”}; –SpinnerModel model = new SpinnerListModel(classes); –JSpinner spinner = new JSpinner(model); Notice in this case, the model is a List model, not a number model –notice that you do not provide an initial value with the SpinnerListModel, instead To get the value from a Spinner, you have to be careful because spinner.getValue( ) returns an Object, so if the values are numbers, use: x = Integer.parseInt(“” + spinner.getValue( ));