Java Programming Fourth Edition - Rutgers Universityszhou/351/ch14.pdf · 2009. 11. 24. · Java...
Transcript of Java Programming Fourth Edition - Rutgers Universityszhou/351/ch14.pdf · 2009. 11. 24. · Java...
Java Programming Fourth Edition
Chapter 14 Using Layout Managers and Events
Java Programming, Fourth Edition 2
Objectives
• Learn about layout managers • Use JPanels to increase layout options • Understand events and event handling • Use the AWTEvent class methods • Handle mouse events
Java Programming, Fourth Edition 3
Learning About Layout Managers
• Layout manager – Controls size and position of Components inside a Container object
– Assign to content pane or panel – Interface classes – Part of Java SDK – Align components so that they don’t:
• Crowd each other • Overlap
Java Programming, Fourth Edition 4
Learning About Layout Managers (continued)
• Layout manager (continued) – Arrange components within a Container – Container can also be Container itself – Assign layout managers within layout managers
• Java platform-supplied layout managers – FlowLayout and GridLayout – BorderLayout and CardLayout – GridBagLayout and BoxLayout
Java Programming, Fourth Edition 5
Java Layout Managers
Java Programming, Fourth Edition 6
Using BorderLayout
• BorderLayout manager – Default for all content panes – Use with:
• Container with five or fewer components • Component containers can hold more components
– Fill screen in regions • North • South • East • West • Center
Java Programming, Fourth Edition 7
The JDemoBorderLayout Application
Java Programming, Fourth Edition 8
Using BorderLayout (continued)
• Static import feature – Allows static constant without class name import static java.awt.BorderLayout.*;
• GUI component must be part of: – Containment hierarchy
• Tree of components • Top-level container as its root
Java Programming, Fourth Edition 9
Using BorderLayout (continued)
• Create Container named con – Set layout manager to BorderLayout con.setLayout(new BorderLayout());
• To set layout manager setLayout(new BorderLayout()); Or this.setLayout(new BorderLayout());
• Place object in south region of JApplet’s Container add(someButton, BorderLayout.SOUTH)
Java Programming, Fourth Edition 10
Using FlowLayout
• FlowLayout manager – Arrange components in rows across width of Container
– Add Component • Place to right of previously added components in row • If current row filled Component placed to start new
row – Each Component retains preferred size
Java Programming, Fourth Edition 11
Using FlowLayout (continued) • Align Components with Container
FlowLayout.LEFT
FlowLayout.CENTER FlowLayout.RIGHT
– If alignment not specified • Components center-aligned
Java Programming, Fourth Edition 12
The JDemoFlowLayout Applet
Java Programming, Fourth Edition 13
Using FlowLayout (continued) • invalidate()
– Marks container as needing to be laid out • validate()
– Causes components to be rearranged based on newly assigned layout
Java Programming, Fourth Edition 14
Using GridLayout
• GridLayout manager class – Arrange components into equal rows and columns
• Create GridLayout object – Indicate numbers of rows and columns
• Specify rows first and then columns – Container surface divided into grid
• Establish GridLayout con.setLayout(new GridLayout(4, 5));
Java Programming, Fourth Edition 15
Using GridLayout (continued)
• Establish GridLayout within JApplet this.setLayout(new GridLayout(4, 5));
Or setLayout(new GridLayout(4, 5)); • Establish GridLayout with three horizontal rows,
two vertical columns, and vertical gaps of five pixels each private GridLayout layout = new GridLayout(3, 2, 5, 5);
• Can use 0 for number of columns or rows
Java Programming, Fourth Edition 16
The JDemoGridLayout Applet
Java Programming, Fourth Edition 17
Output of the JDemoGridLayout Applet
Java Programming, Fourth Edition 18
Using CardLayout
• CardLayout manager – Generates stack of containers or components – One on top of another – Each component in group referred to as card – Multiple components share same display space
Java Programming, Fourth Edition 19
Using CardLayout (continued)
• Create card layout with one of two constructors CardLayout()
• Creates card layout without horizontal or vertical gap CardLayout(int hgap, int vgap)
• Creates card layout with specified horizontal and vertical gaps
– Add component to content pane add(aString, aContainer);
Java Programming, Fourth Edition 20
The JDemoCardLayout JApplet
Java Programming, Fourth Edition 21
Using Advanced Layout Managers
• GridBagLayout manager – Add Components to precise locations within grid – Indicate specific Components should span multiple
rows or columns within grid – Must set position and size for each component – Must customize one or more GridBagConstraints
objects • BoxLayout manager
– Allows multiple components to be laid out either vertically or horizontally
Java Programming, Fourth Edition 22
Using JPanels to Increase Layout Options
• Using JPanels within JPanels can create infinite variety of screen layouts
• Create JPanel object – Constructors
JPanel()
JPanel(LayoutManager layout)
JPanel(Boolean isDoubleBuffered) JPanel(LayoutManager layout, Boolean isDoubleBuffered)
Java Programming, Fourth Edition 23
Output of the Checkerboard Application
Java Programming, Fourth Edition 24
Understanding Events and Event Handling
• Events – Objects that user initiates
• EventObject – Parent class for all event objects – Descends from Object class – Parent of AWTEvent class
• Parent of ActionEvent and ComponentEvent
Java Programming, Fourth Edition 25
The Inheritance Hierarchy of Event Classes
Java Programming, Fourth Edition 26
Understanding Events and Event Handling (continued)
• ActionEvents – Focus on changes in a component
• MouseEvents – Focus on what user does manually with mouse
• Computer’s operating system notifies user when AWTEvent occurs – Can ignore AWTEvents – Must implement appropriate interface for your class
• To receive events
Java Programming, Fourth Edition 27
Examples of User Actions and Their Resulting Event Types
Java Programming, Fourth Edition 28
Understanding Events and Event Handling (continued)
• Event handler – Interface method such as actionPerformed() – Called automatically when appropriate event occurs
• Adapter class – Implements all methods in an interface
• Provides empty body for each method
• Extend adapter class – Write only methods you want to use
• Don’t bother creating empty methods for others
Java Programming, Fourth Edition 29
Understanding Events and Event Handling (continued)
• Create event handler – When writing code for listener methods
• Tell class how to handle events • Register instance of class with component that
event affects – For any <name>Listener object.add<name>Listener(Component)
Java Programming, Fourth Edition 30
An Event-Handling Example: KeyListener
• KeyListener interface – Receive actions user initiates from keyboard
• KeyListener contains three methods: keyPressed()
keyTyped() • Discover which character was typed • Does not execute calls from action keys
keyReleased() • Does not take action while user holds down key
Java Programming, Fourth Edition 31
Events with Their Related Listeners and Handlers
Java Programming, Fourth Edition 32
An Event-Handling Example: KeyListener (continued)
• KeyEvent class – Contain virtual key codes
• Represent keyboard keys that have been pressed • Virtual key code constants have names such as
VK_SHIFT and VK_ALT
Java Programming, Fourth Edition 33
Using AWTEvent Class Methods
• AWTEvent classes – Contain methods
• Determine nature of and facts about event – All Components define methods
• addComponentListener() • addFocusListener() • addMouseListener() • addMouseMotionListener()
Java Programming, Fourth Edition 34
Using AWTEvent Class Methods (continued)
• Call Event class methods – Use object-dot-method format
• InputEvent named inEvent and integer named modInt
modInt = inEvent.getModifiers();
• Use event object within handler method to obtain information – Add dot and appropriate method name
• Use any methods that belong to any superclass of an event
Java Programming, Fourth Edition 35
Useful Event Class Methods
Java Programming, Fourth Edition 36
Handling Mouse Events
• MouseMotionListener interface: mouseDragged() and mouseMoved()
• Detect mouse being rolled or dragged across component surface
• MouseListener interface: mousePressed(), mouseClicked(), and mouseReleased()
• Analogous to keyboard event methods mouseEntered() and mouseExited()
• User positions mouse over component (entered) • Or moves mouse off component (exited)
Java Programming, Fourth Edition 37
MouseListener Methods
Java Programming, Fourth Edition 38
MouseMotionListener Methods
Java Programming, Fourth Edition 39
Handling Mouse Events (continued)
• MouseInputListener interface – Implements all methods in both MouseListener
and MouseMotionListener interfaces – Has no methods of its own – Handles many different types of mouse events
• MouseEvent – Type of event generated by mouse manipulation – Contains instance methods and fields
• Useful in describing mouse-generated events
Java Programming, Fourth Edition 40
The Inheritance Hierarchy of the MouseEvent Class
Java Programming, Fourth Edition 41
You Do It
• Using BorderLayout • Using fewer than five components with the BorderLayout manager
• Using FlowLayout • Using CardLayout • Viewing all the cards in CardLayout
Java Programming, Fourth Edition 42
You Do It (continued)
• Using JPanels to achieve complex layouts • Implementing KeyListener • Using the getSource() method to determine an
event • Using MouseEvents
Java Programming, Fourth Edition 43
Summary
• Layout manager – Object that controls size and position of components
inside a Container object – BorderLayout – FlowLayout – GridLayout – CardLayout – GridBagLayout
• Use JPanels within other JPanels – Create infinite variety of screen layouts
Java Programming, Fourth Edition 44
Summary (continued)
• Events are Objects that user initiates • Implement appropriate listener interface for your
class • Event handlers
– Interface methods automatically called when event occurs
• KeyListener interface – Handles keyboard events
• MouseListener interface – Handles mouse events