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

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

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

GUI Programming in Java:GUI Programming in Java:Event Handling Event Handling

&&More ComponentsMore Components

Corresponds with Chapter 14, Corresponds with Chapter 14, Chapter 15Chapter 15

Event-Driven Event-Driven ProgrammingProgramming

Procedural programmingProcedural programming is executed is executed in procedural order.in procedural order.

In In event-driven programmingevent-driven programming, code is , code is executed upon executed upon activation of eventsactivation of events..

Events and ListenersEvents and Listeners An An eventevent can be defined as a type of signal to the can be defined as a type of signal to the

program that something has happened. program that something has happened.

The event is generated by external user actions The event is generated by external user actions such as mouse movements, mouse button clicks, such as mouse movements, mouse button clicks, and keystrokes, or by the operating system, such and keystrokes, or by the operating system, such as a timer.as a timer.

Events are responded to by event Events are responded to by event listenerslisteners

The Delegation ModelThe Delegation Model

Event-generating Objects send Events to Listener ObjectsEach 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.

source: SourceClass

+addXListener(XListener listener)

listener: ListenerClass User Action

Trigger an event

XListener +handler(XEvent event)

Internal function of the source object

event: XEvent listener1 listener2 … listenern

+handler(XEvent

Register by invoking source.addXListener(listener);

Keep it a list

Invoke listener1.handler(event) listener2.handler(event) … listenern.handler(event)

Event ClassesEvent Classes

We will focus on ActionEvent and ListSelectionEvent

Selected User ActionsSelected User ActionsSource Event Type

User Action Object Generated

Click a button JButton ActionEvent

Click a check box JCheckBox ItemEvent, ActionEvent

Click a radio button JRadioButton ItemEvent, ActionEvent

Press return on a text field JTextField ActionEvent

Select a new item JComboBox ItemEvent, ActionEvent

Select an item from a List JList ListSelectionEvent

Window opened, closed, etc. Window WindowEvent

Mouse pressed, released, etc. Any Component MouseEvent

Key released, pressed, etc. Any Component KeyEvent

Java AWT Event Java AWT Event Listener InterfacesListener InterfacesJava AWT Event Java AWT Event

Listener InterfacesListener Interfaces ActionListenerActionListener AdjustmentListenerAdjustmentListener ComponentListenerComponentListener ContainerListenerContainerListener FocusListenerFocusListener ItemListenerItemListener

KeyListenerKeyListener MouseListenerMouseListener MouseMotionListenerMouseMotionListener TextListenerTextListener WindowListenerWindowListener ListSelectionListenerListSelectionListener

All are in the java.awt.event or javax.swing.event packageAll are in the java.awt.event or javax.swing.event packageAll are derived from EventListener in the java.util packageAll 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 How to Implement a Listener InterfaceInterface

Use the Use the implementsimplements keyword in the class keyword in the class declarationdeclaration

Register the object as a listener for a Register the object as a listener for a component’s event, using the component’s component’s event, using the component’s addaddXXListenerListener method. (where method. (where XX is the type is the type of event). (Typically done in constructor)of event). (Typically done in constructor)

Declare and fully define all methods for the Declare and fully define all methods for the interface that you are implementinginterface that you are implementing Requires:Requires:

Complete method signature Complete method signature Method bodyMethod body

Selected Event HandlersSelected Event Handlers

Event Class Listener Interface Listener Methods (Handlers)ActionEvent ActionListener actionPerformed(ActionEvent)

ItemEvent ItemListener itemStateChanged(ItemEvent)

ListSelection ListSelection valueChangedEvent Listener (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 Alternative Approaches to ListeningListening

Implement the listener with the Implement the listener with the main main application classapplication class, and have the one listener , and have the one listener assigned to all components generating the eventsassigned to all components generating the events This is the approach I generally use with my examplesThis is the approach I generally use with my examples Advantage: simplicity for beginner programmersAdvantage: simplicity for beginner programmers Disadvantage: event-handler method may require if-Disadvantage: event-handler method may require if-

statement or switch with several branches when statement or switch with several branches when multiple components generate the eventmultiple components generate the event

Use Use inner classesinner classes to implement the listeners to implement the listeners and create a different instance as each and create a different instance as each component’s listener.component’s listener. NamedNamed inner class or inner class or anonymousanonymous inner class (This is inner class (This is

the approach used in the textbook most of the time)the approach used in the textbook most of the time) Advantage: no need to test within the listeners for Advantage: no need to test within the listeners for

determining which component sent the event. Each determining which component sent the event. Each component has its own dedicated listenercomponent has its own dedicated listener

Disadvantage: harder to understand for novice Disadvantage: harder to understand for novice programmersprogrammers

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, Working with JLabel, JTextField, JTextArea, JList, JTextField, JTextArea, JList,

JComboBox, and JRadiobuttonJComboBox, and JRadiobutton

Similar topics are covered in Similar topics are covered in Chapter 15, but these Chapter 15, but these examples are my ownexamples are my own

JLabelJLabel

Swing class for a non-editable text Swing class for a non-editable text displaydisplay

Typical constructor:Typical constructor: JLabel(stringValue)JLabel(stringValue)

Other Useful Methods:Other Useful Methods: getText()getText() – returns a string containing – returns a string containing

the text in the label componentthe text in the label component setText(String)setText(String) – sets the label – sets the label

component to contain the string valuecomponent to contain the string value

JTextFieldJTextField Swing class for an editable text displaySwing 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 Will instantiate a text field component of the specified

width (width is approximate number of characters visible).width (width is approximate number of characters visible). Some useful methods:Some useful methods:

getText()getText() – returns the text value in the text field – returns the text value in the text field getSelectedText()getSelectedText() – returns the text value that – returns the text value that

has been highlighted in the text fieldhas been highlighted in the text field setText(stringValue)setText(stringValue) – sets the text value to the – sets the text value to the

indicated argumentindicated argument append(stringvalue)append(stringvalue) – appends the text value of – appends the text value of

the string to the already existing text in the the string to the already existing text in the componentcomponent

JTextAreaJTextArea Swing class for an editable text displaySwing 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 Will instantiate a text area component of the specified width

and height (width is approximate number of characters and height (width is approximate number of characters visible, height is approximate number of text lines visible)visible, height is approximate number of text lines visible)

Some useful methods:Some useful methods: getText()getText() – returns the text value in the text field – returns the text value in the text field getSelectedText()getSelectedText() – returns the text value that has – returns the text value that has

been highlighted in the text fieldbeen highlighted in the text field setText(stringValue)setText(stringValue) – sets the text value to the – sets the text value to the

indicated argumentindicated argument append(stringvalue)append(stringvalue) – appends the text value of the – appends the text value of the

string to the already existing text in the componentstring to the already existing text in the component

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

JListJList Swing GUI component that presents a list of itemsSwing GUI component that presents a list of items Many constructors…here’s one:Many constructors…here’s one:

JList(sourceArray);JList(sourceArray); Produces a Produces a ListSelectionEventListSelectionEvent

Handling this event by implementing a Handling this event by implementing a ListSelectionListenerListSelectionListener Need to import Need to import javax.swing.event javax.swing.event package for thispackage for this

Some useful methods:Some useful methods: addListSelectionListeneraddListSelectionListener – specify which objects will respond to list – specify which objects will respond to list

selection eventselection event setListDatasetListData – indicate the source of data for this list (e.g. an array) – indicate the source of data for this list (e.g. an array) getSelectedIndexgetSelectedIndex – identify the current selection from the list (0- – identify the current selection from the list (0-

based) -- -1 indicates nothing is selected from list.based) -- -1 indicates nothing is selected from list. setFixedCellHeightsetFixedCellHeight and and setFixedCellWidthsetFixedCellWidth – indicate pixel size of – indicate pixel size of

each item of the list.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 usedfor 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

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

Exception HandlingException HandlingException HandlingException Handling

This example makes use of This example makes use of Exception Exception handlinghandling

try/catch format try/catch format

NOTE: if the text entered into the NOTE: if the text entered into the numeric field cannot be parsed into a numeric field cannot be parsed into a number, an Exception is thrown number, an Exception is thrown (specifically a (specifically a NumberFormatExeption).NumberFormatExeption).

Exception Handling Using Exception Handling Using trytry and and catchcatch

Exception Handling Using Exception Handling Using trytry and and catchcatch

try{try{

…………....

}}

catch (ExceptionType e){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

JComboBoxJComboBox Swing GUI component that presents a dropdown list of Swing GUI component that presents a dropdown list of

itemsitems Many constructors…here’s one:Many constructors…here’s one:

JComboBox(sourceArray);JComboBox(sourceArray); Produces an Produces an ActionEventActionEvent and an and an ItemEventItemEvent

You can handle these event by implementing an You can handle these event by implementing an ActionListener ActionListener or an or an ItemListenerItemListener

If you want to handle these events, you need to import If you want to handle these events, you need to import java.awt.event java.awt.event packagepackage

Some useful methods:Some useful methods: getSelectedIndexgetSelectedIndex – identify the current selection from the list – identify the current selection from the list

(0-based) -- -1 indicates nothing is selected from list.(0-based) -- -1 indicates nothing is selected from list. getSelectedItemgetSelectedItem – returns the currently selected object from – returns the currently selected object from

the list. Since it returns an Object reference, if you want to the list. Since it returns an Object reference, if you want to treat it as string, you should call toString() for the returned treat it as string, you should call toString() for the returned objectobject

setSelectedIndexsetSelectedIndex – Changes the current selection to whatever – Changes the current selection to whatever the integer is that is passed as an argument.the integer is that is passed as an argument.

setSelectedItemsetSelectedItem – sets the currently selected item to whatever – sets the currently selected item to whatever the Object is that is passed as an argumentthe Object is that is passed as an argument

JRadioButtonJRadioButton Swing GUI component that presents a radio buttons of options. Swing GUI component that presents a radio buttons of options.

You group the options into a ButtonGroup.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 Since a RadioButton is a button, it produces an ActionEventActionEvent. It . It

also generates a also generates a ChangeEventChangeEvent You can handle these event by implementing an You can handle these event by implementing an ActionListener ActionListener or or

an an ChangeListenerChangeListener If you want to handle these events, you need to import If you want to handle these events, you need to import

java.awt.event java.awt.event packagepackage Lots of useful methods…here’s three:Lots of useful methods…here’s three:

setMnemonicsetMnemonic – Specifies a alt-Key alternative for selecting the – Specifies a alt-Key alternative for selecting the RadioButton.RadioButton.

isSelectedisSelected – returns a boolean value to specify if the button has – returns a boolean value to specify if the button has been selectedbeen selected

setSelected(boolean)setSelected(boolean) – allows you to programmatically change the – allows you to programmatically change the selection status of a RadioButtonselection status of a RadioButton

Put related RadioButtons into a Put related RadioButtons into a ButtonGroupButtonGroup, so only one will , so only one will be selected at a timebe selected at a time Instantiate the ButtonGroupInstantiate the ButtonGroup Call the ButtonGroup’s Call the ButtonGroup’s addadd method to assign RadioButtons 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 toVia 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