CMSC 341 Making Java GUIs Functional. 09/29/2007 CMSC 341 Events 2 More on Swing Great Swing demo at /demos/jfc/SwingSet2/SwingSet2Plugin.html.

Slides:



Advertisements
Similar presentations
Event handling and listeners What is an event? user actions and context event sources and listeners Why should my programs be event- driven? User interaction.
Advertisements

Programming in Java; Instructor:John Punin Graphics and Graphical User Interfaces1 Programming in Java Graphics and Graphical User Interfaces.
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.
TCU CoSc Programming with Java Handling Events.
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.
Event Handling.
Jan Event Handling -1.1 Yangjun Chen Dept. Business Computing University of Winnipeg.
Events and the AWT The objectives of this chapter are: To understand the principles of the Java 1.1 event model To understand how the event model is used.
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.
Unit 12 Object-oriented programming: Event-driven programming for GUI Jin Sa.
Event Handling n Events: an event is an object that describes a state change in a source. n Event Sources: A source is an object that generates an event.
1 Gui Programming (Part I) Graphical User Interfaces (Part I) l Introduction to events. l A Brief history. l Event sources and listeners. l The delegation.
Intermediate Java1 An example that uses inner classes Week Four Continued.
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
28-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Event Handling – GUI Part II.
GUI Programming in Java: Event Handling & More Components Corresponds with Chapter 14, Chapter 15.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © 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,
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
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.
CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.
Graphical User Interface Components: Part 1 Chapter 11.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
Pravin Yannawar, DOCS, NMU Jalgaon. Basic Java : Event handling in AWT and Swing 2 Objectives of This Session Explain the Event handling mechanism & demonstrate.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
For (int i = 1; i
UID – Event Handling and Listeners Boriana Koleva
Event Handling. 2 GUIs are event driven –Generate events when user interacts with GUI e.g., moving mouse, pressing button, typing in text field, etc.
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.
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA.
Object Oriented Programming.  Interface  Event Handling.
Agenda Introduction. Event Model. Creating GUI Application. Event Examples.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
Events in JAVA Needed for Applets and GUI based programs. Applet uses GUI to interact with user. Most of the events are generated by Mouse, Keyboard.
Event Handling. User actions are called “events” – Low-level window events Window changes – Low-level component events Mouse events, Keyboard events,
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,
Event-Driven Programming F Procedural programming is executed in procedural order. F In event-driven programming, code is executed upon activation of events.
1 Event Handling – Lecture 4 Prepared by: Ahmad Ramin Rahimee Assistant Professor ICTI.
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.
Mouse Events GUI. Types of Events  Below, are some of the many kinds of events, swing components generate. Act causing EventListener Type User clicks.
Event Handling and Listeners in SWING The practice of event handling.
Event Handling CS 21a: Introduction to Computing I First Semester,
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.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
TENTH LECTURE Event and listener. Events and Listeners An event can be defined as a type of signal to the program that something has happened. The event.
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.
GUI Programming in Java Hao Jiang Boston College April, 2009.
Events and Event Handling
Chapter 14 Event-Driven Programming
Welcome To java
CompSci 230 S Programming Techniques
Lecture 8 Object Oriented Programming Using Java
Chapter 12 Event-Driven Programming
Programming in Java Event Handling
CSE 114 – Computer Science I Event Programming
GUI Programming III: Events
Event-driven programming for GUI
Web Design & Development Lecture 12
Chapter 16 Event-Driven Programming
Events, Event Handlers, and Threads
Making Java GUIs Functional
Presentation transcript:

CMSC 341 Making Java GUIs Functional

09/29/2007 CMSC 341 Events 2 More on Swing Great Swing demo at /demos/jfc/SwingSet2/SwingSet2Plugin.html Just google for “SwingSet Demo Java” Now let’s learn how to make GUIs functional

09/29/2007 CMSC 341 Events 3 Last Class Learned about GUI Programming. Created two GUIs –UppercaseConverter –Calculator Now we will make them work.

09/29/2007 CMSC 341 Events 4 Events Java uses an Event Delegation Model. Every time a user interacts with a component on the GUI, events are generated. Events are component-specific. Events are objects that store information like  the type of event that occurred,  the source of the event,  the time of an event to name a few.

09/29/2007 CMSC 341 Events 5 Event Delegation Model Once the event is generated, then the event is passed to other objects which handle or react to the event, thus the term event delegation. The objects which react to or handle the events are called event listeners.

09/29/2007 CMSC 341 Events 6 Three Players Event source which generates the event object Event listener which receives the event object and handles it Event object that describes the event

09/29/2007 CMSC 341 Events 7 Revisiting our GUI We have already created a GUI. How many components? What are some possible events?

09/29/2007 CMSC 341 Events 8 Example Click on UPPER JButton Generates an ActionEvent Event object is sent to an ActionListener that is registered with the UPPER JButton ActionListener handles in actionPerformed method. Event public class Handler implements ActionListener { public void actionPerformed(ActionEvent e){ System.out.println(“Handling “ + e); }

09/29/2007 CMSC 341 Events 9 Registering Listeners By having a class implement a listener interface, it can contain code to handle an event. However, unless an instance of the class is registered with the component, the code will never be executed. (Common novice error.)

09/29/2007 CMSC 341 Events 10 A Few More Java Events FocusEvent – component gains or loses focus FocusEvent MouseEvent – mouse is moved, dragged, pressed, released or clicked MouseEvent WindowEvent – window is iconified, deiconified, opened or closed WindowEvent TextEvent – text is modified TextEvent KeyEvent – key is pressed, depressed or both KeyEvent ContainerEvent – components are added or removed from Container ContainerEvent

09/29/2007 CMSC 341 Events 11 Corresponding Listeners FocusEvent – FocusListener FocusListener MouseEvent – MouseListener, MouseMotionListener MouseListenerMouseMotionListener WindowEvent – WindowStateListener, WindowListener, WindowFocusListener WindowStateListener WindowListenerWindowFocusListener TextEvent – TextListener TextListener KeyEvent – KeyListener KeyListener ItemEvent- ItemListener ItemListener ContainerEvent – ContainerListener ContainerListener

09/29/2007 CMSC 341 Events 12 Methods for Registering Listeners JButton  addActionListener(ActionListener a)  addChangeListener(ChangeListener c)  addItemListener(ItemListener i) JList  addListSelectionListener(ListSelectionListener l)

09/29/2007 CMSC 341 Events 13 UpperCaseConverter Example Goal  When UPPER button is pressed, the text in the textfield will be converted to upper case and appended into the text area.  When CLEAR button is pressed, both the text field and the text area will be cleared. Things to consider to accomplish goal  What type of events do we need to respond to?  What listener interfaces do we need to implement?

09/29/2007 CMSC 341 Events 14 Implementing an ActionListener Create as a separate class  No access to data in JFrame Create as an inner class  Access to JFrame data  Must instantiate an object of this class to pass to addActionListener method Make the JFrame implement the interface  Access to JFrame data  No need to instanciate an object of this class – have the this reference

09/29/2007 CMSC 341 Events 15 Implementing ActionListener import java.awt.event.*; public class UpperCaseConverter extends JFrame implements ActionListener {//omitted code upper = new JButton("UPPER"); clear = new JButton("CLEAR"); upper.addActionListener(this); clear.addActionListener(this); //omitted code public void actionPerformed(ActionEvent e){ Object obj = e.getSource(); if(obj == clear) System.out.println("Clear"); else if(obj == upper) System.out.println("Upper"); } Good to test for expected interaction as you go

09/29/2007 CMSC 341 Events 16 Implement Desired Behavior public void actionPerformed(ActionEvent e) { Object obj = e.getSource(); if(obj == clear){ input.setText(""); output.setText(""); } else if(obj == upper){ String result = input.getText(); StringBuffer buffer = new StringBuffer(output.getText()); buffer.append(result.toUpperCase()+ "\n"); output.setText(buffer.toString()); } JButtons, JLabels, JTextFields and JTextAreas all have setText method to change their content

09/29/2007 CMSC 341 Events 17 Adding Functionality to the Calculator Need capability for telling the number to go to the left or right TextField.  If click and holding the ctrl button then number goes to the left, else the right. Need to be able to perform operations.  Use the operators themselves for the operations. Need to be able to clear fields.  Convert the equal sign to a C for clear.

09/29/2007 CMSC 341 Events 18 Slightly Modified GUI Notice the change –Changed ‘=‘ to ‘C’ –Changed all references from “equals” to “clears” in the code

09/29/2007 CMSC 341 Events 19 Add Listeners plus.addActionListener(this); minus.addActionListener(this); mult.addActionListener(this); div.addActionListener(this); clears.addActionListener(this); dot.addActionListener(this); for(int i = 0; i < 10 ; i++) numbers[i].addActionListener(this);

09/29/2007 CMSC 341 Events 20 Implementing the actionPerformed Method First step is to implement the skeleton code that will recognize the different locations that are clicked. Second step is to code for clicks with ctrl key pressed and not pressed. Third step is to add desired behavior.  Helper methods would be helpful for the converting of text to floats and for the various arithmetic operations.

09/29/2007 CMSC 341 Events 21 More ActionEvent Methods public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); System.out.println(command); int modifiers = e.getModifiers(); if(modifiers == ActionEvent.CTRL_MASK) System.out.println("CTRL PRESSED"); }

09/29/2007 CMSC 341 Events 22 Problem Unfortunately, the code on the previous code can not differentiate between a button click with the control key down and a button click alone. Next… try MouseListener interface.  mousePressed  mouseReleased  mouseExited  mouseClicked  mouseEntered

09/29/2007 CMSC 341 Events 23 Changing to a MouseListener Change all ActionListener references to MouseListener references Remove actionPerformed method and add: public void mouseClicked(MouseEvent e){ int button = e.getButton(); System.out.println(button); String modifiers = e.getMouseModifiersText(e.getModifiers()); System.out.println(modifiers); } public void mouseReleased(MouseEvent e){} public void mousePressed(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} Determines which button was pressed, right or left States whether the Ctrl, Alt or Shift buttons were pressed

09/29/2007 CMSC 341 Events 24 Output After a left click then right click on a number output is: 1 Button1 3 Meta+Button3 After left click then right click on a number with ctrl down output is: 1 Ctrl+Button1 3 Meta+Ctrl+Button3

09/29/2007 CMSC 341 Events 25 mouseClicked Method Need to use getSource method to determine which button was pressed. Easiest way to differentiate is left click and right click Left click ->left operand Right click -> right operand For operators doesn’t matter

09/29/2007 CMSC 341 Events 26 Functional mouseClicked Method public void mouseClicked(MouseEvent e){ int button = e.getButton(); JTextField dest = null; if(button == 1) dest = operand1; //left click == left operand if(button == 3) dest = operand2; //right click == right operand Object src = e.getSource(); if(src == clears) clear(); //helper method else if(src == mult||src == div||src == plus||src == minus) performOperation(src); //helper method else{ int i = 0; for(; i < numbers.length; i++) if(src == numbers[i]) break; StringBuffer text = new StringBuffer(dest.getText()); if (src == dot) text.append(dot.getText()); else text.append(numbers[i].getText()); dest.setText(text.toString()); }

09/29/2007 CMSC 341 Events 27 Helper Method private void performOperation(Object src){ float f1 = 0;float f2 = 0; try { f1 = Float.parseFloat(operand1.getText()); f2 = Float.parseFloat(operand2.getText()); }catch (NumberFormatException e){ output.setText("Invalid Number Format"); } try{ float ans = 0; if(src == mult) ans = f1 * f2; else if(src == plus) ans = f1 + f2; else if(src == minus) ans = f1 - f2; else if(src == div) ans = f1 / f2; output.setText(Float.toString(ans)); } catch (Exception e) { output.setText("Invalid Operation"); }

09/29/2007 CMSC 341 Events 28 Adapter Classes In the previous implementation, we implemented four empty methods. We can create a listener class that extends its corresponding adapter class. Adapter classes provide the empty implementation of all the methods in a listener interface We only need to override the method(s) whose behavior we want to influence.

09/29/2007 CMSC 341 Events 29 Anonymous Inner Classes Adapter classes are often implemented as anonymous inner classes. mult.addListener(new MouseAdapter(){ public void mouseReleased(){ // specialized code just for mult // that will only be executed when mouse is // released on the ‘x’ JButton } });