GUI Event Handlers (Part II)

Similar documents
GUI Event Handlers (Part I)

Chapter 18. Advanced graphics programming

Graphical User Interfaces 2

Outline. More on the Swing API Graphics: double buffering and timers Model - View - Controller paradigm Applets

Advanced Java Programming (17625) Event Handling. 20 Marks

GUI in Java TalentHome Solutions

Graphical User Interfaces 2

Method Of Key Event Key Listener must implement three methods, keypressed(), keyreleased() & keytyped(). 1) keypressed() : will run whenever a key is

EVENTS, EVENT SOURCES AND LISTENERS

Graphical User Interfaces 2

12/22/11. Copyright by Pearson Education, Inc. All Rights Reserved.

Graphical User Interfaces. Comp 152

The AWT Event Model 9

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Chapter 6: Graphical User Interfaces

CS111: PROGRAMMING LANGUAGE II

Java Event Handling -- 1

Introduction to the JAVA UI classes Advanced HCI IAT351

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

CS 251 Intermediate Programming GUIs: Components and Layout

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

ECE 462 Object-Oriented Programming using C++ and Java. Key Inputs in Java Games

Handling Mouse and Keyboard Events

BASICS OF GRAPHICAL APPS

Advanced Computer Programming

GUI 4.1 GUI GUI MouseTest.java import javax.swing.*; import java.awt.*; import java.awt.event.*; /* 1 */

Summary Chapter 25 GUI Components: Part 2

Computer Science 210: Data Structures. Intro to Java Graphics

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

Unit 7: Event driven programming

Java & Graphical User Interface II. Wang Yang wyang AT njnet.edu.cn

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

SD Module-1 Advanced JAVA

SD Module-1 Advanced JAVA. Assignment No. 4

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class.

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

JDirectoryChooser Documentation

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

Dr. Hikmat A. M. AbdelJaber

Computer Programming Java AWT Lab 18

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

Programming in the Small II: Control

CS 251 Intermediate Programming GUIs: Event Listeners

CSE 331. Event- driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Class 16: The Swing Event Model

Module 4 Multi threaded Programming, Event Handling. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Event Driven Programming

Java Foundations John Lewis Peter DePasquale Joe Chase Third Edition

10/16/2008. CSG 170 Round 5. Prof. Timothy Bickmore. User Analysis Task Analysis (6) Problem Scenarios (3)

G51PRG: Introduction to Programming Second semester Applets and graphics

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events

Introduction p. 1 JFC Architecture p. 5 Introduction to JFC p. 7 The JFC 1.2 Extension p. 8 Swing p. 9 Drag and Drop p. 16 Accessibility p.

Lecture 19 GUI Events

TYPES OF INTERACTORS Prasun Dewan Department of Computer Science University of North Carolina at Chapel Hill

CS11 Java. Fall Lecture 4

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

Java IDE Programming-I

Basics of programming 3. Java GUI and SWING

CSE 331 Software Design & Implementation

GUI Software Architecture

Swing/GUI Cheat Sheet

Programming graphics

Appendix G Navigation and Collision Detection for Web-Based 3D Experiment

Table of Contents. Chapter 1 Getting Started with Java SE 7 1. Chapter 2 Exploring Class Members in Java 15. iii. Introduction of Java SE 7...

Graphical User Interface (GUI)

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Java GUI Design: the Basics

PESIT Bangalore South Campus

Contents Chapter 1 Introduction to Programming and the Java Language

COSC 123 Computer Creativity. Graphics and Events. Dr. Ramon Lawrence University of British Columbia Okanagan

JList. Displays a series of items The user can select one or more items Class JList extends directly class Jcomponent Class Jlist supports

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components

The init() Method. Browser Calling Applet Methods

Interacción con GUIs

Programming Languages and Techniques (CIS120)

UI Software Organization

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

Cheng, CSE870. More Frameworks. Overview. Recap on OOP. Acknowledgements:

Graphical User Interface (GUI)

(Incomplete) History of GUIs

COMPSCI 230. Software Design and Construction. Swing

Chapter 17 Creating User Interfaces

JAVA NOTES GRAPHICAL USER INTERFACES

ว ฒนพงศ ส ทธภ กด Java Programming ( )

Programming Mobile Devices J2SE GUI

Swing. By Iqtidar Ali

2010 가을학기부산대학교정보컴퓨터공학부 OVERVIEW OF GUI PROGRAMMING

XML Parsers. Asst. Prof. Dr. Kanda Runapongsa Saikaew Dept. of Computer Engineering Khon Kaen University

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING. A Multithreaded program contains two or more parts that can run concurrently.

CS211 GUI Dynamics. Announcements. Motivation/Overview. Example Revisted

Welcome to CIS 068! 1. GUIs: JAVA Swing 2. (Streams and Files we ll not cover this in this semester, just a review) CIS 068

Programming: You will have 6 files all need to be located in the dir. named PA4:

Advanced Java Programming. Swing. Introduction to Swing. Swing libraries. Eran Werner, Tel-Aviv University Summer, 2005

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Transcription:

GUI Event Handlers (Part II) 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen University 1

Agenda Listener Interfaces and Event Classes How to Handle Combo Box Events How to Write a List Selection Listener How to Write a Key Listener How to Write a Mouse Listener Advanced Swing Components JSlider, JColorChooser, JFileChooser How to Write a Change Listener 2

ActionListener & ActionEvent interface ActionListener { // Invoked when an action occurs. void actionperformed(actionevent e); } Important methods of ActionEvent String getactioncommand(): Returns the command string associated with this action long getwhen(): Returns the timestamp of when this event occurred. 3

ItemListener & ItemEvent interface ItemListener { // Invoked when an item has been selected or deselected void itemstatechanged(itemevent e); } Important methods of ItemEvent Object getitem(): Returns the item affected by the event int getstatechange(): Returns the type of state change (selected or deselected) ItemEvent.SELECTED ItemEvent.DESELECTED 4

ComponentListener interface ComponentListener { // Invoked when the component has been made invisible. void componenthidden(componentevent e) // Invoked when the component's position changes. void componentmoved(componentevent e) // Invoked when the component's size changes. void componentresized(componentevent e) // Invoked when the component has been made visible. void } componentshown(componentevent e) 5

ComponentEvent Class Component getcomponent() Returns the originator of the event Important methods of Component void requestfocus(); void repaint(); int getwidth(); int getheight(); int getx(); int gety(); 6

How to Handle Combo Box Events Define a listener class that implements ActionListener Perform type casting from ActionEvent to JComboBox Implement handling method public void actionperformed(actionevent e) {...} JComboBox cb = (JComboBox)e.getSource(); Use getselecteditem to find out which item is selected String selecteditem = (String)cb.getSelectedItem(); 7

ComboBoxDemo (1/2) 8

ComboBoxDemo (2/2) 9

How to Write a List Selection Listener List selection events occur when the selection in a list or table is either changing or has just changed List selection events are fired from an object that implements the ListSelectionModel interface To get a table's list selection model object, you can use either getselectionmodel method or getcolumnmodel().getselectionmodel(). 10

Detecting Selection To detect list selection events, you register a listener on the list selection model object The JList class also gives you the option of registering a listener on the list itself, rather than directly on the list selection model Selection mode single selection mode single interval selection mode multiple interval selection mode 11

ListSelectionModel This interface represents the current state of the selection for any of the components that display a list of values with stable indices The selection is modeled as a set of intervals, each interval represents a contiguous range of selected list elements. The isadjusting flag is true if the user is still manipulating the selection, and false if the user has finished changing the selection. 12

ListSelectionModel & ListSelectionInterface ListSelectionModel addlistselectionlistener(listselectionlistener x) Add a listener to the list that's notified each time a change to the selection occurs. interface ListSelectionListener { // Called whenever the value of the selection changes. public void valuechanged(listselectionevent e); } 13

ListSelectionEvent Important methods of ListSelectionEvent class int getfirstindex(); int getlastindex(); Returns the index of the first row whose selection may have changed. boolean Returns the index of the last row whose selection may have changed. getvalueisadjusting(); Returns whether or not this is one in a series of multiple events, where changes are still being made. 14

JListDemoV2 15

JListDemoV3 (1/4) 16

JListDemoV3 (2/4) 17

JListDemoV3 (3/4) 18

JListDemoV3 (4/4) 19

JListDemoV3 Output 20

Key Events Key events indicate when the user is typing at the keyboard Specifically, key events are fired by the component with the keyboard focus when the user presses or releases keyboard keys Notifications are sent about two basic kinds of key events: The typing of a Unicode character (key typed) The pressing or releasing of a key on the keyboard 21 (key pressed or key released)

Firing Keyboard Events To fire keyboard events, a component must have the keyboard focus Make sure the component's isfocusable method returns true setfocusable(true) method on the component. Make sure the component requests the focus when appropriate For custom components, implement a mouse listener that calls the requestfocusinwindow method when the component is clicked. 22

KeyListener void Invoked when a key has been pressed. void keyreleased(keyevent e) Invoked when a key has been released. void keypressed(keyevent e) keytyped(keyevent e) Invoked when a key has been typed. 23

KeyEvent int getkeycode() Returns the integer keycode associated with the key in this event or VK_UNDEFINED (for a key typed event) char getkeychar() Returns the character associated with the key in this event For example, the KEY_TYPED event for shift + "a" returns the value for "A" 24

KeyEventDemo Example It consists of a text field that you can type into, followed by a text area that displays a message every time the text field fires a key event Type a lowercase 'a' by pressing and releasing the A key on the keyboard The text field fires three events: a key pressed event, a key typed event, and a key released event Type an uppercase 'A' by pressing the Shift and A keys. You'll see the following events, although perhaps not in this order: key pressed (Shift), key pressed (A), key typed ('A'), key 25 released (A), key released (Shift)

KeyEventDemo (1/4) 26

KeyEventDemo (2/4) 27

KeyEventDemo (3/4) 28

KeyEventDemo (4/4) 29

Mouse Events Mouse events occur when the cursor enters or exits a component's onscreen area and when the user presses or releases one of the mouse buttons Tracking the cursor's motion involves significantly more system overhead than tracking other mouse events That is why mouse motion events are separated into Mouse Motion listener type To track mouse wheel events, you can register 30 a mouse wheel listener

MouseListener Interface void Invoked when the mouse enters a component. Invoked when the mouse exits a component. void mousepressed(mouseevent e) mouseentered(mouseevent e) void mouseexited(mouseevent e) Invoked when the mouse button has been clicked (pressed and released) on a component void mouseclicked(mouseevent e) Invoked when a mouse button has been pressed on a component. void mousereleased(mouseevent e) Invoked when a mouse button has been released on a component. 31

MouseEvent int Returns the horizontal x position of the event relative to the source component int gety() getx() int Returns the vertical y position of the event relative to the source component. getclickcount() Returns the number of mouse clicks associated with this event. 32

MouseEventDemo (1/3) 33

MouseEventDemo (2/3) 34

MouseEventDemo (3/3) 35

JSlider A JSlider component is intended to let the user easily enter a numeric value bounded by a minimum and maximum value By default, spacing for major and minor tick marks is zero To see tick marks, set the spacing for either major or minor tick marks (or both) to a non zero value and call the setpaintticks(true) method. To display standard, numeric labels at major tick mark locations, set the major tick spacing, then call the 36 setpaintlabels(true) method

JSlider Examples The second slider is decorated with ticks The third one is decorated with labels It s possible for a single slider to have both types of decorations 37

JSlider Constructors public JSlider(int minimum, int maximum, int value) The most commonly used constructor The first and second parameters are the start and end of the range of values for the slider The third parameter is its initial value when it first appears on the screen If the parameters are omitted, the values 0, 100, and 50 are used 38

JSlider Important Methods By default, a slider is horizontal, but you can make it vertical by calling its method setorientation(jslider.vertical) The current value of a JSlider can be read at any time with its getvalue() method, which returns a value of type int If you want to change the value, you can do so with the method setvalue(n), which takes a parameter of type int 39

JSliderDemo 40

JSliderDemoV2 41

ChangeListener When you move the slider's knob, the statechanged method of the slider's ChangeListener is called ChangeListener is in package javax.swing.event Several Swing components rely on change events for basic functionality sliders, color choosers and spinners 42

ChangeListener & ChangeEvent interface ChangeListener { // Called when the listened to component changes state. void statechanged(changeevent) } Important methods of ChangeEvent int getvalue(): To get the value of the slider String getname(): To get the name of the slider void setname(string s): To set the name of the slider 43

JSliderDemoV3 44

Dialogs A Dialog window is an independent subwindow meant to carry temporary notice apart from the main Swing Application Window Most Dialogs present an error message or warning to a user Dialogs can present images, directory trees, or just about anything compatible with the main Swing Application that manages them 45

Classes for Creating Dialogs To create simple, standard dialogs, you use the JOptionPane class The ProgressMonitor class can put up a dialog that shows the progress of an operation Two other classes, JColorChooser and JFileChooser, also supply standard dialogs To create a custom dialog, use the JDialog class directly 46

JDialog Class The JDialog class is very similar to JFrame and is used in much the same way Like a frame, a dialog box is a separate window Unlike a frame, however, a dialog is not completely independent Every dialog is associated with a frame (or another dialog), which is called its parent window If the parent is closed, the dialog box will also be47 closed

Modal or Modeless Dialog boxes can be either modal or modeless When a modal dialog is created, its parent frame is blocked The user will not be able to interact with the parent until the dialog box is closed In practice, modal dialog boxes are easier to use and are much more common than modeless dialogs 48

JColorChooser JColorChooser is a subclass of JDialog Use the JColorChooser class to provide users with a palette of colors to choose from A color chooser is a component that you can place anywhere within your program GUI The JColorChooser API also makes it easy to bring up a dialog (modal or not) that contains a color chooser. 49

ColorChooserDemo (1/2) 50

ColorChooserDemo (2/2) 51

ColorChooserDemo Output 52

ColorChooserDemoV2 Set both background and foreground colors 53

FileChooser File choosers provide a GUI for navigating the file system Choosing a file or directory from a list Entering the name of a file or directory To display a file chooser, you usually use the JFileChooser API to show a modal dialog containing the file chooser Another way to present a file chooser is to add an instance of JFileChooser to a container 54

JFileChooser A JFileChooser is a dialog to select a file or files The return value of the three methods is one of the following: 1. JFileChooser.CANCEL_OPTION, if the user clicks Cancel 2. JFileChooser.APPROVE_OPTION, if the user click an OK/Open/Save button. 3. JFileChooser.ERROR_OPTION, if the user closes the dialog 55

Getting the Chosen File To get the chosen file, call the getselectedfile method on the file chooser The method getselectedfile returns an instance of File You can call other methods on the File object, such as getpath, isdirectory, or exists to obtain information about the file You can also call other methods such as delete and rename to change the file in some way. 56

FileChooserDemo (1/3) 57

FileChooserDemo (2/3) 58

FileChooserDemo (3/3) 59

FileChooserDemo Output 60

References David J. Eck, Introduction to Programming Using Java, Version 5.0, December 2006 http://math.hws.edu/javanotes/ Sun, Writing Event Listeners, http://java.sun.com/docs/books/tutorial/uiswing/even Sun, Using Swing Components, http://java.sun.com/docs/books/tutorial/uiswing/com 61