CS2110. GUIS: Listening to Events

Slides:



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

CS18000: Problem Solving and Object-Oriented Programming.
Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
Event Handling Events and Listeners Timers and Animation.
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
CS/ENGRD 2110 FALL 2014 Lecture 15: Graphical User Interfaces (GUIs): Listening to events 1.
1 Listening to events on GUIs Sec contains this material. Corresponding lectures on ProgramLive CD is a better way to learn the material. Top finalists.
Welcome to CIS 083 ! Events CIS 068.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
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,
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
CS 11 java track: lecture 4 This week: arrays interfaces listener classes inner classes GUI callbacks.
Java GUI’s are event driven, meaning they generate events when the user interacts with the program. Typical events are moving the mouse, clicking a mouse.
CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.
SD2071 Games Programming Abstraction, inheritance and interfaces Exceptions Two dimensional arrays Java collections framework Files Aaron Kans.
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.
Previous programs used a JLabel for OUTPUT. Another Swing component that can be used for both user input and output is the JTextfield. Suppose we want.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
CS2110. GUIS: Listening to Events 1 Download the demo zip file from course website and look at the demos of GUI things: sliders, scroll bars, combobox.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
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.
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
Layout Managers Arranges and lays out the GUI components on a container.
For (int i = 1; i
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
CS2110. GUIS: Listening to Events Also Example of Stepwise Refinement and Anonymous classes 1 Download the demo zip file from course website and look at.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
1 Lecture 25 Listening to buttons and mice Quotes by Tony Hoare There are two ways of constructing a software design: (1) make it so simple that there.
Review_6 AWT, Swing, ActionListener, and Graphics.
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 Listening to events on GUIs Sec contains this material. Corresponding lectures on ProgramLive CD is a better way to learn the material. Why men.
What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
UQC117S2 Graphics Programming Lecture 2 Event Handling Program as a sequence of instructions Event -driven program Need to detect the event and carry out.
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.
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.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
1 12. Listening to events. Inner and anonymous classes Why men think “computer” should be a feminine word 1. No one but their creator understands their.
Dept. of CSIE, National University of Tainan 10/21/2012 Responding to User Input.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
10/20/2005week71 Graphics, mouse and mouse motion events, KeyEvent Agenda Classes in AWT for graphics Example java programs –Graphics –Mouse events –Mouse.
Review Session for EXCEPTIONS & GUI -Ankur Agarwal 1.
CS2110. GUIS: Listening to Events
GUIs and Events Rick Mercer.
CSC 205 Programming II Lecture 5 AWT - I.
Events and Event Handling
Chapter 14 Event-Driven Programming
CompSci 230 S Programming Techniques
Final exam: Period B: Thursday, 13 May, 9:00-11:30AM, Barton East
A First Look at GUI Applications
CS2110. GUIS: Listening to Events
Computer Science 209 Graphics and GUIs.
Listening to events on GUIs
Programming in Java Event Handling
Ellen Walker Hiram College
GUI Programming III: Events
Event-driven programming for GUI
CS2110. GUIS: Listening to Events
Interfaces – handling very “general” operations cleanly (April 21)
CS2110. GUIS: Listening to Events
Events, Event Handlers, and Threads
Lecture 21. Listening to events on a GUI (and development of a loop)
CS2110. GUIS: Listening to Events
12. Listening to events. Inner and anonymous classes
Presentation transcript:

CS2110. GUIS: Listening to Events Lunch with instructors: Visit Piazza pinned post. Prelim 1 regrade deadline: Friday, 23 March midnight. 21 March: last day to drop or change grade to S/U Consider taking course S/U (if allowed) to relieve stress. Need a letter grade of C- or better to get an S. Right now: 13 AUDIT, 45 S/U A4 submissions: this Thursday. this Friday A4 deadline for late submissions remains Sunday Download demo zip file from course website, look at demos of GUI things: sliders, scroll bars, listening to events, etc. We’ll update it after today’s lecture.

Checkers.java mainBox boardBox infoBox JButton JLabel row … Square … Square Square … Square Layout Manager for Checkers game has to process a tree pack(): Traverse the tree, determining the space required for each component and its position in the window boardBox: vertical Box row: horizontal Box Square: Canvas or JPanel infoBox: vertical Box

Listening to events: mouse click, mouse movement into or out of a window, a keystroke, etc. • An event is a mouse click, a mouse movement into or out of a window, a keystroke, etc. • To be able to “listen to” a kind of event, you have to: Have some class C implement an interface IN that is connected with the event. In class C, override methods required by interface IN; these methods are generally called when the event happens. Register an object of class C as a listener for the event. That object’s methods will be called when event happens. We show you how to do this for clicks on buttons, clicks on components, and keystrokes.

Anonymous functions You know about interface Comparable. public interface Comparable<T> { /** Return neg, 0 or pos …*/ int compareTo(T ob); } public abstract class Shape implements Comparable { … /** Return the area of this shape */ public abstract double area() ; /** Return neg, 0, or pos … */ public int compareTo(Shape ob) { } In some class: Shape[] s= …; … Arrays.sort(s); Use an anonymous function to make this easier!

Anonymous functions You used anonymous functions in A1 to test whether some statement threw an exception. The second argument to assertThrows is an anonymous function with no parameters. Its body calls g.setAdvisor. assertThrows(AssertionError.class, () -> {g.setAdvisor1(null);});

Anonymous functions Here is a function: public int f(Person b, Person c) { return b.age – c.age; } public class Person { public String name; public int age; … } Written as an anonymous function (Person b, Person c) -> b.age – c.age Anonymous because it does not have a name. Don’t need keyword return. Can put braces around the body if it is more than a single expression. Depending on where it is written, don’t need to put in types of b, c if the types can be inferred.

Anonymous functions In some class: Person p[]= new Person[10]; … code to put in 10 Persons … public class Person { public String name; public int age; … } /** Sort p on age Arrays.sort(p, (Person b, Person c) -> b.age – c.age); /** Sort p in descending order of age Arrays.sort(p, (b, c) -> c.age – b.age); When Java compiles these calls, it will eliminate the anonymous functions and turn it into code that uses interface Comparable! This is “syntactic sugar”! We use anonymous functions to listen to button clicks.

What is a JButton? Instance: associated with a “button” on the GUI, which can be clicked to do something jb1= new JButton() // jb1 has no text on it jb2= new JButton(“first”) // jb2 has label “first” on it jb2.isEnabled() // true iff a click on button can be // detected jb2.setEnabled(b); // Set enabled property jb2.addActionListener(object); // object must have a method, // which is called when button jb2 clicked (next page) At least 100 more methods; these are most important JButton is in package javax.swing

Listening to a JButton Implement interface ActionListener: public class C extends JFrame implements ActionListener { … } So, C must implement actionPerformed, and it will be called when the button is clicked public interface ActionListener extends … { /** Called when an action occurs. */ public abstract void actionPerformed(ActionEvent e); }

Listening to a JButton 1. Implement interface ActionListener: public class C extends JFrame implements ActionListener { … } 2. In C override actionPerformed --called when button is clicked: /** Process click of button */ public void actionPerformed(ActionEvent e) { … } public interface ActionListener extends EventListener { /** Called when an action occurs. */ public abstract void actionPerformed(ActionEvent e); }

Listening to a JButton 1. Implement interface ActionListener: public class C extends JFrame implements ActionListener { … } 2. In C override actionPerformed --called when button is clicked: /** Process click of button */ public void actionPerformed(ActionEvent e) { … } 3. Add an instance of class C an “action listener” for button: button.addActionListener(this); But instead, we use an anonymous function! Method Jbutton.addActionListener public void addActionListener(ActionListener l)

/** USE anonymous function */ class ButtonDemo1 extends JFrame { red: listening blue: placing /** USE anonymous function */ class ButtonDemo1 extends JFrame { /** exactly one of eastB, westB is enabled */ JButton westB= new JButton("west"); JButton eastB= new JButton("east"); public ButtonDemo1(String t) { super(t); add(westB, BLayout.WEST); add(eastB, BLayout, EAST); westB.setEnabled(false); eastB.setEnabled(true); Add listener to westB the same way eastB.addActionListener( e -> {boolean b= eastB.isEnabled();           eastB.setEnabled(!b);              westB.setEnabled(b);} ); Listening to a Button ButtonDemo1

/** Save anonymous function in local var*/ class ButtonDemo1 extends JFrame { /** exactly one of eastB, westB is enabled */ JButton westB= new JButton("west"); JButton eastB= new JButton("east"); public ButtonDemo1(String t) { super(t); add(westB, BLayout.WEST); add(eastB, BLayout, EAST); westB.setEnabled(false); eastB.setEnabled(true); red: listening blue: placing eastB.addActionListener(al); westB.addActionListener(al); pack(); setVisible(true); ActionListener al= e -> {boolean b= eastB.isEnabled();               eastB.setEnabled(!b);               westB.setEnabled(b);}; Listening to a Button ButtonDemo1

A JPanel that is painted MouseDemo2 The JFrame has a JPanel in its CENTER and a “reset” button in its SOUTH. The JPanel has a horizontal box b, which contains two vertical Boxes. Each vertical Box contains two instances of class Square. Click a Square that has no pink circle, and a pink circle is drawn. Click a square that has a pink circle, and the pink circle disappears. Click the rest button and all pink circles disappear. This GUI has to listen to: (1) a click on Button reset (2) a click on a Square (a Box) These are different kinds of events, and they need different listener methods

How painting works JPanel@25c7 paint(Graphics g) {…} repaint() {paint(gr)} JPanel gr Graphics Class Graphics has methods for drawing (painting) on the JPanel. We’ll look at them soon. Square Override paint to draw on the JPanel paint(Graphics g) {…} Whenever you want to call paint to repaint the Jpanel, call repaint()

/** Instance: JPanel of size (WIDTH, HEIGHT). Green or red: */ public class Square extends JPanel { public static final int HEIGHT= 70; public static final int WIDTH= 70; private int x, y; // Panel is at (x, y) private boolean hasDisk= false; /** Const: square at (x, y). Red/green? Parity of x+y. */ public Square(int x, int y) { this.x= x; this.y= y; setPreferredSize(new Dimension(WIDTH, HEIGHT)); } /** Complement the "has pink disk" property */ public void complementDisk() { hasDisk= ! hasDisk; repaint(); // Ask the system to repaint the square Class Square continued on later

Graphics is in package java.awt Class Graphics An object of abstract class Graphics has methods to draw on a component (e.g. on a JPanel, or canvas). Major methods: drawString(“abc”, 20, 30); drawLine(x1, y1, x2, y2); drawRect(x, y, width, height); fillRect(x, y, width, height); drawOval(x, y, width, height); fillOval(x, y, width, height); setColor(Color.red); getColor() getFont() setFont(Font f); More methods You won’t create an object of Graphics; you will be given one to use when you want to paint a component Graphics is in package java.awt

continuation of class Square /** Paint this square using g. System calls paint whenever square has to be redrawn.*/ public void paint(Graphics g) { if ((x+y)%2 == 0) g.setColor(Color.green); else g.setColor(Color.red); g.fillRect(0, 0, WIDTH-1, HEIGHT-1); if (hasDisk) { g.setColor(Color.pink); g.fillOval(7, 7, WIDTH-14, HEIGHT-14); } g.setColor(Color.black); g.drawRect(0, 0, WIDTH-1,HEIGHT-1); g.drawString("("+x+", "+y+")", 10, 5+HEIGHT/2); /** Remove pink disk (if present) */ public void clearDisk() { hasDisk= false; // Ask system to // repaint square repaint(); }

In package java.awt.event Listen to mouse event (click, press, release, enter, leave on a component) public interface MouseListener { void mouseClicked(MouseEvent e); void mouseEntered(MouseEvent e); void mouseExited(MouseEvent e); void mousePressed(MouseEvent e); void mouseReleased(MouseEvent e); } In package java.awt.event Having write all of these in a class that implements MouseListener, even though you don’t want to use all of them, can be a pain. So, a class is provided that implements them in a painless way.

In package java.swing.event Listen to mouse event (click, press, release, enter, leave on a component) In package java.swing.event MouseEvents public class MouseInputAdaptor implements MouseListener, MouseInputListener { public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} … others … } So, just write a subclass of MouseInputAdaptor and override only the methods appropriate for the application

Javax.swing.event.MouseInputAdapter implements MouseListener mouseClicked() mouseEntered() mouseExited() mousePressed() mouseReleased() MIA a1 mouseClicked() { … } MouseEvents MouseListener MouseDemo2() { … … } MouseDemo2 a2 JFrame a1 me b00 b01 b00.addMouseListener(me);

A class that listens to a mouseclick in a Square import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; /** Contains a method that responds to a mouse click in a Square */ public class MouseEvents extends MouseInputAdapter { // Complement "has pink disk" property public void mouseClicked(MouseEvent e) { Object ob= e.getSource(); if (ob instanceof Square) { ((Square)ob).complementDisk(); } red: listening blue: placing This class has several methods (that do nothing) to process mouse events: mouse click mouse press mouse release mouse enters component mouse leaves component mouse dragged beginning in component Our class overrides only the method that processes mouse clicks

e -> clearDisks(e)); b00.addMouseListener(me); jb.addActionListener( e -> clearDisks(e)); b00.addMouseListener(me); b01.addMouseListener(me); b10.addMouseListener(me); b11.addMouseListener(me); } public class MD2 extends Jframe { Box b= new Box(…X_AXIS); Box leftC= new Box(…Y_AXIS); Square b00, b01= new squares; Box riteC= new Box(..Y_AXIS); Square b10, b01= new squares; JButton jb= new JButton("reset"); /** Constructor: … */ public MouseDemo2() { super(“MouseDemo2”); place components in JFrame; pack, make unresizeable, visible; public void clearDisks( ActionEvent e) { call clearDisk() for b00, b01, b10, b11 } MouseEvents me= new MouseEvents(); red: listening blue: placing MouseDemo2

Listening to the keyboard import java.awt.*; import java.awt.event.*; import javax.swing.*; public class AllCaps extends KeyAdapter { JFrame capsFrame= new JFrame(); JLabel capsLabel= new JLabel(); public AllCaps() { capsLabel.setHorizontalAlignment(SwingConstants.CENTER); capsLabel.setText(":)"); capsFrame.setSize(200,200); Container c= capsFrame.getContentPane(); c.add(capsLabel); capsFrame.addKeyListener(this); capsFrame.show(); } public void keyPressed (KeyEvent e) { char typedChar= e.getKeyChar(); capsLabel.setText(("'" + typedChar + "'").toUpperCase()); red: listening blue: placing 1. Extend this class. 3. Add this instance as a key listener for the frame 2. Override this method. It is called when a key stroke is detected.

25 Have a different listener for each button ButtonDemo3 public class BDemo3 extends JFrame { private JButton wB, eB …; public ButtonDemo3() { Add buttons to JFrame, … wB.addActionListener(this); eB.addActionListener(new BeListener()); } public void disableE(ActionEvent e) { eB.setEnabled(false); wB.setEnabled(true); } public void disableW(ActionEvent e) { eB.setEnabled(true); wB.setEnabled(false); } Have a different listener for each button ButtonDemo3 25

ANONYMOUS CLASS You will see anonymous classes in A5 and other GUI programs Use sparingly, and only when the anonymous class has 1 or 2 methods in it, because the syntax is ugly, complex, hard to understand. The last two slides of this ppt show you how to eliminate BeListener by introducing an anonymous class. You do not have to master this material 26

1 object of BeListener created. Ripe for making anonymous Have a class for which only one object is created? Use an anonymous class. Use sparingly, and only when the anonymous class has 1 or 2 methods in it, because the syntax is ugly, complex, hard to understand. public class BDemo3 extends JFrame implements ActionListener { private JButton wButt, eButt …; public ButtonDemo3() { … eButt.addActionListener(new BeListener()); } public void actionPerformed(ActionEvent e) { … } private class BeListener implements ActionListener { public void actionPerformed(ActionEvent e) { body } 1 object of BeListener created. Ripe for making anonymous 27

28 Expression that creates object of BeListener 1. Write new Making class anonymous will replace new BeListener() eButt.addActionListener( new BeListener () ); private class BeListener implements ActionListener { declarations in class } } Expression that creates object of BeListener 1. Write new 3. Write new ActionListener () 3. Put in arguments of constructor call 2. Write new ActionListener 2. Use name of interface that BeListener implements 4. Write new ActionListener () { declarations in class } 4. Put in class body 5. Replace new BeListener() by new-expression 28

PaintGUI. setUpMenuBar, fixing item “New” ANONYMOUS CLASS IN A5. PaintGUI. setUpMenuBar, fixing item “New” Fix it so that control-N selects this menu item Save new JMenuItem new ActionListener() { … } declares an anonymous class and creates an object of it. The class implements ActionListener. Purpose: call newAction(e) when actionPerformed is called 29

30 Using an A5 function (only in Java 8!. PaintGUI. setUpMenuBar, fixing item “New” Fix it so that control-N selects this menu item Save new JMenuItem argument e -> { newAction(e);} of addActionListener is a function that, when called, calls newAction(e). 30

ANONYMOUS CLASS VERSUS FUNCTION CALL PaintGUI. setUpMenuBar, fixing item “New” The Java 8 compiler will change this: newItem.addActionListener(e -> { newAction(e); }); back into this: newItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { newAction(e); } }); and actually change that back into an inner class