CS2110. GUIS: Listening to Events

Slides:



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

Computer Science 209 Graphics and GUIs. Working with Color The class java.awt.Color includes constants for typical color values and also supports the.
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.
Mouse Events and Keyboard Events
Event Handling Events and Listeners Timers and Animation.
Event-Driven Programming
Unit 12 Object-oriented programming: Event-driven programming for GUI Jin Sa.
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.
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.
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.
(c) University of Washington07b-1 CSC 143 Java Events, Event Handlers, and Threads Reading: Ch. 17.
SD2071 Games Programming Abstraction, inheritance and interfaces Exceptions Two dimensional arrays Java collections framework Files Aaron Kans.
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.
Swing GUI Components You can create graphics components to place on your applet using classes available in the Swing package ( javax.swing ) Class names.
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.
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.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Event Handling.
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.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Chapter 10 Event Handling.
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.
Event-Driven Programming F Procedural programming is executed in procedural order. F In event-driven programming, code is executed upon activation of events.
1/18H212Mouse and Timer Events H212 Introduction to Software Systems Honors Lecture #16: Mouse and Timer Events October 26, 2015.
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.
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.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
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.
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.
1 DemoBasic_v3, DemoBasic_v4 JButton JLabel. 2 Registering an ActionListener Register by invoking the following from within constructor DemoBasicFrame.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 7 Event-Driven Programming and Basic GUI Objects.
Review Session for EXCEPTIONS & GUI -Ankur Agarwal 1.
CS2110. GUIS: Listening to Events
Events and Event Handling
Chapter 14 Event-Driven Programming
CompSci 230 S Programming Techniques
Java Applets.
A First Look at GUI Applications
CS2110. GUIS: Listening to Events
Computer Science 209 Graphics and GUIs.
Listening to events on GUIs
Ellen Walker Hiram College
GUI Event Handling Nithya Raman.
GUI Programming III: Events
CS2110. GUIS: Listening to Events
Event-driven programming for GUI
Java Applets.
CS2110. GUIS: Listening to Events
Chapter 16 Event-Driven Programming
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 Also anonymous classes

Additional GUI references See swing demos (demoGUI.zip, course website) See swing tutorial

(A5 demo)

Custom components Creating custom components: - extend an existing component class - often JPanel - perform setup in constructor - override paint(Graphics) to draw it

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

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(); }

Class java.awt.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 (see also Graphics2D)

Events

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.

Listening to a JButton Implement interface ActionListener: public class C extends JFrame implements ... ActionListener { } In class C override actionPerformed, which is to be 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);

/** Object has two buttons. Exactly one is enabled. */ class ButtonDemo1 extends JFrame { /** Class inv: exactly one of eastB, westB is enabled */ JButton westB= new JButton("west"); JButton eastB= new JButton("east"); public ButtonDemo1(String t) { super(t); Container cp= getContentPane(); cp.add(westB, BLayout.WEST); cp.add(eastB, BLayout, EAST); westB.setEnabled(false); eastB.setEnabled(true); pack(); setVisible(true); } red: listening blue: placing implements ActionListener public void actionPerformed (ActionEvent e) { boolean b= eastB.isEnabled(); eastB.setEnabled(!b); westB.setEnabled(b); } westB.addActionListener(this); eastB.addActionListener(this); Listening to a Button

In package java.awt.event Mouse events 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 to 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 painless way.

In package java.swing.event Mouse events In package java.swing.event public class MouseInputAdaptor implements MouseListener { 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

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

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.

Code organization

Where to implement Listener interface In the main class? Can’t use adapter Can only have one kind of listener In a separate class? Can’t access fields In an inner class? This is often done in practice

18 public class BDemo3 extends JFrame implements ActionListener { private JButton wButt, eButt …; public ButtonDemo3() { Add buttons to content pane, enable ne, disable the other wButt.addActionListener(this); eButt.addActionListener(new BeListener()); } public void actionPerformed(ActionEvent e) { boolean b= eButt.isEnabled(); eButt.setEnabled(!b); wButt.setEnabled(b); } } class BeListener implements ActionListener { eButt.setEnabled(!b); wButt.setEnabled(b); Have a different listener for each button Doesn’t work! Can’t reference eButt, wButt A listener for eastButt 18

listens to eButt but can’t reference fields BD3@2 BD3 eButt … aPerf(… eButt … wButt ...} wButt BeLis@80 BeLis listens to wButt listens to eButt but can’t reference fields Make BeListener an inner class. Inside-out rule then gives access to wButt, eButt BD3@2 BD3 eButt … aPerf…(… eButt … wButt..} wButt BeLis@80 BeLis aPerf(… eButt … wButt ...} 19

We demo this using ButtonDemo3 Solution to problem: Make BeListener an inner class. public class BDemo3 extends Jframe implements ActionListener { private JButton wButt, eButt …; public ButtonDemo3() { … } public void actionPerformed(ActionEvent e) { … } private class BeListener implements ActionListener { … } Just as you can declare variables and methods within a class, you can declare a class within a class Inside-out rule says that methods in here Can reference all the fields and methods We demo this using ButtonDemo3 20

C must implement interface IN that has abstract method aP Problem: can’t give a function as a parameter: Why not just give eButt the function to call? Can’t do it in Java 7! Can in some other languages and Java 8 public void m() { … eButt.addActionListener(aP); } public void aP(ActionEvent e) { body } public void m() { … eButt.addActionListener(new C()); } public class C implements IN { public void aP(ActionEvent e) { body } Java says: provide class C that wraps method; give eButt an object of class C C must implement interface IN that has abstract method aP 21

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 22

23 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 23

with class named and with class anonymous: public ButtonDemo3() { … eButt.addActionListener(new BeListener()); } private class BeListener implements ActionListener { public void actionPerformed(ActionEvent e) { body } public ButtonDemo3() { … eButt.addActionListener(new ActionListener () { public void actionPerformed(ActionEvent e) { body } }); } 24

Java 8 allows functions as parameters We won’t talk anymore about functions as parameters. Perhaps next semester we’ll redo things to cover functions as parameters. 25