Copy of java i lecture_14
Upcoming SlideShare
Loading in...5
×
 

Copy of java i lecture_14

on

  • 146 views

 

Statistics

Views

Total Views
146
Views on SlideShare
146
Embed Views
0

Actions

Likes
0
Downloads
2
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters

Copy of java i lecture_14 Copy of java i lecture_14 Presentation Transcript

  • Java I--Copyright © 2000 Tom Hunter
  • Java I--Copyright © 2000 Tom HunterChapter 12BasicGraphical User InterfaceComponents
  • Java I--Copyright © 2000 Tom Hunter• A GUI interface is not designed casually.• The designer has to pay close attention to somethingcalled “Look and Feel.”• The guiding principle is making the GUI interfaceintuitive.GUI Design
  • Java I--Copyright © 2000 Tom Hunter• To become technically proficient with the important“Swing” API library, you must become comfortable withtwo base classes and their functions:ComponentContainerGUI Design: Foundation Conceptspaint() andrepaint(), forexample, originate inclass Component.A Container is a collection ofrelated Components.• You should print and study these classes !
  • Java I--Copyright © 2000 Tom Hunter• Swing borrows AWT functionality for:graphics,fonts andlayout managers.GUI Design: Foundation Concepts
  • Java I--Copyright © 2000 Tom Hunter• Lightweight components are ultimately derived from theAWT’s Container class, which extends AWT’sComponent class.Therefore:Everything in Swingis a Container ,is a Component.GUI Design: Foundation ConceptsThe AWT class Containeris actually lightweight—meaning it has no “peer.”It is painted in its container’swindow.
  • Java I--Copyright © 2000 Tom Hunter• The JRootPane,has been along for theride in every GUI wehave made. Its functionwill become apparentlater on.GUI Design: Foundation ConceptsComponentContainerJAppletJFrameJRootPaneJRootPanecontentPanecontentPane
  • Java I--Copyright © 2000 Tom HunterModel-View-ControllerArchitecture
  • Java I--Copyright © 2000 Tom Hunter• Lightweight Swing components hand off their look andfeel to a User Interface [UI] delegate.look = painting the component.feel = handling its events.• UI delegates can be plugged into a component when thecomponent is constructed, or any later time.Thus, the term: “Pluggable look and feel”Model-View-Controller Architecture
  • Java I--Copyright © 2000 Tom Hunter• Swing’s pluggable look and feel is based on acomponent architecture called:Model-View-Controller• The MVC architecture is designed for applications thatneed to wear many hats.Model-View-Controller Architecture
  • Java I--Copyright © 2000 Tom Hunter• Model—used to describe a way to maintain the data andprovide access to it via accessor methods.• View—used to paint a visual representation of some orall of the model’s data.• Controller—used to handle events.Model-View-Controller Architecture
  • Java I--Copyright © 2000 Tom Hunter• Model—stores data,—gives a way to access and—modify data,—fire events to registered Views,so the Views can update themselves basedon the change in the underlying data.Model-View-Controller Architecture
  • Java I--Copyright © 2000 Tom Hunter• View—takes care of displaying the data.Model-View-Controller Architecture
  • Java I--Copyright © 2000 Tom Hunter• Controller—handle events.—ActionListeners,—MouseListenersare MVC controllers.—The objects we know as “Listeners” are actuallycontrollers.Model-View-Controller Architecture
  • Java I--Copyright © 2000 Tom Hunter• MVC is a powerful design:Model-View-Controller ArchitectureModelA single Model...ViewViewView… can have Multiple Viewsplugged into it.ControllerController… and MultipleControllersplugged into it.
  • Java I--Copyright © 2000 Tom Hunter• MVC is the basis for Swing’s Look and Feel.• Another advantage of MVC is that any View isautomatically updated when anything changes in theModel (data) it is based on.• Finally, because theModel is independent of the Views and Controllers,any changes to the Views or Controllersdo not affect the underlying Model.Model-View-Controller Architecture
  • Java I--Copyright © 2000 Tom Hunter• An Example Button:The Button is a model—it keeps its name and caption.(its Data)The Button doesn’t decide how to draw itself—the Viewdecides that using a Layout manager.The Button doesn’t decide to to react to being pressed—the Controller decides how to handle that.Model-View-Controller ArchitectureThe Controller is the Listener
  • Java I--Copyright © 2000 Tom Hunter• As you might imagine, the upshot of this design isflexibilityModel-View-Controller Architecture
  • Java I--Copyright © 2000 Tom Hunter• Controller Styles: Known as NotificationKnown as Notification—When a data value of a model changes,the Controller hears about it.—The Controller [Listener] is notified of the change.—An event happens, and the Listener hearsabout the event.Model-View-Controller Architecture
  • Java I--Copyright © 2000 Tom Hunter• Two Kinds of NotificationNotification—Lightweight Notification—Stateful NotificationModel-View-Controller Architecture: Controller> Minimal information is passed. Thiskind of notification is used when amodel experiences frequent events.> The event contains more stateinformation than just the event source.
  • Java I--Copyright © 2000 Tom Hunter• Two Kinds of NotificationNotification—Lightweight Notification—Stateful NotificationModel-View-Controller Architecture: Controller> Example: A JSliderBar, passes manychange events as the GripGrip is moved. Becausethe potential exists for so many events, theinformation in each is minimized.> Example: A JButton, passes just oneaction event as the button is pressed, somore information about the event is passedwith each.
  • Java I--Copyright © 2000 Tom HunterModel InterfaceModel Interface Used by…Used by… NotificationNotificationBoundedRange Model JProgressBar, LightweightJSlider,JScrollBarButton Model JButton, JCheckBox StatefulJCheckBoxMenuItem,JMenu, JMenuItem, LightweightJRadioButton,JRadioButtonMenuItem,JToggleButtonComboBox Model JComboBox StatefulModel-View-Controller Architecture: Controller
  • Java I--Copyright © 2000 Tom HunterGUI Design:A Tour of the SwingObjects
  • Java I--Copyright © 2000 Tom HunterJLabel
  • Java I--Copyright © 2000 Tom Hunter—used for display only, can display text, an image,or both.—cannot react to events, therefore—cannot get the keyboard focus.—an area where uneditable text and textwith icons are displayed.—You can set the alignment of your JLabel textwithin the label.GUI Design: JLabel—Lightweight Swing Component
  • Java I--Copyright © 2000 Tom Hunter—By default, text is placed to the right of an image.—By default, an image is centered.—By default, text alone is left-justified.—You can use HTML to specify the text of a label,and thereby get a more specific appearance.—You can set up tool tips, i.e.:myLabel.setToolTipsText( “Display This” );GUI Design: JLabel
  • Java I--Copyright © 2000 Tom Hunter—By default, text is placed to the right of an image.—By default, an image is centered.—By default, text alone is left-justified.—You can use HTML to specify the text of a label,and thereby get a more specific appearance.—You can set up tool tips, i.e.:myLabel.setToolTipsText( “Display This” );GUI Design: JLabelBecause thissetToolTipsText()method is inherited fromclass JComponent, thenany descendants ofJComponent also havethis method !
  • Java I--Copyright © 2000 Tom Hunter• This is how you would place an icon on the JLabel after itwas already instantiated.myLabel.setIcon( myIcon );• Set alignment.myLabel.setHorizontalAlignment( CENTER );• You don’t need to repaint the label after you change thealignment, because the change triggers a repaint().myLabel.setIconTextGap( intGap );• Integer values allow you set the gap between text andimage.GUI Design: JLabel
  • Java I--Copyright © 2000 Tom Hunter• This is an example of a JLabel that display an Icon, andthat has had its state enabled and disabled:GUI Design: JLabellbl.setEnabled( true )lbl.disabledIcon( Icon icon )• Also, you can make the label have a different icon onlywhen it is disabled.
  • Java I--Copyright © 2000 Tom HunterJTextField
  • Java I--Copyright © 2000 Tom Hunter• Swing provides two distinct types of text components:—Simple text controls—that can only display—one font, and—one color at a time:JTextField, JTextArea,JPasswordField—Styled text components—that can display—multiple fonts, and—multiple colors:JEditorPane, JTextPaneGUI Design
  • Java I--Copyright © 2000 Tom Hunter—Receives a single line of input from the keyboard.—Can display information.—Is editable—the most common way to input data—Single font, single color—Horizontal Alignment can be set:LEFT, CENTER, RIGHTGUI Design: JTextField
  • Java I--Copyright © 2000 Tom Hunter—uses the ActionListener interface to respondto events.—When a JTextField fires an action event, theevent’sevent’s actionCommand is set to the textfield’s actionCommand property.—Using the JTextField’ssetActionCommand() method, you canexplicitly set this property.—Otherwise, it defaults to the contents of theJTextField.GUI Design: JTextField
  • Java I--Copyright © 2000 Tom Hunter—By default pressing the ENTER key while aJTextField has focus fires an ActionEvent.—You set the Preferred Width by instantiating itwith a number of columns, but the LayoutManager has the final say.—The columns you set are assumed to be the letter“m”, because it’s the widest.GUI Design: JTextField
  • Java I--Copyright © 2000 Tom Hunter—Using the GridBagLayout to layoutJTextFields.This example creates pairs of JLabels andJTextFields, which it aligns.In the code, you see howit alternates making eachJLabel the width of 1 cell,followed by a JTextFieldsthat are set up to be theremainder of the space.GUI Design: JTextField
  • Java I--Copyright © 2000 Tom HunterJPasswordField
  • Java I--Copyright © 2000 Tom Hunter• A JPasswordField is just another kind ofJTextField, except it displays a string of asterisks inplace of the text you’re typing in.• You can make an ActionListener listen to yourJPasswordField object, but when it comes time toactually discover what is inside the actionCommand,you must cast your ActionEvent object back into anobject of type JPasswordField .( see page 568)GUI Design: JPasswordField
  • Java I--Copyright © 2000 Tom HunterJButton
  • Java I--Copyright © 2000 Tom Hunter• Setting or Getting The Button’s Contents—Constructors are:—Is initialized with a String that appears on it.—Can display an Icon.—When the button isn’t selected or pressed, you canchange the Icon or see how it is currently set.GUI Design: JButtonJButton()JButton(Icon)JButton(String)JButton(String, Icon)void setIcon(Icon)Icon getIcon()
  • Java I--Copyright © 2000 Tom Hunter• Setting or Getting The Button’s Contents—At run time, you can set or get the text displayedon the button.—Whenever the button is disabled (grayed out), youcan change what icon it displays.GUI Design: JButtonvoid setText(String)String getText()void setDisabledIcon(Icon)Icon getDisabledIcon()
  • Java I--Copyright © 2000 Tom Hunter• Setting or Getting The Button’s Contents—You can specify which Icon it willdisplay when it is pressed.GUI Design: JButtonvoid setPressedIcon(Icon)Icon getPressedIcon()
  • Java I--Copyright © 2000 Tom Hunter• Designing How the Button Functions—A JButton can display a “mnemonic”, or anunderline that identifies the shortcut key.GUI Design: JButtonvoid setMnemonic(int)char getMnemonic()
  • Java I--Copyright © 2000 Tom Hunter• Designing How the Button Functions—This has two alternative overrides:i.) one accepts a char argumentsetMnemonic(char mnemonic)]ii.) The other accepts an int constant of a typeKeyEvent.VK_XsetMnemonic(int mnemonic)(This one is preferred)GUI Design: JButton
  • Java I--Copyright © 2000 Tom Hunter—setActionCommand() —this lets youdefine the action command string thisbutton will generate when an eventhappens to it.—getActionCommand()—this is the commandan Event Handler would use to discover theaction command string. By default, a button’saction command is set to the button text.We have used this method to process events.GUI Design: JButtonvoid setActionCommand(String)String getActionCommand(void)
  • Java I--Copyright © 2000 Tom HunterGUI Design: JButtonWhen an event occurs, the button passes anActionEvent object to the listener registered to listenfor events on the button.The ActionEvent object has two commonlyused methods:—getSource() which returns the referencename of the object the event happened to, and— getActionCommand() which “Returns thecommand string associated with this action.”This usually means, “Return the String displayed on thebutton,” but you can set it to something more specific.
  • Java I--Copyright © 2000 Tom Hunterb1.setActionCommand("disable");b3.setActionCommand("enable");public void actionPerformed(ActionEvent e){if ( e.getActionCommand().equals("disable") ){b2.setEnabled(false);b1.setEnabled(false);b3.setEnabled(true);}else{b2.setEnabled(true);b1.setEnabled(true);b3.setEnabled(false);}}This gives you agreater degree ofcontrol over whatexactly happens inresponse to the event.
  • Java I--Copyright © 2000 Tom Hunterb1.setActionCommand("disable");b3.setActionCommand("enable");public void actionPerformed(ActionEvent e){if ( e.getActionCommand().equals("disable") ){b2.setEnabled(false);b1.setEnabled(false);b3.setEnabled(true);}else{b2.setEnabled(true);b1.setEnabled(true);b3.setEnabled(false);}}In fact, this is the preferred way to use thissetActionCommand() method.Your program sets the Action Command String on anobject that has an Action Listener.When the event happens, you can fine tune the result.
  • Java I--Copyright © 2000 Tom Hunterb1.setActionCommand("disable");b3.setActionCommand("enable");public void actionPerformed(ActionEvent e){if ( e.getActionCommand().equals("disable") ){b2.setEnabled(false);b1.setEnabled(false);b3.setEnabled(true);}else{b2.setEnabled(true);b1.setEnabled(true);b3.setEnabled(false);}}Remember, when we call the methodgetActionCommand() of an ActionEvent object[ e.getActionCommand() ] it returns a String.If we want to make a comparison between that commandString, we can’t just compare the two, we have to usethe equals() method, which is inherited from Object.
  • Java I--Copyright © 2000 Tom HunterGUI Design: JButton• The JButton object lets you specify a different“rollover” icon—when a mouse pointer is on top of thebutton:Normal Rolloverbutton.setIcon(new ImageIcon("open_hand.gif"));button.setRolloverIcon(new ImageIcon("punch.gif"));
  • Java I--Copyright © 2000 Tom HunterGUI Design: JButton• You can set a JButton to be the Default Button,meaning it automatically has the focus.• To do this, you have to get an object of theJRootPane, which we have not yet had to do:Container c = getContentPane();JRootPane root = getRootPane();JButton def = new JButton( “Default Button” );root.setDefaultButton( def );c.add( def );
  • Java I--Copyright © 2000 Tom HunterGUI Design: JButton• Using a method called doClick(), you can make abutton be clicked programmatically—meaning seeminglyby magic.• The argument is the time in milliseconds that the buttonwill remain pressed.JButton click = new JButton( “Click” );click.doClick( 2000 );
  • Java I--Copyright © 2000 Tom HunterJCheckBox
  • Java I--Copyright © 2000 Tom Hunter• Setting or Getting The CheckBox’s Contents—These are two-state buttons that reflect their statusby having a checkmark in a box (as the nameimplies)—We say they can be Selected or DeSelected.GUI Design: JCheckBox
  • Java I--Copyright © 2000 Tom Hunter• Constructors are many and varied.—can include a String, an Icon and it can be presetas either selected or deselected.GUI Design: JCheckBox
  • Java I--Copyright © 2000 Tom Hunter• Event Handling for a JCheckBox is different—it usesan ItemListener rather than an ActionListener.• Your program must implement the ItemListenerinterface.• This interface has only one method for you to override:public void itemStateChanged( ItemEvent e );GUI Design: JCheckBox
  • Java I--Copyright © 2000 Tom Hunter• An ItemEvent object is passed, and it contains a constantproperty: ItemEvent.SELECTED• Method getStateChange() tells what happened.GUI Design: JCheckBoxJCheckBox ans = new JCheckBox( “Yes” );ans.addItemListener( this );…public void itemStateChanged( ItemEvent e ){if( e.getStateChange() == ItemEvent.SELECTED )}
  • Java I--Copyright © 2000 Tom Hunter• If you instantiate the JCheckBox without an image, itwill get the familiar square box.• If you instantiate the JCheckBox with an image, thenthe square box will be omitted and no default square boxwill be created.• When you create a menu, you may also add a menu itemthat is a check box. For this purpose, you would use a:JCheckBoxMenuItemGUI Design: JCheckBox
  • Java I--Copyright © 2000 Tom Hunter• This control follows the standard L & F as other objects.• For example, you can set the Mnemonic as follows:JCheckBox ans = new JCheckBox( “Yes” );ans.setMnemonic( KeyEvent.VK_Y );• This is how to change the status of the control, and ofcourse, this would trigger an itemStateChangedevent.ans.setSelected( true );GUI Design: JCheckBox
  • Java I--Copyright © 2000 Tom HunterJRadioButton
  • Java I--Copyright © 2000 Tom Hunter• Setting or Getting The JRadioButton—These are two-state buttons that reflect their statusby having a dot in a circular hole.—The interior of the hole is either white or gray,depending on the L&F.—When organized in a structure called aButtonGroup, only oneButtonGroup in thegroup can be selected atone time.JRadioButtonsare Mutually Exclusive.GUI Design: JRadioButton
  • Java I--Copyright © 2000 Tom Hunter• Constructors—Just as with the JCheckBoxes,JRadioButtonshave many Constructors, taking an Icon,a String caption, and a preset boolean foreither Selected or Deselected.—When a JRadioButton is Selected, it fires anItemEvent. Therefore, if you use aJRadioButton, you must implement theItemListener interface as with theJCheckBox.GUI Design: JRadioButton
  • Java I--Copyright © 2000 Tom Hunter• ButtonGroup—The logical relationship between the buttonsgathered together to form a button groupis maintained by the objectButtonGroup.—Warning: The ButtonGroup is NOT a GUIobject. It cannot appear on the GUI and soyou do NOT ever add a ButtonGroupobject to the Container. To do so is asyntax error.GUI Design: JRadioButton
  • Java I--Copyright © 2000 Tom Hunter• ButtonGroup—Joining your JRadioButtons into aButtonGroup is entirely separate fromadding the JRadioButtons to the GUI’sContainer.GUI Design: JRadioButton
  • Java I--Copyright © 2000 Tom HunterContainer c = getContentPane();c.setLayout( new FlowLayout );JRadioButton ital = new JRadioButton( “Italic” );JRadioButton bold = new JRadioButton( “Bold” );JRadioButton undr = new JRadioButton( “Underline” );c.add( ital );c.add( bold );c.add( undr );ButtonGroup bg = new ButtonGroup();bg.add( ital );bg.add( bold );bg.add( undr );The process ofcollectingJRadioButtons into aButtonGroup isentirely separate fromthe creation of theGUI.
  • Java I--Copyright © 2000 Tom HunterJMenuBar,JMenu,JMenuItem
  • Java I--Copyright © 2000 Tom Hunter• The menu bar is an aspect of modern GUIs thatusers have become very common.• The tool bar is just as common.—Creating and managing either one requiressignificant effort.GUI Design: JMenuBar, JToolBar
  • Java I--Copyright © 2000 Tom Hunter• There are two broad categories of menus:—Menu Bars (on the top)(Known as a top-level menu)(Menus that are contained in another menuare called pull-right menus.)—Popup Menus (coming from anywhere else)• Menus can only be attached to objects of classes thatcontain the method:setJMenuBar()GUI Design: JMenuBar
  • Java I--Copyright © 2000 Tom Hunter• If you understand the termsused to describe a menu,building one can be veryeasy.GUI Design: JMenuBarThe bar across the top is theJMenuBar. After you instantiatethe single JMenuBar, you set itto be thethe JMenuBar.To place a JMenu object inthe JMenuBar, you add it.A JMenu item always haschildren.If this object is the end of theroad, it is a JMenuItem .Because this has childrenmenus, it is a JMenu .This is a JMenuItem.
  • Java I--Copyright © 2000 Tom HunterJMenuBar bar = new JMenuBar();setJMenuBar( bar );action = new JMenu( "Action" );enterNew = new JMenuItem( "Enter New Data" );enterNew.addActionListener( this );printData = new JMenu( "Print Data" );printDataSorted = new JMenuItem( ”Printed in Sorted Order" );printData.add( printDataSorted );printDataEntry = new JMenuItem( ”Print in Entry Order" );printData.add( printDataEntry );exit = new JMenuItem( "Exit" );action.add( enterNew );action.add( printData );action.add( exit );bar.add( action );
  • Java I--Copyright © 2000 Tom Hunter• Because menus and menu bars ( also toolbars) are allsubclasses of the JComponent class, they are alllightweight containers.• Since they’re containers,any type of component canbe added to a Swing menu—such as the icons you sawin the first example.GUI Design: JMenuBarThis is an example of a menu withgraphics, and a Toolbar with graphics.
  • Java I--Copyright © 2000 Tom HunterJPopupMenu
  • Java I--Copyright © 2000 Tom Hunter• A Popup Menu comes from anywhere on the GUI.• On a Windows L&F, the 2nd mouse button triggers it.• On a Unix Mofif L&F, the 3rd mouse button triggers it.• The ActionListener has to work hard to determine ifthe correct mouse button was pressed—meaning, if it was avalid “popup trigger”.GUI Design: JPopupMenu
  • Java I--Copyright © 2000 Tom HunterAny time an actionis detected, thisapplet calls themethodshowPopup(),trying to see if theMouseEventqualified as aPopup Trigger.When it qualifies,it fires the show()method of theJPopupMenu
  • Java I--Copyright © 2000 Tom Hunter• JMenu offers a number of ways to add/insert/remove itemsfrom menus.—Normally, methods that add or insert actions ormenu items return a reference to the menu item that isultimately added or inserted.—Methods that add or insert a String do NOT returna reference to a menu item. However, an item or listing in themenu is still created.—Thus, we create what is called a self-modifyingmenu.GUI Design: Dynamically Modifying Menus
  • Java I--Copyright © 2000 Tom Hunterpublic SelfModifyingMenu(){super("Self Modifying Menu");add(enablerItem = new JMenuItem("Disable Item Below"));add(toggleItem = new JMenuItem("Enable/Disable Me"));addSeparator();add(addItem = new JMenuItem("Add a JMenuItem ..."));add(removeItem = new JMenuItem("Remove last JMenuItem "));addItem.setFont(new Font("Helvetica", Font.BOLD, 18));addSeparator();enablerItem.addActionListener(menuItemListener);toggleItem.addActionListener(menuItemListener);addItem.addActionListener(menuItemListener);removeItem.addActionListener(menuItemListener);}public void addItem(){JMenuItem newItem =new JMenuItem("Extra Item #" + newItems.size());add(newItem);newItems.addElement(newItem);}
  • Java I--Copyright © 2000 Tom HunterJToolBar
  • Java I--Copyright © 2000 Tom Hunter• Unlike the menus, a JToolBar is not added with aspecific method. Rather, the JToolBar is just added to thecontainer like any other component.—Further, Tool bars should be added to a containerthat contains an instance of theBorderLayout.—In this BorderLayout, the JToolBar shouldbe put in anywhere but the center of theBorderLayout.GUI Design: JToolBar
  • Java I--Copyright © 2000 Tom Hunter• To begin, the JToolBar is a container that can beoriented either horizontally or vertically.• A Swing Tool Bar can float—meaning it can move aroundanywhere on the GUI the user desires.• Using JToolBar methods:—add( Action ), and—addSeparator,any type of component can be added to a JToolBarGUI Design: JToolBar
  • Java I--Copyright © 2000 Tom HunterGUI Design: JToolBar• This is a sample JToolBar.• We just treat it as a component that gets buttons added to it.• We can add any component to it, although the results don’talways look the greatest unless we tweak the layout.• If you drag a JToolBar,you can cause it to floatinto another side, whereit will “stick” andattach itself.• Otherwise, it can pop upin its own window.
  • Java I--Copyright © 2000 Tom HunterUp Close and Personalwith theEvent Handling Model
  • Java I--Copyright © 2000 Tom HunterPreliminaries• To process an event, a Java program must:(1) Implement an Event Listener(2) Register an Event Listener(3) Override the required methods for thatlistener interfaceinterface, which handles thedelegated event.Event Handling Model
  • Java I--Copyright © 2000 Tom HunterAlthough the “Delegation” event modelmay seem difficult, it is a vastimprovement over the previous“Inheritance”-based event model—whichis no longer used now that we have Swing.In short, how it works is this: if mysubclass can’t handle the event, then I pass( or “propagate” ) it up the ladder—hopingmy Superclass will be capable ofhandling. This led to giant switchstatements...
  • Java I--Copyright © 2000 Tom Hunter• The Event Model is Built Around A variety ofinterfaces that focus on different kinds of events.• The Event Listener interfaces is the universalparent to all the other interfaces.“Delegation” Event Handling Modeljava.util.EventListenerActionListenerAdjustmentListenerComponentListenerContainerListenerFocusListenerItemListenerKeyListenerMouseListenerMouseMotionListenerTextListenerWindowListener
  • Java I--Copyright © 2000 Tom Hunter• All of the previous Events are inherited from thepackage:java.awt.event.*;• Several of the Swing package have extra eventtypes that are found in:javax.swing.event.*;Event Handling Model
  • Java I--Copyright © 2000 Tom HunterEvent Handling Model• In a nutshell, the delegation event model workslike this:—components fire events, which can belistened for and acted upon bylistenerslisteners.—after the event happens, the listenershave established methods that willrespond.
  • Java I--Copyright © 2000 Tom HunterEvent Handling Model• All of the action—for events and listeners—startsin the java.util package.• This package comes with a class and an interface.—EventListener—the interface, a tagginginterface, which alllisteners extend.—EventObject—this class keepstrack of the eventsource.A tagging interface does notdefine any methods at all.
  • Java I--Copyright © 2000 Tom HunterEvent Handling ModelAWT Class/Interface Listener RegistrationButton addActionListenerCheckBox addItemListenerCheckBoxMenuItem addItemListenerChoice addItemListenerComponent addComponentListeneraddFocusListeneraddInputMethodListeneraddKeyListeneraddMouseListeneraddMouseMotionListener
  • Java I--Copyright © 2000 Tom HunterEvent Handling ModelAWT Class/Interface Listener RegistrationContainer addContainerListenerList addActionListenerMenuItem addActionListenerScrollBar addAdjustmentListenerTextArea addTextListenerTextComponent addTextListenerTextField addTextlisteneraddActionListenerWindow addWindowListener
  • Java I--Copyright © 2000 Tom HunterEvent Handling Model•Of all these various Event Source Interfaces, theyfall into two broad types:—AdjustableThese listeners have values that can beset between defined minimum andmaximum values.(They also fire multipleAdjustmentEvents—ItemSelectableThese listeners have items, of whichzero of more are selectable.
  • Java I--Copyright © 2000 Tom HunterEvent Handling Model: Component Events• Component events are fired when somethingspecific happens to a component:—the mouse enters or exits—the component is pressed—the component gains or loses focus—the component is a window that isclosing.
  • Java I--Copyright © 2000 Tom HunterEvent Handling Model: Component Events• Component events are classified as either:—input events or—non-input events.• Input events are distinguished from non-inputevents because input events can be consumed,meaning they are entirely dealt with in thatcomponent and are not passed on to anythingelse.
  • Java I--Copyright © 2000 Tom HunterEvent Handling Model: Focus Events•At any moment in time, only one component hasthe keyboard focus.• When a component has focus, keyboard eventsare delivered to the component in question.• In most cases, it is possible to visibly detectwhich component has the keyboard focus.
  • Java I--Copyright © 2000 Tom HunterEvent Handling Model: Focus Events•There are several ways an AWT component cangain focus:—the user interacts with the componentusing the mouse.—Invoke: Component.focusRequested()—Type TAB or SHIFT-TAB to cycle thekeyboard focus.
  • Java I--Copyright © 2000 Tom HunterEvent Handling Model: Focus Events• Focus events are described as either:—FOCUS_LOST events or—FOCUS_GAINED events.