GUI Programming in Java: Event Handling & More Components Corresponds with Chapter 14, Chapter 15.

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

TCU CoSc Programming with Java Handling Events.
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 12 Event-Driven Programming 找出画中真谛 — 保罗. 塞尚.
Fall 2007CS 225 Graphical User Interfaces Event Handling Appendix C.
Java Programming, 3e Concepts and Techniques Chapter 5 Arrays, Loops, and Layout Managers Using External Classes.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
Event Handling Events and Listeners Timers and Animation.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 15 Event-Driven Programming.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 14 Event-Driven Programming.
© The McGraw-Hill Companies, 2006 Chapter 18 Advanced graphics programming.
Event-Driven Programming
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 16 Event-Driven Programming.
1 Event-Driven Programming Just like designing GUIs, you also will probably not write Java code like the program examples given in these notes. You will.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
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,
Java Programming: Guided Learning with Early Objects
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 14 Event-Driven Programming.
Dale Roberts GUI Programming using Java - Event Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Graphical User Interface Components: Part 1 Chapter 11.
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.
1 Unit 5 GUI Aum Amriteshwaryai Namah. 2 Overview Shall learn how to reuse the graphics classes provided by Java for constructing Graphical User Interface.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
Dale Roberts GUI Programming using Java - GUI Components Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
Omer Boyaci.  GUIs are event driven.  When the user interacts with a GUI component, the interaction—known as an event—drives the program to perform.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 12 Event-Driven Programming.
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.
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
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.
Lesson 6 Programming Techniques Event Handling /EvH/ AUBG ICoSCIS Team Assoc. Prof. Stoyan Bonev March, , 2013 SWU, Blagoevgrad.
Object Oriented Programming.  Interface  Event Handling.
Agenda Introduction. Event Model. Creating GUI Application. Event Examples.
Graphical User Interface Components: Part 1 Chapter 11.
Creating User Interfaces Chapter 13 CSCI CSCI 1302 – Creating User Interfaces2 Outline Introduction Common Features of Swing GUI Components Buttons.
Creating User Interfaces Event-Driven Programming.
Copyright © Curt Hill More Widgets In Abstract Window Toolbox.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
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.
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.
 Figure illustrates a hierarchy containing many event classes from the package java.awt.event.  Used with both AWT and Swing components.  Additional.
1 Chapter 3 Event-Driven Programming. 2 Objectives F To explain the concept of event-driven programming (§12.2). F To understand event, event source,
1 Lecture 8: User Interface Components with Swing.
Jozef Goetz Credits: Copyright  Pearson Education, Inc. All rights reserved. expanded by J. Goetz, 2016.
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.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
GUIs & Event-Driven Programming Chapter 11 Review.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
Java GUI programming with Swing Tim McKenna
GUI Programming using Java - Event Handling
GUIs and Events Rick Mercer.
CSC 205 Programming II Lecture 5 AWT - I.
Chapter 14 Event-Driven Programming
CompSci 230 S Programming Techniques
A First Look at GUI Applications Radio Buttons and Check Boxes
Chapter 12 Event-Driven Programming
Appendix I GUI Components and Event Handling
A First Look at GUI Applications
Advanced User Interfaces
Graphical User Interface (pronounced "gooey")
Chapter 16 Event-Driven Programming
Exception Handling and Event Handling
Java GUI programming with Swing
Presentation transcript:

GUI Programming in Java: Event Handling & More Components Corresponds with Chapter 14, Chapter 15

Event-Driven Programming Procedural programming is executed in procedural order. Procedural programming is executed in procedural order. In event-driven programming, code is executed upon activation of events. In event-driven programming, code is executed upon activation of events.

Events and Listeners An event can be defined as a type of signal to the program that something has happened. An event can be defined as a type of signal to the program that something has happened. The event is generated by external user actions such as mouse movements, mouse button clicks, and keystrokes, or by the operating system, such as a timer. The event is generated by external user actions such as mouse movements, mouse button clicks, and keystrokes, or by the operating system, such as a timer. Events are responded to by event listeners Events are responded to by event listeners

The Delegation Model Event-generating Objects send Events to Listener Objects Each event-generating object (usually a component) maintains a set of listeners for each event that it generates. To be on the list, a listener object must register itself with the event-generating object. Listeners have event-handling methods that respond to the event.

Event Classes We will focus on ActionEvent and ListSelectionEvent

Selected User Actions SourceEvent Type User ActionObjectGenerated Click a button JButtonActionEvent Click a check box JCheckBoxItemEvent, ActionEvent Click a radio button JRadioButtonItemEvent, ActionEvent Press return on a text field JTextFieldActionEvent Select a new item JComboBoxItemEvent, ActionEvent Select an item from a List JListListSelectionEvent Window opened, closed, etc. WindowWindowEvent Mouse pressed, released, etc.Any ComponentMouseEvent Key released, pressed, etc. Any ComponentKeyEvent

Java AWT Event Listener Interfaces  ActionListener  AdjustmentListener  ComponentListener  ContainerListener  FocusListener  ItemListener  KeyListener  MouseListener  MouseMotionListener  TextListener  WindowListener  ListSelectionListener All are in the java.awt.event or javax.swing.event package All are derived from EventListener in the java.util package NOTE: any object that will respond to an event must implement a listener interface.

How to Implement a Listener Interface Use the implements keyword in the class declaration Use the implements keyword in the class declaration Register the object as a listener for a component’s event, using the component’s addXListener method. (where X is the type of event). (Typically done in constructor) Register the object as a listener for a component’s event, using the component’s addXListener method. (where X is the type of event). (Typically done in constructor) Declare and fully define all methods for the interface that you are implementing Declare and fully define all methods for the interface that you are implementing Requires: Requires: Complete method signature Complete method signature Method body Method body

Selected Event Handlers Event ClassListener InterfaceListener Methods (Handlers) ActionEventActionListeneractionPerformed(ActionEvent) ItemEventItemListeneritemStateChanged(ItemEvent) ListSelectionListSelectionvalueChanged EventListener(ListSelectionEvent)

Handling Simple Action Events Implementing the listener interface Registering the frame to be a listener for action events generated by the two buttons The method for responding to an Action event.

Handling Simple Action Events – a closer look at the event-handling method actionPerformed is a method required for all ActionListeners An Event object’s getSource() method returns a reference to the Component object that generated the event.

Alternative Approaches to Listening Implement the listener with the main application class, and have the one listener assigned to all components generating the events Implement the listener with the main application class, and have the one listener assigned to all components generating the events This is the approach I generally use with my examples This is the approach I generally use with my examples Advantage: simplicity for beginner programmers Advantage: simplicity for beginner programmers Disadvantage: event-handler method may require if-statement or switch with several branches when multiple components generate the event Disadvantage: event-handler method may require if-statement or switch with several branches when multiple components generate the event Use inner classes to implement the listeners and create a different instance as each component’s listener. Use inner classes to implement the listeners and create a different instance as each component’s listener. Named inner class or anonymous inner class (This is the approach used in the textbook most of the time) Named inner class or anonymous inner class (This is the approach used in the textbook most of the time) Advantage: no need to test within the listeners for determining which component sent the event. Each component has its own dedicated listener Advantage: no need to test within the listeners for determining which component sent the event. Each component has its own dedicated listener Disadvantage: harder to understand for novice programmers Disadvantage: harder to understand for novice programmers

Example with named inner classes, one for listening to each button Inner class has direct access to all members (even private) of the outer class

Example with anonymous inner classes, one for listening to each button

Working with JLabel, JTextField, JTextArea, JList, JComboBox, and JRadiobutton Similar topics are covered in Chapter 15, but these examples are my own

JLabel Swing class for a non-editable text display Swing class for a non-editable text display Typical constructor: Typical constructor: JLabel(stringValue) JLabel(stringValue) Other Useful Methods: Other Useful Methods: getText() – returns a string containing the text in the label component getText() – returns a string containing the text in the label component setText(String) – sets the label component to contain the string value setText(String) – sets the label component to contain the string value

JTextField Swing class for an editable text display Swing class for an editable text display Many constructors possible – here’s one: Many constructors possible – here’s one: JTextField(columnWidth) JTextField(columnWidth) Will instantiate a text field component of the specified width (width is approximate number of characters visible). Will instantiate a text field component of the specified width (width is approximate number of characters visible). Some useful methods: Some useful methods: getText() – returns the text value in the text field getText() – returns the text value in the text field getSelectedText() – returns the text value that has been highlighted in the text field getSelectedText() – returns the text value that has been highlighted in the text field setText(stringValue) – sets the text value to the indicated argument setText(stringValue) – sets the text value to the indicated argument append(stringvalue) – appends the text value of the string to the already existing text in the component append(stringvalue) – appends the text value of the string to the already existing text in the component

JTextArea Swing class for an editable text display Swing class for an editable text display Many constructors possible – here’s one: Many constructors possible – here’s one: JTextArea(rowHeight, columnWidth) JTextArea(rowHeight, columnWidth) Will instantiate a text area component of the specified width and height (width is approximate number of characters visible, height is approximate number of text lines visible) Will instantiate a text area component of the specified width and height (width is approximate number of characters visible, height is approximate number of text lines visible) Some useful methods: Some useful methods: getText() – returns the text value in the text field getText() – returns the text value in the text field getSelectedText() – returns the text value that has been highlighted in the text field getSelectedText() – returns the text value that has been highlighted in the text field setText(stringValue) – sets the text value to the indicated argument setText(stringValue) – sets the text value to the indicated argument append(stringvalue) – appends the text value of the string to the already existing text in the component append(stringvalue) – appends the text value of the string to the already existing text in the component

Note use of getText, setText, getSelectedText and append methods.

JList Swing GUI component that presents a list of items Swing GUI component that presents a list of items Many constructors…here’s one: Many constructors…here’s one: JList(sourceArray); JList(sourceArray); Produces a ListSelectionEvent Produces a ListSelectionEvent Handling this event by implementing a ListSelectionListener Handling this event by implementing a ListSelectionListener Need to import javax.swing.event package for this Need to import javax.swing.event package for this Some useful methods: Some useful methods: addListSelectionListener – specify which objects will respond to list selection event addListSelectionListener – specify which objects will respond to list selection event setListData – indicate the source of data for this list (e.g. an array) setListData – indicate the source of data for this list (e.g. an array) getSelectedIndex – identify the current selection from the list (0-based) indicates nothing is selected from list. getSelectedIndex – identify the current selection from the list (0-based) indicates nothing is selected from list. setFixedCellHeight and setFixedCellWidth – indicate pixel size of each item of the list. setFixedCellHeight and setFixedCellWidth – indicate pixel size of each item of the list.

components List’s data source JList Example 1: using lists, text fields, labels, and buttons Implementing listeners

Use list index tp get associated array element When array changes, refresh the list JList Example 1: using lists, text fields, labels, and buttons (con’t.) valueChanged is the ListSelectionListener event handler method

JList Example 2: slightly more complicated…data source is an array of objects This is the class being used for the array associated with the JList. toString is a method that overrides the Object class’s method of the same name. This determines what will be displayed in the JList.

JList Example 2: slightly more complicated…data source is an array of objects

Exception Handling This example makes use of Exception handling This example makes use of Exception handling try/catch format try/catch format NOTE: if the text entered into the numeric field cannot be parsed into a number, an Exception is thrown (specifically a NumberFormatExeption). NOTE: if the text entered into the numeric field cannot be parsed into a number, an Exception is thrown (specifically a NumberFormatExeption).

Exception Handling Using try and catch try{……..} catch (ExceptionType e){ ……..} If code within the try block causes an error, the program will automatically branch to the catch block

JList Example 2: slightly more complicated…data source is an array of objects This may throw an exception Here we handle the exception Code in the try block

JComboBox Swing GUI component that presents a dropdown list of items Swing GUI component that presents a dropdown list of items Many constructors…here’s one: Many constructors…here’s one: JComboBox(sourceArray); JComboBox(sourceArray); Produces an ActionEvent and an ItemEvent Produces an ActionEvent and an ItemEvent You can handle these event by implementing an ActionListener or an ItemListener You can handle these event by implementing an ActionListener or an ItemListener If you want to handle these events, you need to import java.awt.event package If you want to handle these events, you need to import java.awt.event package Some useful methods: Some useful methods: getSelectedIndex – identify the current selection from the list (0- based) indicates nothing is selected from list. getSelectedIndex – identify the current selection from the list (0- based) indicates nothing is selected from list. getSelectedItem – returns the currently selected object from the list. Since it returns an Object reference, if you want to treat it as string, you should call toString() for the returned object getSelectedItem – returns the currently selected object from the list. Since it returns an Object reference, if you want to treat it as string, you should call toString() for the returned object setSelectedIndex – Changes the current selection to whatever the integer is that is passed as an argument. setSelectedIndex – Changes the current selection to whatever the integer is that is passed as an argument. setSelectedItem – sets the currently selected item to whatever the Object is that is passed as an argument setSelectedItem – sets the currently selected item to whatever the Object is that is passed as an argument

JRadioButton Swing GUI component that presents a radio buttons of options. You group the options into a ButtonGroup. Swing GUI component that presents a radio buttons of options. You group the options into a ButtonGroup. Many constructors…here’s one: Many constructors…here’s one: JRadioButton(Label) JRadioButton(Label) Since a RadioButton is a button, it produces an ActionEvent. It also generates a ChangeEvent Since a RadioButton is a button, it produces an ActionEvent. It also generates a ChangeEvent You can handle these event by implementing an ActionListener or an ChangeListener You can handle these event by implementing an ActionListener or an ChangeListener If you want to handle these events, you need to import java.awt.event package If you want to handle these events, you need to import java.awt.event package Lots of useful methods…here’s three: Lots of useful methods…here’s three: setMnemonic – Specifies a alt-Key alternative for selecting the RadioButton. setMnemonic – Specifies a alt-Key alternative for selecting the RadioButton. isSelected – returns a boolean value to specify if the button has been selected isSelected – returns a boolean value to specify if the button has been selected setSelected(boolean) – allows you to programmatically change the selection status of a RadioButton setSelected(boolean) – allows you to programmatically change the selection status of a RadioButton Put related RadioButtons into a ButtonGroup, so only one will be selected at a time Put related RadioButtons into a ButtonGroup, so only one will be selected at a time Instantiate the ButtonGroup Instantiate the ButtonGroup Call the ButtonGroup’s add method to assign RadioButtons Call the ButtonGroup’s add method to assign RadioButtons

By putting all buttons into a panel, you can place them all together in the same region of the frame’s BorderLayout By putting all buttons into a ButtonGroup, you ensure that only one will be selected at a time This code causes the RadioButtons to generate ActionEvents that the frame will listen to Via setMnemonic, you allow Alt-1, Alt-2 and Alt-3 to select the appropriate RadioButtons

A component’s action command is usually its label, although you can change this The setSelected method can be used to programmatically change the current RadioButton selection The isSelected method can be used to determine if a RadioButton is selected