Java GUI Design: the Basics

Similar documents
CS 251 Intermediate Programming GUIs: Event Listeners

Event Driven Programming

PIC 20A GUI with swing

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

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

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

Graphical User Interfaces 2

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

Graphical User Interfaces 2

CS 251 Intermediate Programming GUIs: Components and Layout

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

Graphical User Interfaces 2

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

Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

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

Introduction to the JAVA UI classes Advanced HCI IAT351

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!

Lecture 5: Java Graphics

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

Graphical User Interface (GUI)

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

Lecture 3: Java Graphics & Events

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

CSE 331 Software Design & Implementation

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

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

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

COMPSCI 230. Software Design and Construction. Swing

AP CS Unit 11: Graphics and Events

Window Interfaces Using Swing Objects

(listener)... MouseListener, ActionLister. (adapter)... MouseAdapter, ActionAdapter. java.awt AWT Abstract Window Toolkit GUI

Class 16: The Swing Event Model

Window Interfaces Using Swing Objects

Lecture 19 GUI Events

BASICS OF GRAPHICAL APPS

Dr. Hikmat A. M. AbdelJaber

GUI Software Architecture

Java: Graphical User Interfaces (GUI)

The AWT Event Model 9

Graphical User Interfaces. Comp 152

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

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau

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

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski

AP Computer Science Unit 13. Still More Graphics and Animation.

Swing from A to Z Some Simple Components. Preface

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University

Unit 7: Event driven programming

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

GUI Event Handlers (Part I)

Java Foundations John Lewis Peter DePasquale Joe Chase Third Edition

G51PRG: Introduction to Programming Second semester Applets and graphics

Graphical User Interface (GUI)

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

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons

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

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

3 Combining Widgets to create Graphical User Interfaces

Java Interfaces Part 1 - Events Version 1.1

Graphics User Defined Forms, Part I

UI Software Organization

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

Programming graphics

GUI Forms and Events, Part II

Graphical User Interface

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

2IS45 Programming

CS Exam 1 Review Suggestions

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

Assignment 1. Application Development

GUI Event Handlers (Part II)

SD Module-1 Advanced JAVA

Lecture (06) Java Forms

SD Module-1 Advanced JAVA. Assignment No. 4

14.2 Java s New Nimbus Look-and-Feel 551 Sample GUI: The SwingSet3 Demo Application As an example of a GUI, consider Fig. 14.1, which shows the SwingS

Example: Building a Java GUI

DEMYSTIFYING PROGRAMMING: CHAPTER FOUR

Systems Programming Graphical User Interfaces

Packages: Putting Classes Together

Graphical User Interfaces (GUIs)

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

Computer Science 210: Data Structures. Intro to Java Graphics

Input (part 2: input models)

AP CS Unit 12: Drawing and Mouse Events

Summary. Section 14.1 Introduction. Section 14.2 Java s New Nimbus Look-and-Feel. 618 Chapter 14 GUI Components: Part 1

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords

DEMYSTIFYING PROGRAMMING: CHAPTER SIX METHODS (TOC DETAILED) CHAPTER SIX: METHODS 1

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Java IDE Programming-I

PIC 20A Anonymous classes, Lambda Expressions, and Functional Programming

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

Example: Building a Java GUI

Introduction to GUIs. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2014

MIT AITI Swing Event Model Lecture 17

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology:

Graphical interfaces & event-driven programming

GUI Components: Part 1

Come & Join Us at VUSTUDENTS.net

Transcription:

Java GUI Design: the Basics Daniel Brady July 25, 2014 What is a GUI? A GUI is a graphical user interface, of course. What is a graphical user interface? A graphical user interface is simply a visual way of interacting with a computer. The desktop environment you are using right now to read this PDF is has GUI. The PDF viewer you are using to read this has a GUI. Basically, anything interactive that can be displayed on a screen is a GUI; technically, even a simple terminal or command prompt is a GUI. This document will introduce you to creating these types of applications in the Java programming language. How is designing a GUI dierent from designing a traditional application? GUIs are a dierent type of application from non-graphical programs, in that they do not 'ow' in the same ways. Traditional programs have a distinct beginning and end, a logical (if not always clear) path that can be (and is) followed once they are executed, and that path is dened by the code that was written. Graphical user interfaces, however, are event-driven programs and, as such, seemingly control themselves as opposed to following a predened path. This is true, in a sense: the code you write for a GUI is not designed to be executed in a predetermined order, but rather is intended to allow for almost arbitrary execution based on external (and sometimes, internal) events. It's like you're trying to speak to me, I know it. `Event-driven'? `Arbitrary execution'? I don't know what any of this means! Fear not, young programmer 1. Wisdom will come with experience. For now, let us start with the essentials. 1`Young' in the sense of knowledge, not age. 1

There are two types of GUI elements: 1 the essentials 1. Components: Components are elementary GUI entities (such as JButton, JLabel, and JTextField). 2. Containers: Containers (such as JFrame, JPanel, and JDialog) are used to hold components in a specic layout; a container can also contain other containers. For the purpose of creating graphical user interfaces in Java, we will be using the Java Swing and AWT graphics APIs. In a GUI program, every component must be held within a container. That container must be identied in some way, such that its add(jcomponent c) method can be called to add a component to itself. 1 JFrame frame = new JFrame ( " I yam a frame " ); 2 J P a n e l panel = new J P a n e l () ; 3 frame. add ( panel ); 4 JButton button = new JButton ( " I yam a button " ); 5 panel. add ( button ); 1.1 the frame The purpose of a GUI is to make it easier to interact with a computer. We've 2 found that visual aids tend to help this process. As such, GUIs are displayed on a screen. To separate one GUI from another, the graphical components of any given application 3 are placed inside a window, or frame. The frame of an application is the component of the GUI that typically contains the minimize-maximize-close buttons, as well as text displaying some title. Many frames often have menubars associated with them, with menus such as `File' and `Edit'. To create such a frame, you have two options: Create an instance of the javax.swing.jframe class Create a class which extends javax.swing.jframe, and create an instance of that class The rst option is best if you don't need to do anything to fancy or complicated and a generic JFrame will do what you want. 2 Not me. 3 In this document, `application' is used to refer to programs with GUIs, for the sake of brevity. It would be more accurate to say that an application has a GUI, but I don't want to. 2

1 // ---- Option 1 - - - -\\ 2 JFrame frame = new JFrame ( " A title for the title bar." ); The second is better if you will be doing a lot of customization to your frame. 1 // ---- Option 2 - - - -\\ 2 public c l a s s M y F r a m e extends J F r a m e { 3 //... 4 public s t a t i c void main ( S t r i n g [] args ) { 5 M y F r a m e frame = new M y F r a m e () ; 6 //... 7 } 8 } Once you have a frame, you can start thinking about setting up its behavior. Should the program exit when you close the frame? How big should the frame be? Should the user be able to resize it? These are questions you can provide answers to by modifying various attributes of your frame. Note: The order in which you set up the frame and its components can sometimes aect the behavior of your GUI. Unless you have a reason, you should apply frame settings last, after all of its components have been set up. 1 // ---- General frame settings - - - -\\ 2 frame. setdefaultcloseoperation ( J F r a m e. E X I T _ O N _ C L O S E ); 3 // exit the program when window is closed 4 frame. setsize ( 300, 400 ); 5 // set the width and height of the window 6 frame. setresizable ( f a l s e ); 7 // don ' t allow resizing once the frame has been created 8 frame. setvisible ( true ); 9 // make the frame visible ( and interactive!) to the user 3

If you are creating your own custom frame, you can congure these settings within the constructor of your frame instead, giving your frame a set of default behaviors should the user choose not to provide any. Once you've gotten your frame congured, it's time to start worrying about the content of that frame. 1.2 the canvas When a graphical component is rendered to the screen, it said to have been `drawn' or `painted' there. As such, the component onto which other components are `drawn' is referred to as a canvas. Another way to think about it is to consider the canvas a container, a place to hold and organize all the various components of your GUI. No matter how you visualize it, in Java GUIs the most commonly used such component is the javax.swing.jpanel. Every JFrame has exactly one container in which to organize its components. You can access this container via the getcontentpane method, and there are two ways you can handle it once you have it. 1 // ---- Option 1: treat as a generic java. awt. Container - - - -\\ 2 C o n t a i n e r contentcontainer = frame. getcontentpane ( ) ; 3 // retrieve and store the current content pane of the specified frame 4 // as a generic Container 5 // ---- Option 2: treat as a javax. swing. JPanel - - - -\\ 6 JPanel contentpanel = ( JPanel ) ^\ footnote { The \ texttt { getcontentpane } method of \ texttt { JFrame } actually returns a \ texttt { JPanel } as generic \ texttt { Container }, and so to treat it as a \ texttt { JPanel } it must be cast as such.}^ frame. getcontentpane ( ) ; 7 // retrieve and store the current content pane of the specified frame 8 // as a JPanel An alternative to dealing with the default content pane is to set the content pane to a JPanel of your choice via JFrame's setcontentpane method. 1 J P a n e l content = new J P a n e l () ; 2 frame. setcontentpane ( content ) ; Once you have your frame and canvas all set up, it's time to start adding the more exciting components of your GUI to your canvas! 1 content.add( somecomponent ) ; Keep in mind: the order in which you add components to the canvas matters, and the exact reasons why it matters are discussed later, in section 1.4 on layout managers. 4

1.3 the components The Java Swing and AWT packages provide many ready-made and reusable GUI components; the three that I will discuss here are some of the most commonly used: JButton, JLabel, and JTextField. There are three steps that are necessary to create and place a GUI component: 1. Declare the component, using a valid identier: 1 J B u t t o n button ; 2. Construct the component by invoking an appropriate constructor. 1 button = new JButton ( " I yam a button " ); 3. Identify the container (such as a JPanel) to hold the component. The container can then add the component onto itself via its add(jcomponent c) method. Every container has such a method. Take note that the container adds the component to itself: the component does not add the container as its parent. 1 J P a n e l container = new J P a n e l () ; 2 container. add( button ) ; If the component you are creating is never going to be used after creation (often this is the case when creating labels), then it is appropriate to simply add an anonymous instance of that component to a container instead of saving it away in a variable that will never be used again. 1 container. add ( new JLabel ( " WE ARE ANONYMOUS." ) ); 1.3.1 the JButton A javax.swing.jbutton is a GUI component that triggers a certain pre-programmed action when clicked or otherwise activated by the user. The JButton has ve constructors, only four of which are commonly used. The no-arg constructor simply creates a blank button; another takes a String to use as display text; one takes an Icon to use instead of text; and yet another takes both a String and an Icon to use when displaying the button. 5

1 public J B u t t o n () ; 2 // Creates a button with no set text or icon. 3 public J B u t t o n ( S t r i n g text ); 4 // Creates a button with text. 5 public J B u t t o n ( Icon img ); 6 // Creates a button with an icon. 7 public J B u t t o n ( S t r i n g text, Icon img ); 8 // Creates a button with initial text and an icon. JButtons have various getters and setters associated with their commonly used attributes, such as gettext and seticon. But they can also be programmatically enabled or disabled, using the setenabled(boolean b) method. 1.3.2 the JLabel A javax.swing.jlabel provides a GUI component for rendering a short text string or an image, or both. Take note: System.out.print prints to the console, not to the screen of a GUI! JLabels are often used to label other components (such as a JTextField) or provide a text description. Similar to JButtons, there are many constructors for the JLabel. By default, JLabels are vertically centered in their display area, but you can specify where in the label's display are the label's contents are aligned by setting the vertical and horizontal alignment. You can also specify the position of the text relative to the image. 1 public J L a b e l () ; 2 // Creates a label with no image and with an empty 3 // string for the title. 4 public J L a b e l ( S t r i n g text ); 5 // Creates a label with the specified text. 6 public J L a b e l ( Icon img ); 7 // Creates a label with the specified image. 8 p u b l i c J L a b e l ( S t r i n g text, Icon img, i n t horizontalalignment ); 9 // Creates a label with the specified text, image, 10 // and horizontal alignment ( one of : LEFT, CENTER, RIGHT, LEADING or 11 // TRAILING, defined in javax. swing. SwingConstants ) The gettext and settext methods can be used to read and modify the Label's text. Similarly, the getalignment and setalignment methods can be used to retrieve and modify the alignment of the text. 6

1.3.3 the JTextField The javax.swing.jtextfield is a lightweight component that allows the editing of a single line of text. 4 Hitting the ENTER key while focused on a JTextField object will re an ActionEvent if the object is registered to any ActionListeners. 5 1 public J T e x t F i e l d ( i n t columns ); 2 // Constructs a new empty TextField with the specified number of 3 // columns. 4 public J T e x t F i e l d ( S t r i n g text ); 5 // Constructs a new TextField initialized with the specified text. 6 public J T e x t F i e l d ( S t r i n g text, i n t columns ); 7 // Constructs a new TextField initialized with the specified text 8 // and columns. As with other textual GUI components, the gettext and settext methods can be used to read and modify the text shown in a JTextField. Take note, however, that these methods work with Strings: if you are trying to insert any other data type, say a number, then that value must rst be converted to a String before calling gettext / settext. 1.4 layout managers TO BE WRITTEN 4 A JTextArea can be used if multiple lines of displayed and editable text are desired. 5 For information on and examples of using text elds see How to Use Text Fields in The Java Tutorial. 7

1.5 fully-worked example 1 import javax. swing.*; 2 3 public c l a s s M y s t e r y G u i extends J F r a m e { 4 // ---- Class and instance variables - - - -\\ 5 6 J P a n e l content ; 7 8 // ---- Constructors - - - -\\ 9 10 public M y s t e r y G u i () { 11 // Create and add the content pane. 12 content = new J P a n e l () ; 13 t h i s. setcontentpane ( content ); 14 15 // Create and add the mystery labels. 16 content. add ( new J L a b e l ( "I am mystery," ) ); 17 content. add ( new JLabel ( " a wonderous sight to see " ) ); 18 content. add ( new JLabel ( " on a night like this." ) ); 19 20 // General frame settings. 21 settitle ( " Haiku " ); 22 setdefaultcloseoperation ( J F r a m e. E X I T _ O N _ C L O S E ); 23 setsize ( 200, 110 ); 24 setlocationrelativeto ( n u l l ); 25 // a handy way of centering the frame on - screen 26 setvisible ( true ); 27 } 28 29 // - - - - - - - - - - - - - - - - - - - - - - - - -\\ 30 public s t a t i c void main ( S t r i n g [] args ) { 31 new M y s t e r y G u i () ; 32 } 33 } 8

2 event-driven programming The short story below can be used to illustrate the idea of event-driven programming. Event-driven programming is a programming paradigm in which the ow of the program is determined by eventsi.e., user actions such as mouse clicks and key presses. You're on a train: you don't know where that train is headed, but you know where you hope to end up. You arrive at the train station; stepping o of the train, you discover it is not your nal destination. You can choose get back on the same train, or try another line, but until you decide your journey has come to a halt. You decide get back on the train you just left, and it promptly whisks you away on the next leg of your journey. Strangely, the scenery you pass seems identical to the scenery you saw the last time you were on this train; indeed, looking ahead you can see the exact same train station you just left. Determined to be more prepared next time, you pull out your map and have a good look: there are so many routes that at rst it is hard to nd where you are. You arrive at the train station; stepping o of the train, you discover it is not your nal destination. You can choose get back on the same train, or try another line, but until you decide your journey has come to a halt. This time you decide to try a dierent line, and, crossing the station, you quickly board another train. Once again, as if it had been waiting for you, the train takes o as soon as you step onboard, nearly causing you to fall over. You manage to make it to your seat, and settle in for the ride. But just as you start to take notice of the wonderfully new scenery passing by, you feel the train start to slow: the next stop is coming up fast. You arrive at the train station; stepping o the train, you discover... Graphical user interfaces and other applications that are centered around performing certain actions in response to user input tend to follow the event-driven paradigm, and Java GUIs are no exception. In an event-driven application, there is generally a main loop that listens for events, triggering a piece of event-handling code when one of those events is detected. This behavior is unlike the more traditional procedural approach we are familiar with, in which programs are implemented in terms of explicit, sequential steps. Bits and pieces (the bodies of event-handlers and other methods) still execute sequentially, but the order in which these methods are called is determined by the order in which particular events occur. 9

Three objects are involved in the event-handling process: a source the listener(s) an event The source object (e.g. a JButton) interacts with the user. When triggered, it creates an event object. This event object is sent to all of the registered listener objects, and an appropriate event-handler method of the listener(s) is invoked upon it. Interested parties must rst register themselves with the source as active listeners of events before they can receive news of such things; without registration, the source has no idea that anybody is interested in the news it carries, and becomes sad and lonely. You can think of this relationship like that of a magazine or newspaper subscription: rst you subscribe to the distributor, and then anything they publish will get sent to you. This is a perfect example of the Observer design pattern, discussed in chapter 2 of Head First Design Patterns. When creating GUIs in Java, there are three major types of events 6 that you need to know how to handle: ActionEvents, KeyEvents, and MouseEvents. 2.1 ActionEvents and the ActionListener interface ActionEvents are versatile, meaningful events which indicate that a component-dened action has occurred. For example, if a JButton is pressed, or the user types ENTER in a JTextField, an ActionEvent is created and sent out to any one who is listening. Because of their behavior as a representative of a generic 'action' occurring, ActionEvent is the most commonly extended event class when creating your own types of events. Objects which are interested in listening and handling ActionEvents must implement the ActionListener interface. 1 // ---- ActionListener interface - - - -\\ 2 public i n t e r f a c e A c t i o n L i s t e n e r { 3 p u b l i c void actionperformed ( A c t i o n E v e n t e ) ; 4 // Invoked when an action occurs. 5 } Furthermore, these listeners must be registered with the source (of the desired events) via the source's addactionlistener method. 6 Located in the java.awt.event package 10

There are two common ways of creating and registering event-listeners: 1. add an instance of the EventListener class itself 2. add an instance of a user-dened EventListener class 1 // ---- Option 1: generic listener - - - -\\ 2 source. addactionlistener ( new A c t i o n L i s t e n e r () { 3 @Override 7 4 p u b l i c void actionperformed ( A c t i o n E v e n t e ) { 5 // Handle the action. 6 //... 7 } 8 } ) ; 9 10 // ---- Option 2: custom listener - - - -\\ 11 source. addactionlistener ( new F r A ct i o n L i st e n e r () ) ; Here's an example of a simple listener which keeps track of and reports how many times it has received an ActionEvent: 1 import java. awt. event. A c t i o n E v e n t ; 2 import java. awt. event. A c t i o n L i s t e n e r ; 3 public c l a s s A c t i o n T r a c k e r implements A c t i o n L i s t e n e r { 4 // ---- Class and instance variables - - - -\\ 5 6 i n t count ; // initialized to 0 by default 7 8 // ---- Utility methods - - - -\\ 9 10 /* * 11 * Records and reports how many times an action has occurred. 12 */ 13 @ Override 14 p u b l i c void actionperformed ( A c t i o n E v e n t e ) { 15 count ++; 16 System. out. println ( count + ( count == 1? 17 " action has occurred." 18 : " actions have occurred." ) 19 ); 20 } 21 } 7 An annotation used to convey the intention of the programmer to override an inherited method. See this tutorial on Java Annotations for more details. 11

2.2 KeyEvents and the KeyListener interface A KeyEvent is an event that is red when a keystroke occurs in a component. This event is generated by a component when a key is pressed, released, or typed. Following the Observer pattern, the event is then passed to every KeyListener object registered to receive such events, using the component's addkeylistener method. 1 // ---- KeyListener interface - - - -\\ 2 public i n t e r f a c e K e y L i s t e n e r { 3 public void keypressed ( K e y E v e n t e ) ; 4 // Invoked when a key has been pressed. 5 public void keyreleased ( K e y E v e n t e ) ; 6 // Invoked when a key has been released. 7 public void keytyped ( K e y E v e n t e ) ; 8 // Invoked when a key has been typed. 9 } There is an important dierence between the events generated by keypressed / keyreleased methods and the keytyped method, outlined in detail in the documentation on KeyEvents. To summarize, `key typed' events are not red simply when the component registers a backto-back press-and-release (like the mouseclicked method described below does); rather, a `key typed' event will typically occur when a valid Unicode character is entered. The dierence here is subtle, but it is there: many valid characters are entered via a series of key-presses (`Shift' + `a', for example), and therefore deserve to be recognized by a single event. As a result, `key pressed' and `key released' events are low-level events, meaning they depend on the particular platform and keyboard layout used to generate the event and are therefore the only way to nd out about keys that don't generate character input (e.g. `Shift', `Ctrl', etc.). `Key typed' events are higher-level, platform and keyboard independent, but cannot detect such key-presses. Below is an excellent example that highlights the dierence between these three events. For this EventListener, I have provided an example of a main method in which the listener might be used. This is a complete GUI. 12

1 import javax. swing.*; 2 import java. awt.*; 3 import java. awt. event.*; 4 public class K e y T r a c k e r implements K e y L i s t e n e r { 5 6 // ---- Utility methods - - - -\\ 7 8 @Override 9 public void keypressed ( K e y E v e n t e ) { 10 System. out. println ( " KEY PRESSED EVENT \ n =================\ n" 11 + "\ tkey description : " 12 + KeyEvent. getkeytext ( e. getkeycode () ) 13 + "\ n\ tkey character : " 14 + e. getkeychar () 15 ); 16 } 17 18 @Override 19 public void keyreleased ( K e y E v e n t e ) { 20 System. out. println ( " KEY RELEASED EVENT \ n ==================\ n" 21 + "\ tkey description : " 22 + KeyEvent. getkeytext ( e. getkeycode () ) 23 + "\ n\ tkey character : " 24 + e. getkeychar () 25 ); 26 S y s t e m. out. println () ; 27 S y s t e m. out. println () ; 28 } 29 30 @Override 31 public void keytyped ( K e y E v e n t e ) { 32 System. out. println ( " KEY TYPED EVENT \ n ===============\ n" 33 // The getkeycode () method of a key - typed event 34 // always returns VK_UNDEFINED. 35 + "\ tkey description : " 36 + KeyEvent. getkeytext ( e. getkeycode () ) 37 + "\ n\ tkey character : " 38 + e. getkeychar () 39 ); 40 } 41 42 public static void main ( S t r i n g [] args ) { 43 JFrame frame = new JFrame ( " KEY TEST " ); 44 JPanel content = new JPanel () ; 45 frame. setcontentpane ( content ); 46 47 JTextField tfinput = new JTextField ( 9 ); // space for >= 9 chars 48 tfinput. addkeylistener ( new KeyTracker () ); 49 content. add ( tfinput ); 50 51 frame. setdefaultcloseoperation ( JFrame. EXIT_ON_CLOSE ); 52 frame. setsize ( 200, 75 ); 53 frame. setlocationrelativeto ( null ); // center frame on - screen 54 frame. setvisible ( true ); 55 } 56 } 13

2.3 MouseEvents and the MouseListener interface MouseEvents are generated to indicate that a mouse action 8 has occurred in a component; this is considered to be the case if and only if the mouse cursor is over a visible (unobscured by another component) part of the component's bounds when the action happens. And just like with all events, a generated MouseEvent is sent to any listeners that have registered with the source as interested MouseListeners. 1 // ---- MouseListener interface - - - -\\ 2 public i n t e r f a c e M o u s e L i s t e n e r { 3 p u b l i c void mousepressed ( M o u s e E v e n t evt ) ; 4 // Invoked when the mouse button has been pressed 5 p u b l i c void mousereleased ( M o u s e E v e n t evt ) ; 6 // Invoked when the mouse button has been released 7 p u b l i c void mouseclicked ( M o u s e E v e n t evt ) ; 8 // Invoked when the mouse button has been clicked ( pressed and 9 // released ) 10 p u b l i c void mouseentered ( M o u s e E v e n t evt ) ; 11 // Invoked when mouse cursor has entered the unobscured bounds 12 // of a component 13 p u b l i c void mouseexited ( M o u s e E v e n t evt ) ; 14 // Invoked when mouse cursor has exited the unobscured bounds 15 // of a component 16 } The next example is a long one, as a direct result of the amount of methods being implemented, but hopefully it is quite clear. Once again, the example is a fully-working GUI, and can be executed directly. 8 A closely related (and, in fact, subclass) of the MouseEvent is the MouseWheelEvent, generated in response to scrolling the wheel of the mouse. It has its own EventListener, the MouseWheelListener. 14

1 import javax. swing.*; 2 import java. awt.*; 3 import java. awt. event.*; 4 public class M o u s e T r a c k e r implements M o u s e L i s t e n e r { 5 6 // ---- Utility methods - - - -\\ 7 8 @Override 9 public void mousepressed ( M o u s e E v e n t e ) { 10 S t r i n g button ; 11 switch ( e. getbutton () ) { 12 case MouseEvent. BUTTON1 : 13 button = " LEFT "; 14 break; 15 case MouseEvent. BUTTON2 : 16 button = " MIDDLE "; 17 break; 18 case MouseEvent. BUTTON3 : 19 button = " RIGHT "; 20 break; 21 default : 22 button = ""; 23 break; 24 } 25 System. out. println ( " The " + button + " mouse button has been PRESSED @point \ n" 26 + "\ t( relative to the source ): " 27 + "[" + e. getx () + ", " + e. gety () + " ]\ n" 28 + "\ t( relative to the screen ): " 29 + "[" + e. getxonscreen () + ", " + e. getyonscreen () + " ]\ n" 30 ); 31 } 32 33 34 @Override 35 public void mousereleased ( M o u s e E v e n t e ) { 36 S t r i n g button ; 37 switch ( e. getbutton () ) { 38 case MouseEvent. NOBUTTON : 39 button = " invisible "; 40 break; 41 case MouseEvent. BUTTON1 : 42 button = " LEFT "; 43 break; 44 case MouseEvent. BUTTON2 : 45 button = " MIDDLE "; 46 break; 47 case MouseEvent. BUTTON3 : 48 button = " RIGHT "; 49 break; 50 default : 51 button = ""; 52 break; 53 } 54 System. out. println ( " The " + button + " mouse button has been RELEASED @point \ n" 55 + "\ t( relative to the source ): " 56 + "[" + e. getx () + ", " + e. gety () + " ]\ n" 57 + "\ t( relative to the screen ): " 58 + "[" + e. getxonscreen () + ", " + e. getyonscreen () + " ]\ n" 59 ); 60 } 61 62 15

63 64 @Override 65 public void mouseclicked ( M o u s e E v e n t e ) { 66 S t r i n g button ; 67 switch ( e. getbutton () ) { 68 case MouseEvent. NOBUTTON : 69 button = " invisible "; 70 break; 71 case MouseEvent. BUTTON1 : 72 button = " LEFT "; 73 break; 74 case MouseEvent. BUTTON2 : 75 button = " MIDDLE "; 76 break; 77 case MouseEvent. BUTTON3 : 78 button = " RIGHT "; 79 break; 80 default : 81 button = ""; 82 break; 83 } 84 System. out. println ( " The " + button + " mouse button has been CLICKED @point \ n" 85 + "\ t( relative to the source ): " 86 + "[" + e. getx () + ", " + e. gety () + " ]\ n" 87 + "\ t( relative to the screen ): " 88 + "[" + e. getxonscreen () + ", " + e. getyonscreen () + " ]\ n" 89 ); 90 } 91 92 @Override 93 public void mouseentered ( M o u s e E v e n t e ) { 94 System. out. println ( " Mouse ENTERED the source @point \ n" 95 + "\ t( relative to the source ): " 96 + "[" + e. getx () + ", " + e. gety () + " ]\ n" 97 + "\ t( relative to the screen ): " 98 + "[" + e. getxonscreen () + ", " + e. getyonscreen () + " ]\ n" 99 ); 100 } 101 102 @Override 103 public void mouseexited ( M o u s e E v e n t e ) { 104 System. out. println ( " Mouse EXITED the source @point \ n" 105 + "\ t( relative to the source ): " 106 + "[" + e. getx () + ", " + e. gety () + " ]\ n" 107 + "\ t( relative to the screen ): " 108 + "[" + e. getxonscreen () + ", " + e. getyonscreen () + " ]\ n" 109 ); 110 } 111 112 public static void main ( S t r i n g [] args ) { 113 JFrame frame = new JFrame ( " Key test " ); 114 JPanel content = new JPanel () ; 115 frame. setcontentpane ( content ); 116 117 content. addmouselistener ( new MouseTracker () ); 118 119 frame. setdefaultcloseoperation ( JFrame. EXIT_ON_CLOSE ); 120 frame. setsize ( 100, 100 ); 121 frame. setlocationrelativeto ( null ); 122 frame. setvisible ( true ); 123 } 124 } 16

2.4... and the MouseMotionListener interface Very closely related to the MouseListener interface, the MouseMotionListener interface responds to MouseEvents that are generated due to mouse motion or movement. As before, a MouseMotionListener must be registered with a source via the addmousemotionlistener method in order to receive interesting events. 1 // ---- MouseMotionListener interface - - - -\\ 2 public interface M o u s e M o t i o n L i s t e n e r { 3 public void mousedragged ( M o u s e E v e n t e ) ; 4 // Invoked when a mouse button is pressed on a component and then 5 // dragged. 6 public void mousemoved ( M o u s e E v e n t e ) ; 7 // Invoked when the mouse cursor has been moved onto a component 8 // but no buttons have been pushed. 9 } Here is an example that is very similar to the previous one, but provides a GUI that only cares about the motion of the mouse and not its clicks. 1 import javax. swing.*; 2 import java. awt.*; 3 import java. awt. event.*; 4 public class M o u s e M o t i o n T r a c k e r implements M o u s e M o t i o n L i s t e n e r { 5 6 // ---- Utility methods - - - -\\ 7 @Override 8 public void mousedragged ( M o u s e E v e n t e ) { 9 System. out. println ( " The mouse is being DRAGGED, currently @point \ n" 10 + "\ t( relative to the source ): " 11 + "[" + e. getx () + ", " + e. gety () + " ]\ n" 12 + "\ t( relative to the screen ): " 13 + "[" + e. getxonscreen () + ", " + e. getyonscreen () + " ]\ n" 14 ); 15 } 16 17 @Override 18 public void mousemoved ( M o u s e E v e n t e ) { 19 System. out. println ( " The mouse is MOVING, currently @point \ n" 20 + "\ t( relative to the source ): " 21 + "[" + e. getx () + ", " + e. gety () + " ]\ n" 22 + "\ t( relative to the screen ): " 23 + "[" + e. getxonscreen () + ", " + e. getyonscreen () + " ]\ n" 24 ); 25 } 26 27 public static void main ( S t r i n g [] args ) { 28 JFrame frame = new JFrame ( " Key test " ); 29 JPanel content = new JPanel () ; 30 frame. setcontentpane ( content ); 31 32 content. addmousemotionlistener ( new MouseMotionTracker () ); 33 34 frame. setdefaultcloseoperation ( JFrame. EXIT_ON_CLOSE ); 35 frame. setsize ( 100, 100 ); 36 frame. setlocationrelativeto ( null ); 37 frame. setvisible ( true ); 38 } 39 } 17

3 coming up next... I hope you nd this document to be as useful as I intend it to be. Below, you will nd various class diagrams of the Java Swing API, illustrating how they all t together. My next document will provide step-by-step instructions in the creation of Stage 1 of our Tetris game. Happy coding! ~1)aniel 13rady 18

19