Event Driven Programming - PowerPoint PPT Presentation

1 / 47
About This Presentation
Title:

Event Driven Programming

Description:

– PowerPoint PPT presentation

Number of Views:825
Avg rating:3.0/5.0
Slides: 48
Provided by: Knigh7
Category:

less

Transcript and Presenter's Notes

Title: Event Driven Programming


1
Event Driven Programming
  • PJ Dillon
  • CS401

Slides adapted from Dr. Ramirez
2
Graphical Interfaces
  • So far all of our programs have used
  • Input from the keyboard
  • Output to the console
  • This is effective but in todays world is not so
    user-friendly
  • Users want to use the mouse
  • Users want windows with dialog boxes and buttons
  • Users need maximum guidance with minimum room for
    error

3
Graphical Interfaces
  • Java has all of the tools for us to design and
    implement complex graphical user interfaces
  • Graphical output, use of a mouse, and other
    graphical components for input
  • Ex Windows with buttons, textfields, pulldown
    menus, radiobuttons, labels, and more
  • To use these tools we need to learn some Java
    classes and some programming theory
  • But once we learn how to do it we will typically
    prefer it over console applications

4
AWT and Swing
  • The AWT (Abstract Windowing Toolkit) was
    developed for the first versions of Java
  • Created components such as Frame, Panel, Button,
    TextField, Label
  • Found in package java.awt.
  • However, the look and feel of the AWT varied on
    different windowing systems
  • The same AWT Java program looks different when
    run on MS Windows machines, MACs and Sun
    Workstations
  • This is because the underlying windowing systems
    on those machines differ

5
AWT and Swing
  • Since a goal of Java is to be platform
    independent, its look and feel should also be
    platform independent
  • Swing was developed from Java v. 1.2 to be more
    consistent in its look and feel across all
    platforms
  • It also adds some extra features that did not
    exist in the AWT
  • Many Swing components are similar to AWT in name,
    but with a J in front
  • Ex JFrame, JPanel, JButton, JTextField, JLabel
  • Found in package javax.swing.

6
JFrames and JApplets
  • JFrames are Java objects that will represent the
    windows in graphical applications
  • We can draw/paint graphics within them
  • We can place and manipulate graphical components
    within them
  • JApplets are similar in their functionality to
    JFrames
  • However, they are run within the context of
    another program (i.e. a Web browser)

7
JFrames and JApplets
  • For now we will focus on JFrames
  • To use them we
  • Create a JFrame object
  • Size it as desired
  • Show it on the display
  • Once we have a JFrame we can do a LOT with it
  • Draw graphics within it
  • Store and organize other components
  • React to events such as mouse movement and
    clicking
  • We will gradually be looking at all of these
    things

8
Components and Containers
  • A component is an object that represents an
    element on the screen
  • Interacts with the user
  • e.g. label, text area, text field, etc.
  • A container is a component that holds other
    components
  • Also called Panes
  • Organizes multiple components on the screen
  • Can nest containers inside each other
  • In general, we create one or more components and
    add them to a container to display them on the
    screen
  • JFrame consists of multiple containers
  • Main one is the Content Pane

9
JLabels
  • JLabels are simple components to show formatted
    text on the display
  • We can set the font type, size and color
  • We can set and change the text itself as desired
    throughout program execution
  • Lets look at a very simple example
  • Create a JFrame, then put a JLabel in it and
    display it

10
Simple Example
  • See ex33.java
  • See the comments to determine how the various
    objects are created and set up properly
  • Note that this example does not really do much
  • No interaction with the user
  • But it does show us some of the basic setup for
    graphical applications
  • Lets now add a bit more functionality
  • Add a button that user can click to change the
    color of the label text

11
JButtons
  • JButtons are simple components that can also show
    text on the display
  • However, in addition to showing text, they also
    respond to clicks of the mouse
  • If a user clicks the mouse within a JButton, an
    ActionEvent object is generated in response
  • This object is passed automatically to an
    ActionListener object
  • The ActionListener must be registered to listen
    to the JButton
  • ActionListener is actually an interface with the
    single method actionPerformed()
  • Any class that implements actionPerformed() can
    be an ActionListener

12
Event-Driven Programming
  • This causes the actionPerformed method within the
    ActionListener to execute
  • It is the actionPerformed() method that is doing
    the actual response to the button click
  • This idea is called event-driven programming
  • Program executes idle, waiting for events to
    occur
  • user generates events in various ways
  • Ex click a button, move the mouse, edit text
  • Programmer writes code to respond to the various
    events that may occur

13
Event-Driven Programming
  • There are many different types of events in Java
    programs, but the basic idea for all of them is
    similar
  • Some component generates an event object
  • The event object is passed to some event listener
    object
  • A method in the event listener executes to handle
    the event
  • It is important that event handlers are linked to
    the appropriate event generators
  • Events are generated by any component with which
    the user interacts
  • Ignored if no handlers are associated with it
  • See ex33b.java

14
Another Example
  • Lets look at another simple example
  • Toggle Button
  • Click it once and it does an action
  • Click it again and it does a different action
  • Each click it alternates between the two actions
  • The setup of this program is very similar to
    ex33b.java
  • Only difference is what the listener is doing
  • See ex33c.java

15
JTextField and JPasswordField
  • JTextFields are components that let the user
    enter a single line of text
  • Generates ActionEvents
  • When user hits Enter key
  • getText() method returns text entered
  • getActionCommand() method of ActionEvent also
  • JPasswordField is similar
  • Displays alternative character for each character
    entered
  • getPassword() method returns password as char

16
Inner Classes
  • Notice that a new class is created for each
    different ActionListener implemented
  • One for each unique response to an ActionEvent
  • This can require a lot of extra coding
  • May want to have components interact with one
    another
  • Need to allow Listeners to access variables in
    our class
  • Three alternatives
  • Main class can implement ActionListener Interface
  • public class Main implements ActionListener
  • private int x
  • public void actionPerformed(ActionEvent e)
  • x2

17
Inner Classes
  • Declare an inner class
  • public class Main
  • private int x
  • private class MyListener implements
    ActionListener
  • public void actionPerformed(ActionEvent e)
  • x 2
  • An inner class can access all private instance
    variables and methods of its outer class
  • Well see the third alternative shortly
  • See ex33d.java

18
Anonymous Inner Classes
  • Even writing a number of inner classes can be
    tedious
  • Especially if actionPerformed() is fairly simple
  • May want to avoid if/else if/else structure
    (switch logic)
  • Can use anonymous inner classes
  • Subclasses with no name
  • public class Main
  • public Main()
  • component.addActionListener(
  • new ActionListener()
  • public void actionPerformed(ActionEvent e)
  • )
  • Creates an anonymous subclass that implements
    ActionListener
  • A instance is created here and passed to
    addActionListener()

19
Layout Managers
  • If we want to have multiple components, we need
    to determine how to lay them out
  • To do this we use a layout manager
  • These determine how components appear in a window
    and how much space is allocated for them
  • Each container can have only a single Layout
    Manager arrange its components
  • There are many layout managers in Java
  • Three simple ones are
  • FlowLayout
  • GridLayout
  • BorderLayout

20
FlowLayout
  • Simplest Layout Manager
  • Components are laid out left to right
  • Arranged in order they are added
  • Placed in a row
  • When the window no longer has enough space, a new
    row is started
  • Much like words on a page
  • A row of components can be aligned LEFT, RIGHT,
    or CENTER
  • See ex34.java

21
GridLayout
  • Divides a container into evenly sized cells of
    rows and columns
  • Each added component is placed in a cell
  • Components are resized to fit the cell
  • Placed left to right in the order theyre added
  • See ex34b.java

22
BorderLayout
  • Splits the screen into five regions
  • North, South, East, West, Center
  • At most five components can be added to the
    window
  • North and South components are resized
    horizontally
  • East and West components are resized vertically
  • Central component is resized to consume all
    remaining space
  • Default layout for JFrame Content Pane
  • See ex34c.java

23
JOptionPane
  • GUIs often need to briefly display a message,
    warning, or error
  • Popup dialogs
  • Block the user from interacting with any part of
    the GUI until the message is acknowledged
  • JOptionPane class defines a set of static methods
    to display these
  • showMessageDialog()
  • showInputDialog()
  • showConfirmDialog()
  • showOptionDialog()
  • Each method can accepts
  • A String message to display
  • A String title
  • One of several predefined icons to display
  • A reference to a component in which the dialog
    should be centered
  • See ex35.java

24
JCheckBox
  • There are several special kinds of buttons
  • JCheckBox
  • JRadioButton
  • Have an associated state Selected or Unselected
  • JCheckBox objects represent selectable options
  • Typically one of a group of options
  • Any number of the options can be selected at once
  • Consider text fonts
  • Text can be bold, in italics, or underlined
  • Can also be any combination of these
  • See ex36.java

25
JRadioButton
  • JRadioButton components are similar to JCheckBoxs
  • Have an associated selected or unselected state
  • Typically represent a set of possible options
  • Differ in that only one JRadioButton in the set
    of them can be selected at a time
  • If the user selects one, the previously selected
    one automatically becomes deselected
  • Formally define a logical set of JRadioButtons
    with a ButtonGroup object
  • See ex36b.java

26
JComboBox
  • Screen real estate is often too precious to
    display a lot of radio buttons
  • An alternative is a combo box
  • Sometimes called a drop-down list
  • Lets the user select one of a number of options
  • Initially, only the selected option is displayed
  • User clicks drop down button to display list of
    other options
  • Can be an editable
  • Lets the user enter a new value not part of the
    list
  • See ex36c.java

27
Model/View/Controller Architecture
  • JComboBox is first component weve seen that
    exposes what is known as the MVC architecture
  • GUIs render program information on the screen
  • Provide a View of the data
  • Screen elements are provided to alter the
    information
  • Controls
  • View and Controls access data through a Data
    Model
  • An abstraction that separates the access of the
    data from how its stored
  • You should read this and think, Interface

28
Model/View/Controller Architecture
  • In Java, the View and Controller are generally
    combined into the same classes
  • JComboBox provides an editor field
  • Each Model is defined as an Interface
  • ComboBoxModel, ListModel, TableModel, ButtonModel
  • Automatically propagate changes in the data to
    Views
  • Implementing classes provide single point of data
    storage and GUI interaction
  • Each GUI component comes with a default Model
    implementation
  • DefaultComboBoxModel, DefaultListModel,
    DefaultTableModel
  • Works for most simple applications
  • Well look at ex37b.java in a second

29
JList
  • A list displays a series of items
  • Arranged in a column
  • Allows the user to select one or more items from
    the list
  • Three defined selection modes
  • SINGLE_SELECTION only one item from the list can
    be selected at a time
  • SINGLE_INTERVAL_SELECTION allows one range of
    values to be selected using the shift key
  • MULTIPLE_INTERVAL_SELECTION allows more than one
    range of values to be selected
  • Generates ListSelectionEvent objects
  • ListSelectionListener
  • See ex37.java and ex37b.java

30
JPanels
  • As GUIs get more complex
  • May want to use different layout managers on
    different parts of the window
  • Need to logically group components related to
    different parts of the program
  • The GridBagLayout manager allows for arbitrary
    configurations, but it is quite complicated to
    use
  • A simpler solution is to subdivide our window
  • We can do this with JPanels
  • Have most of the functionality of JFrames, except
    without the title/menu bar
  • Can store other components and lay them out using
    a layout manager
  • Can then treat the group of components as a
    single component that can be added to our window
    with its BorderLayout

31
Borders
  • Logically grouping a set of related components
    helps organize a program and layout
  • Visually grouping them could ease user experience
  • Can use borders for this
  • Line drawn around the edge of a screen element
  • Can have many different styles
  • Titled, etched, beveled, line, empty
  • Any JComponent can have a border
  • Usually added to JPanels
  • Package javax.swing.border. defines the Swing
    Border architecture

32
Borders
  • BorderFactory class provides static factory
    methods for creating standard borders
  • BorderFactory.createEtchedBorder()
  • BorderFactory.createTitledBorder()
  • BorderFactory.createMatteBorder()
  • Each takes a different set of arguments based
    upon what the border will display
  • Returns a new Border object
  • Set a JComponents border with the
    setBorder(Border) method
  • See ex38.java

33
JTextArea
  • JTextFields allow the user to manipulate a single
    line of text
  • The JTextArea component is provides an area for
    manipulating multiple lines of text
  • Simple plain text
  • All the same font
  • Newline characters, \n, are not displayed
  • Cause subsequent text to appear below the last
  • By default, the text is editable by the user

34
MouseEvents
  • Most components generate events when the mouse
    interacts with it
  • Including JFrames, JLabel, JButton
  • Two types of Listeners MouseListener,
    MouseMotionListener
  • 7 events that can occur
  • MouseListener
  • Press, Release, Click, Enter the components
    screen area, and Leave the components area
  • MouseMotionListener
  • Move, Drag
  • A Click is a combination of a press and release
    without intervening motion
  • Often were only concerned with this operation
  • Can ignore separate press and release events

35
MouseEvents
  • Notice We could register JButtons to respond to
    mouse clicks
  • Would occur at the same time as ActionEvents
  • MouseEvents are lower level, hardware dependent
  • More abstract events are preferred, i.e.
    ActionEvents, ItemEvents, ListSelectionEvents
  • See ex39.java

36
Adapter Classes
  • A program may only need to respond to a single
    type of MouseEvent
  • Implementing MouseListener requires 5 methods
  • Extraneous
  • Each Listener interface has an Adapter class that
    implements it
  • With empty method bodies
  • ActionAdapter, MouseAdapter, WindowAdapter, etc.
  • A subclass can then just override the needed
    methods
  • window.addMouseListener(new MouseAdapter()
  • public void mouseClicked(MouseEvent e)
  • )
  • Disadvantage single inheritance
  • Dont serve as advantageous parent classes

37
Basic GUI processing
  • In GUI programs, weve seen
  • main() method usually ends after setting up and
    displaying the GUI
  • But the program doesnt terminate
  • Why?
  • GUI programs are multithreaded
  • A thread is a sequence of instructions
  • Execute separately and concurrently from other
    threads
  • A single program can be composed of a number of
    threads
  • When a GUI application is started
  • A thread is started in the background Event
    Thread
  • Processes GUI events
  • Clicks, Mouse movements, etc.
  • Drawing the screen

38
Component Drawing
  • GUIs are constructed in Containment Heirarchies
  • JFrame contains several JPanels
  • JPanel contains a JList
  • JList contains Objects that need rendered
  • When the screen needs redrawn
  • Event Thread starts by drawing the top most
    container
  • Recursively traverses containment tree drawing
    lower level Components
  • Calls paintComponent(Graphics) for each Component
  • Why is this important?
  • By subclassing a Component, we can override the
    paintComponent() method
  • Provide custom painting in the GUI

39
Graphics Object
  • When paintComponent() is called, the system
    passes it a abstract representation of the
    current drawing device
  • Screen, printer, etc.
  • The Graphics object provides a number of
    primitive drawing methods
  • fillRect() draw filled Rectangle
  • drawString() draw a String on the screen
  • setFont() set the drawing Font
  • setColor() set the drawing Color
  • drawLine(), drawRect(), drawOval(), etc.
  • Draws based on the window coordinate system
  • Upper left corner is the origin (0, 0)
  • X axis increases to the right
  • Y axis increases DOWNWARD

40
Graphics2D Object
  • Instance passed to paintComponent() is actually a
    Graphics2D object
  • A subclass of Graphics
  • The Java2D API interacts with this instance
  • Defines Gradients, Painting stroke styles, Shape
    objects, image rendering, etc.
  • See The Java Tutorial for more information
  • For now, lets look at an example
  • ex40.java

41
Menus
  • Menus allow the programmer to supply a lot of
    functionality without permanently taking up much
    window space
  • Created with several classes
  • JMenuBar
  • represents the menu bar of a window
  • Container for menus
  • JMenu
  • Represents a menu that pops down from the menu
    bar
  • Contains menu items
  • Can contain submenus
  • JMenuItem
  • A single item in a menu
  • Displays text, icons, and shortcut keys
  • Fires ActionEvents when selected by user
  • Two subclasses JCheckBoxMenuItem,
    JRadioButtonMenuItem

42
Popup Menus
  • Modern GUI applications provide context-sensitive
    popup menus
  • Menu displayed depends on screen item that gets
    clicked
  • Popup trigger differs from platform to platform
  • Typically a mouse event
  • E.g. Windows click with right mouse button
  • MouseEvent class provides isPopupTrigger() method
    to test for proper click in a platform-independent
    way
  • See ex42.java and ex42b.java

43
JColorChooser and JFileChooser
  • Notice from ex42.java that only a small selection
    of colors are provided
  • There are 224 possible colors though
  • Need a better color chooser
  • Could construct our own
  • JColorChooser is a predefined layout of
    components for picking a color
  • Added to application GUI
  • Displayed as a dialog box
  • Opening or saving a file requires a equally
    complex GUI
  • Need to display file system directories and files
  • JFileChooser is a predefined component
  • Displays Open and Save file dialogs
  • Similar to usual file dialog windows
  • See ex42c.java

44
JSlider
  • A JSlider lets the user select an integer from a
    specific range
  • Displays a bar with a thumb that can be slid
    from one end of the bar to the other
  • Can display major and minor tick marks and labels
  • Supports snap to ticks
  • Can be manipulated by the arrow keys
  • See ex43.java
  • A similar component is JSpinner
  • Has a more sophisticated model

45
Multiple Document Interface
  • Many applications support multiple open documents
    being processed in parallel
  • Reading multiple emails
  • Writing multiple documents in a word processor
  • Multiple IMs
  • MDI is supported in Java with two classes
  • JDesktopPane provides desktop space container
    for internal frames
  • JInternalFrame
  • Treated just like JFrame
  • Lay out components in its Content Pane
  • Add each frame to the desktop
  • See ex44.java

46
JSplitPane
  • A split pane divides its area among two
    components
  • Vertical or horizontal division
  • Sliding divider lets the user allocate more space
    to one component or the other
  • Constructor takes components as arguments
  • JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
    leftComponent, rightComponent)
  • Or we can set them later with
  • setLeftComponent(), setTopComponent()
  • setRightComponent(), setBottomComponent()
  • Top and Left perform same function, as does
    Bottom and Right
  • Provided for logical convenience
  • See ex45.java

47
JTabbedPane
  • JTabbedPane allows several components to share
    the same screen space
  • Each component associated with a tab on the
    screen
  • Only one component can be visible at a time
  • Clicking a tab displays the associated component
  • Similar to CardLayout
  • See ex46.java
Write a Comment
User Comments (0)
About PowerShow.com