CIS-257 Home: http://www.c-jump.com/bcc/c257c/c257syllabus.html
Classes that respond to user-initiated events
Must implement interface that deals with events, called event listeners
Many types of listeners exist in Java
Each can handle specific event type
A class can implement multiple event listener interfaces
Event occurs every time user types a character or clicks on a mouse button
For a complete list of listeners, see Listener API Table tutorial article.
----------------------------------------- Control/action Listener interface ----------------- --------------------- Button click ActionListener Scroll Bar AdjustmentListener Slider ChangeListener Text Field focus FocusListener Check Box ItemListener Text entered KeyListener Mouse click MouseListener Mouse wheel MouseWheelListener Window closes WindowListener -----------------------------------------
Event listener establishes relationship between Swing component and a class that reacts to the user's manipulation of the component.
For example, JCheckBox responds to user mouse clicks and supports
addItemListener( eventHandler )
method.
The format of "add listener" methods is
theSourceOfTheEvent.addListenerMethod( theClassThatShouldRespond );
For a complete list of components and listeners, see Listeners Supported by Swing Components
JCheckBox consists of a label positioned beside a square
Clicking the square turns check mark option on or off
Constructors
JCheckBox()
JCheckBox( "text label" )
JCheckBox( "text label", boolean checked )
Methods
void setText( String ) String getText() void setSelected( boolean ) boolean isSelected() void addItemListener( new ItemListener() {} );
checkBox = new JCheckBox( "check label", false );
checkBox.addItemListener(
// using anonymous class without a name
new java.awt.event.ItemListener()
{
// method executes when status of the check box changes:
public void itemStateChanged( java.awt.event.ItemEvent evt ) {
JCheckBox source = ( JCheckBox ) evt.getItemSelectable();
if ( source == checkBox ) {
System.out.println( "box" + source.isSelected() );
}
}//itemStateChanged
}//anonymous class
);
frame.getContentPane().add(checkBox);
To add or remove a component from a container that has already been made visible, or to repaint background colors, call
JFrame.validate() JFrame.repaint()
Layout manager is a class that controls size and position of components inside a Container object
Examples:
BorderLayout
Normal (default) behavior of a JFrame :
JLabel myLabel; frame.getContentPane().add( myLabel, BorderLayout.CENTER );
Divides a container into regions
FlowLayout
places components in a row
Layout Manager determines how the components are sized and positioned to avoid
components crowding each other
components overlap
A component can also be a Container itself; therefore, Swing can assign layout managers within layout managers
BorderLayout (default) adds 5 sections N-S-E-W-Center
FlowLayout adds components left-to-right, wraps rows as needed
GridLayout adds rows and columns, autosizes components
CardLayout displays components one at a time
GridBagLayout sets custom size, place, and alignment for each component
BoxLayout adds components to a single row or column
Default for all content panes
Best use with any container that has five or fewer components
Arranges components in rows across width of a Container
If current row is filled, the added component wraps to the next row
Each component retains its own preferred size
Alignment options available:
FlowLayout.LEFT FlowLayout.CENTER (default) FlowLayout.RIGHT
For example,
private FlowLayout layout = new FlowLayout(); layout.setAlignment( FlowLayout.RIGHT );
invalidate() -- marks container (and all parent containers) as needing to be laid out
validate() -- causes components to be rearranged based on newly assigned layout
Arranges components into equal rows and columns:
container.setLayout( new GridLayout( ROWS, COLUMNS ) );
Container surface becomes divided into grid
Another constructor allows to specify vertical and horizontal gaps between rows and columns in pixels:
container.setLayout( new GridLayout( ROWS, COLUMNS, GAP_PIXELS_ROW, GAP_PIXELS_COL ) );
Note: number of rows or columns can be zero. In that case the layout manager will determine the number of rows/columns automatically.
Generates stack of containers or components
One on top of another
Each component in group referred to as a "card"
Multiple components share same display space
CardLayout can implement a wizard dialog, taking the user through the series of screens
// no horizontal or vertical gaps CardLayout() // specifies horizontal and vertical gaps in pixels: CardLayout( int hgap, int vgap )
add( String componentCardID, Component component );
import javax.swing.*; import java.awt.*; public class FrameWithCardLayout extends JFrame { private JButton nb = new JButton( "North" ); private JButton sb = new JButton( "South" ); private JButton eb = new JButton( "East" ); private JButton wb = new JButton( "West" ); private JButton cb = new JButton( "Center" ); public FrameWithCardLayout() { setLayout( new CardLayout() ); add( "north", nb ); add( "south", sb ); add( "east", eb ); add( "west", wb ); add( "center", cb ); setSize( 250, 250 ); setVisible( true ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } public static void main(String[] ags) { FrameWithCardLayout jbl = new FrameWithCardLayout(); } }//class FrameWithCardLayout
private CardLayout mLayout; // class member // constructor JPanel cards = new JPanel(); // panel to hold cards mLayout = new CardLayout(); cards.setLayout( mLayout ); // operations mLayout.first( cards ); mLayout.previous( cards ); mLayout.next( cards ); mLayout.last( cards );
Adds components at precise locations to the grid
Indicates that specific components can span multiple rows or multiple columns within grid
Must set position and size for each component
Must customize one or more GridBagConstraints objects
Allows multiple components to be laid out either vertically or horizontally
Plain borderless surface
holds lightweight UI components
supports double-buffering (default buffering for Java GUI)
Note: JPanel uses additional memory to draw offscreen when the panel is updated
Constructors:
JPanel() JPanel( LayoutManager layout ) JPanel( Boolean isDoubleBuffered ) JPanel( LayoutManager layout, Boolean isDoubleBuffered )
To add a component to JPanel:
Call JPanel.add() method
Specify component as argument
JPanel.setBackground() method changes JPanel's background color
Several JPanels can be used within one application frame to organize components
Operates like CardLayout
Folder-style tabs are displayed on top of the container
Provides scroll bars along side or bottom of pane
Constructors:
JScrollPane() JScrollPane( Component ) // holds the specified component JScrollPane( Component, constant, constant ) JScrollPane( constant, constant )
where each constant represents a behavior option. The constants can be
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER
EventObject
parent class for all event objects
descends from Object class
parent of AWTEvent class
parent of ActionEvent and ComponentEvent
ActionEvents convey changes in a component
MouseEvents convey user interaction with the mouse
AWTEvents convey operating system notifications (many can be ignored)
Note: to receive events the class must implement the appropriate interface
To handle an event, the interface method such as actionPerformed() is called automatically when that event occurs.
An adapter class implements all methods in an interface, providing empty body for each method
To handle events, extend the adapter class:
write only methods you need
no need to write empty methods for other methods
The library adapter classes
implement a specific event listener interface
provide empty implementations for each method
Java library provides adapter classes for some event listener interfaces. For example,
class WindowAdapter implements WindowListener interface with empty bodies to methods
class MouseAdapter implements MouseListener interface with empty bodies to methods
For any XyzListener, to register event handler with the control that generates particular set of events, call
control.addXyzListener( handler )
where handler is an instance of a class that implements the XyzListener interface.
For example,
checkBox = new JCheckBox( "check label", false ); checkBox.addItemListener( // using anonymous class without a name new java.awt.event.ItemListener() { // method executes when status of the check box changes: public void itemStateChanged( java.awt.event.ItemEvent evt ) { JCheckBox source = ( JCheckBox ) evt.getItemSelectable(); if ( source == checkBox ) { System.out.println( "box" + source.isSelected() ); } }//itemStateChanged }//anonymous class ); frame.getContentPane().add(checkBox);
Registering WindowAdapter window listener object to GUI component:
call component.addWindowListener() method
pass WindowAdapter object as parameter to be registered
Registering MouseAdapter mouse listener object to GUI component:
call component.addMouseListener() method
pass MouseAdapter object as parameter to be registered
The KeyListener interface receives actions that user initiates from the keyboard
Declares three methods:
keyPressed() // character typed -- no calls from function keys keyTyped() // function keys and keys not generating any characters keyReleased() // used in most cases, including function keys
The keyReleased() does not take action while user holds down key
The keyTyped() is platform independent -- preferred way of handling the keyboard.
The keyPressed() and keyReleased() are platform/locale dependent.
The KeyEvent class contains virtual key code values mapped to library constants that indicate which keys the user pressed.
Virtual key code constants have names such as VK_SHIFT and VK_ALT
MouseMotionListener interface:
mouseDragged() // mouse being dragged across component surface mouseMoved() // mouse being rolled across component surface
MouseListener interface:
// Analogous to keyboard event methods: mousePressed() mouseClicked() mouseReleased() mouseEntered() // User positions mouse over component mouseExited() // User moves mouse off component
Implements all methods in both MouseListener and MouseMotionListener interfaces
Has no methods of its own
Handles many different types of mouse events
MouseEvent class represents the type of event generated by mouse manipulation
Contains instance methods and fields
Useful in describing mouse-generated events
Menus are lists of user options/commands
Menu classes:
JMenuBar JMenu JMenuItems
The JFrame.setJMenuBar() method adds JMenuBar to the frame
The JMenuBar.add() method adds JMenu item to the menu.
JCheckBoxMenuItem objects appear with a check box next to them
JRadioButtonMenuItem objects appear with a round radio button next to them
isSelected() method determines the state of either a JCheckBoxMenuItem or a JRadioButtonMenuItem item.
The addSeparator() method adds a horizontal line to menus
Visually separates groups of menus
Does not change the functionality of the menu
Mnemonic is the key that causes an already-visible menu item to be chosen
Mnemonic key should be unique for each menu item
Shortcut menu key is a unique key to select any visible menu item
Accelerator key is a key combination that causes a menu item to be chosen, whether or not visible
Note: Only leaf menu items (not submenus) can have accelerators
A visual guide to layout managers:
download.oracle.com/javase/tutorial/uiswing/layout/visual.html
Using Layout Managers
download.oracle.com/javase/tutorial/uiswing/layout/using.html
Lessons on implementing each type of event handler:
download.oracle.com/javase/tutorial/uiswing/events/handling.html
General Information about Writing Event Listeners:
download.oracle.com/javase/tutorial/uiswing/events/generalrules.html
Java and event handling:
www.javaworld.com/javaworld/jw-08-1996/jw-08-event.html