Title: Administrivia
1Administrivia
- On Tuesday March 2nd (one week after coming week)
project presentation. Prepare 10-15 minutes per
group. - Check current course schedule and let me know
which topics do you think are relevant to your
projects. You may suggest others not listed but
related to GUI design.
2Last class review
- Transformations
- Basic animation models
- Swing and Java2D demos
- The GUI equation
- GUIcontainerslayout managerswidgetsevent
handlers
3GUI building process
- do
- Create a container
- Create a louyout
- Create widgets
- Write event handlers
- Associate event handlers with widgets
- Add widgets into container
- while (!GUI_Done)
4Today
- Event driven programming
- Threads and Swing
- Discussing solution of assignment 1
- Lab and new assignment
5Programming paradigms
Polling pseudocode
Event driven pseudocode
while(true) if (componentHasRequest())
updateComponent() else doSomethingElse()
... RegisterEventListenerWith Component() ....
EventListener(Event e) updateComponent()
I m calling you because I received your
request
I will call wheter or not you have a request
6GUI Events
App1
App2
mouseclick
OK
OK
App2 code OKbtn_click() do
stuff OKbtn_mouseover() do more
stuff CancelBtn_click() do different
stuff
Cancel
Cancel
App1 event loop
WindowSystem event loop
App2 event loop
whichapp?
inputdevice
whichcallback?
7Delegation Model
Register EventListener
class X implements EventListener
addEventListener
Event Source
Event Listener
Event Handler
Event
Fire Event
8Delegation Model
Listener object
Event source object
Listener object
Event source object
Listener object
Event source object
Fire events
Register handler
9Basic framework for event handling in Java
- Write a class that implements the interface
associated with a certain event. Generally this
takes the form of - e.g. WindowListener, MouseListener
- Create an object of the type (class) above.
- Call registering method provided by underlying
component. Generally this takes the form of - addSomethingListener(AListener listener)
- Shortcut Inner class, Listener Adapter class
10Listeners available in Java
- ActionListener - actionPerformed()
- FocusListener - focusGained(), focusLost()
- ItemListener - itemStateChanged()
- KeyListener - keyPressed(), keyReleased(),
keyTyped() - MouseListener - mouseClicked(), mousePressed(),
mouseReleased(), mouseEntered(), mouseExited() - MouseMotionListener - mouseDragged(),
mouseMoved() - TextListener - textValueChanged()
- WindowListener - windowActivated(),
windowDeactivated(), windowOpened(),
windowClosed(), windowClosing(),
windowIconified(), windowDeiconified()
11Some components and Events generated
- Button - ActionEvent
- Checkbox - ItemEvent
- CheckboxMenuItem - ItemEvent
- Choice - ItemEvent
- Component - ComponentEvent, FocusEvent,
KeyEvent, MouseEvent - Container - ContainerEvent
- List - ActionEvent, ListEvent
- TextComponent - TextEvent
- TextField - ActionEvent
- Window - WindowEvent
12Listeners
- You dont have to capture all events in the GUI.
- If you dont want to deal with events from a
component, just dont attach a listener to it. - If you do want to capture events but forget to
add a listener, no events will be captured (a
common omission).
13Listeners
- Listener methods take a corresponding type of
event as an argument. - Event objects have useful methods. For example,
getSource returns the object that produced this
event. - A MouseEvent has methods getX, getY for example.
14Some common listeners
15Implementing listeners
- Three steps
- 1) Add interface
- 2) Register listener
- 3) Create a handler
- Components can have multiple listeners
16Implementing listeners
- public class myClass implements ActionListener
//step 1 -
- JButton button new JButton(Press Me)
- button.addActionListener(this) // Step 2
-
- public void actionPerformed(ActionEvent e)
- // respond to event Step 3
-
- // end response method
- // end class
17Implementing listeners
- ActionListeners may be shared
- public class myClass implements ActionListener
//step 1 - JButton button new JButton(Press Me)
- JTextField textField new JTextField(A text
field) - button.addActionListener(this) // Step 2
- textField.add addActionListener(this)
- public void actionPerformed(ActionEvent e)
- if (e.getSource() button) ..
- else if (e.getSource() textField) ..
- else if (.....) ....
- // end response method
- // end class
18Listeners for event handling
- Classes which implement listener interfaces must
implement all listener methods - e.g. MouseListener has 5 methods mouseClicked,
mouseReleased, mouse Pressed, mouseEntered,
mouseExited - This leads to cluttered code if were not
interested in all events
19Inner classes for event handling
- A solution is using Adapter inner classes
- public class MyClass extends JPanel
-
- anObject.addMouseListener(new myAdapter())
-
- class myAdapter extends MouseAdapter
- public void mouseClicked(MouseEvent e)
- ....
- // end mouseClicked
- // end inner class
- // end MyClass
20Adapters
- Adapters are abstract classes that implement
Listeners with their bodies defined as empty . - Useful also for anonymous class when we need only
one instance. - public class MyClass extends JPanel
- ...
- someObject.addMouseListener(new MouseAdapter()
- public void mouseClicked(MouseEvent e)
- //Event handler implementation goes here
-
- )
- ...
-
-
21Adapters
22Listeners and Adapters
- For each type of event, there is a Listener
interface - For most Listener interfaces, there is an
associated Adaptor (which has empty methods), and
an associated event type - To listen for a specific event, you subclass the
appropriate adaptor
23Implementing/extending
- button1 new JButton(press me)
- myListener new myListenClass()
- button1.addMouseListener(myListener)
- // extending a class
- class myListenClass extends MouseAdapter
- public void mouseClicked(MouseEvent e)
- // button clicked, do stuff here
-
-
- // implementing an interface
- class myListenClass implements MouseListener
- public void mouseClicked(MouseEvent e)
- // button clicked, do stuff here
-
-
Choose either option
24AbstractActions
- Conveniente implementation technique
- Subclass AbstractAction which requires us to
implement ActionPerformed(ActionEvent e) - public class MyAction extends AbstractAction
-
- public void actionPerformed( ActionEvent e)
-
- // my action implementation
-
-
25Using Actions
- If you have two or more components that perform
the same function, consider using an Action
object to implement the function. - An Action object is an ActionListener that
provides not only action-event handling, but also
centralized handling of the text, icon, and
enabled state of tool bar buttons or menu items.
By adding an Action to a JToolBar, JMenu, or
JPopupMenu, you get the following features - A new JButton (for JToolBar) or JMenuItem (for
JMenu and JPopupMenu) that is automatically added
to tool bar/menu. - The button or menu item automatically uses the
icon and text specified by the Action. - A registered action listener for the button/menu
item. - Centralized handling of the button or menu item's
enabled state.
26Mouse Events
- Mouse events are captured by an object which is a
MouseListener and possibly a MouseMotionListener. - A mouse listener is usually attached to a JPanel
component. - It is not uncommon for a panel to serve as its
own mouse listener
addMouseListener(this)
addMouseMotionListener(this) // optional
27Mouse Events (contd)
- Mouse listener methods receive a MouseEvent
object as a parameter. - A mouse event can provide the coordinates of the
event and other information
public void mousePressed(MouseEvent e)
int x e.getX() int y
e.getY() int clicks
e.getClickCount()
28Mouse Events (contd)
- The MouseListener interface defines five methods
- void mousePressed (MouseEvent e)
- void mouseReleased (MouseEvent e)
- void mouseClicked (MouseEvent e)
- void mouseEntered (MouseEvent e)
- void mouseExited (MouseEvent e)
- One click and release causes several calls.
Using only mouseReleased is usually a safe bet.
Called when the mouse cursor enters/exits
components visible area
29Mouse Events (contd)
- The MouseMotionListener interface adds two
methods - void mouseMoved (MouseEvent e)
- void mouseDragged (MouseEvent e)
- These methods are usually used together with
MouseListener methods (i.e., a class implements
both interfaces).
Called when the mouse has moved with a button
held down
30Keyboard Events
- Keyboard events are captured by an object which
is a KeyListener. - A key listener object must first obtain keyboard
focus This is done by calling the components
requestFocus method. - If keys are used for moving objects (as in a
drawing program), the canvas panel may serve as
its own key listener
addKeyListener(this)
31Keyboard Events (contd)
- The KeyListener interface defines three methods
- void keyPressed (KeyEvent e)
- void keyReleased (KeyEvent e)
- void keyTyped (KeyEvent e)
- One key pressed and released causes several calls.
32Keyboard Events (contd)
- Use keyTyped to capture character keys (i.e.,
keys that correspond to printable characters). - e.getKeyChar() returns a char, the typed
character
public void keyTyped (KeyEvent e)
char ch e.getKeyChar() if (ch A)
...
33Keyboard Events (contd)
- Use keyPressed or keyReleased to handle action
keys, such as cursor keys, ltEntergt, function
keys, and so on. - e.getKeyCode() returns and int, the keys
virtual code. - The KeyEvent class defines constants for numerous
virtual keys. For example
VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN VK_HOME,
VK_END, VK_PAGE_UP, ...etc.
Cursor keys
Home, etc.
34Keyboard Events (contd)
- e.isShiftDown(), e.isControlDown(), e.isAltDown()
return the status of the respective modifier
keys. - e.getModifiers() returns a bit pattern that
represents the status of all modifier keys. - KeyEvent defines mask constants CTRL_MASK,
ALT_MASK, SHIFT_MASK, and so on.
35Threads
- Single sequential flow of control within a
program, also called lightweight process or
execution context. - Concurrent programming is performed using
multithreading to improve responsiveness of an
application - Useful and powerful programming paradigm
36Threads
- User-level Threads
- POSIX Pthreads
- Mach C-threads
- Solaris Posix threads
- Java threads
- Kernel supported Threads
- Windows 95/98/NT/2000/XP
- Linux
- Solaris
37Single Processor Multiple Threads
Thread 2
Thread 0
Thread 1
Local context Registers, PC
Local context Registers, PC
Local context Registers, PC
Code
Code
Code
Single Process, address space, file descriptors
JVM
Software
Hardware
Processor
38Multiple Threads, Multiple Processors
Thread 1
... ... Thread n
Thread 2
Thread 0
Software
OS Scheduler
Hardtware Shared Memory Multiprocessor
Processor 1
Processor 0
Processor 2
Shared Memory
The idea is improving performance by executing
threads in parallel
39Java Thread States
40Thread creation in Java
import java.lang.public class MyThread extends
Thread public void
run()
....
2 different ways of creating threads in Java
import java.lang.public class Counter
implements Runnable
public void run()
....
41When to use multiple threads
- Programs that must perform a lengthy
initialization operation before they can be used.
- Programs whose data must be updated as the result
of non-standard events (i.e requests from a
server) - When a lenghty calculation is being performed.
42Threads and Swing
- Why use them?
- Improved perceived performance by the user
- Can remove time consuming task from event thread
to keep GUI responsive - Initialisation of program so GUI appears faster
- Potential problems
- Deadlock the application if access any realised
swing components from non event event dispatch
threads.
43Swing Threads
Main thread
Event Dispatch thread
void main (..) JFrame framenew
JFrame() registerListeners() frame.show() //oth
er calculations ActionListener X
Registered Listeners
User events
Z
Y
X
44Event Dispatch Pseudocode
while (not time to quit) Event e
queue.nextEvent() dispatchEvent(e) void
dispatchEvent(Event e) Window window
calculateWindowThatGetsEventBasedOnEvent(e)
ListenerList list eventTable.lookup(window,
e.type) foreach (listener in list)
list.callback(e)
45Threads and Swing
- Remember the rule
- Once a Swing component has been realised, all
code that might affect or depend on the state of
that component should be executed in the
event-dispatching thread. - If code does not need to be in event thread then
- public void actionPerformed(ActionEvente)
-
- final SwingWorker worker new SwingWorker()
- public Object construct()
- //code that might take a while to execute
- return someValue
-
-
- worker.start()//required for SwingWorker 3
-
-
Not part of Java but avaiable
46Threads and Swing
- invokeLater()
- requests that event thread runs certain code
- can be called from any thread
- code goes in run method of Runable object
- returns immediately without waiting for event
thread to execute code. -
- Runnable updateAComponent new Runnable()
- public void run() component.doSomething()
-
- SwingUtilities.invokeLater(updateAComponent)
47Threads and Swing
- invokeAndWait()
- identical to invokeLater() except doesnt return
till event thread has finished excecuting the
code. - Should use this if possible - less chance of
deadlock. - void showHelloThereDialog() throws Exception
- Runnable showModalDialog new Runnable()
- public void run()
JOptionPane.showMessageDialog(myMainFrame,
"Hello
There") -
-
- SwingUtilities.invokeAndWait(showModalDialog)
-
48Issues in Multithreading
- Scheduling
- Priorities
- Deamon threads
- Synchronization