Administrivia - PowerPoint PPT Presentation

1 / 48
About This Presentation
Title:

Administrivia

Description:

... forget to add a listener, no events will be captured (a ... A mouse listener is usually attached to a ... returns and int, the key's 'virtual code. ... – PowerPoint PPT presentation

Number of Views:33
Avg rating:3.0/5.0
Slides: 49
Provided by: DO3
Category:

less

Transcript and Presenter's Notes

Title: Administrivia


1
Administrivia
  • 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.

2
Last class review
  • Transformations
  • Basic animation models
  • Swing and Java2D demos
  • The GUI equation
  • GUIcontainerslayout managerswidgetsevent
    handlers

3
GUI 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)

4
Today
  • Event driven programming
  • Threads and Swing
  • Discussing solution of assignment 1
  • Lab and new assignment

5
Programming 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
6
GUI 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?
7
Delegation Model
Register EventListener
class X implements EventListener
addEventListener
Event Source
Event Listener
Event Handler
Event
Fire Event
8
Delegation Model
Listener object
Event source object
Listener object
Event source object
Listener object
Event source object
Fire events
Register handler
9
Basic 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

10
Listeners 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()

11
Some 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

12
Listeners
  • 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).

13
Listeners
  • 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.

14
Some common listeners
15
Implementing listeners
  • Three steps
  • 1) Add interface
  • 2) Register listener
  • 3) Create a handler
  • Components can have multiple listeners

16
Implementing 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

17
Implementing 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

18
Listeners 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

19
Inner 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

20
Adapters
  • 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
  • )
  • ...

21
Adapters
22
Listeners 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

23
Implementing/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
24
AbstractActions
  • 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

25
Using 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.

26
Mouse 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
27
Mouse 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()
28
Mouse 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
29
Mouse 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
30
Keyboard 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)
31
Keyboard 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.

32
Keyboard 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)
...
33
Keyboard 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.
34
Keyboard 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.

35
Threads
  • 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

36
Threads
  • User-level Threads
  • POSIX Pthreads
  • Mach C-threads
  • Solaris Posix threads
  • Java threads
  • Kernel supported Threads
  • Windows 95/98/NT/2000/XP
  • Linux
  • Solaris

37
Single 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
38
Multiple 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
39
Java Thread States
40
Thread 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()                      
                                       
....               
41
When 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.

42
Threads 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.

43
Swing 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
44
Event 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)
45
Threads 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
46
Threads 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)

47
Threads 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)

48
Issues in Multithreading
  • Scheduling
  • Priorities
  • Deamon threads
  • Synchronization

Write a Comment
User Comments (0)
About PowerShow.com