8/8/2019 5 Graphical User Interfaces
1/63
Department of Computer ScienceDr. John S. Mallozzi
CS 202HY CS 202HY Computer Science IIComputer Science II
5. Graphical User Interfaces5. Graphical User Interfaces
Basics, Layouts, ComponentsBasics, Layouts, Components
8/8/2019 5 Graphical User Interfaces
2/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 2 2
FramesFrames
OverviewOverviewFrame methodsFrame methodsDrawing text using a labelDrawing text using a labelDrawing in a frameDrawing in a frame
8/8/2019 5 Graphical User Interfaces
3/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 3 3
OverviewOverview
A modern A modern graphical user interface (GUI) graphical user interface (GUI) is basedis basedon drawingon drawing windowswindows on the screenon the screenEach GUI application has aEach GUI application has a mainmain windowwindowin Java, the main window is called ain Java, the main window is called a frameframeTo write a program, you first construct a frame,To write a program, you first construct a frame,then send it messages to give it a particular size,then send it messages to give it a particular size,appear in a particular part of the screen, etcappear in a particular part of the screen, etc
You place drawings into a frame by adding You place drawings into a frame by addingcomponents,components, which are things like text boxes,which are things like text boxes,buttons, etc (each of which is a small window) buttons, etc (each of which is a small window)
8/8/2019 5 Graphical User Interfaces
4/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 4 4
Constructing a FrameConstructing a Frame
A frame is an object constructed using the class A frame is an object constructed using the classJFrameJFrame , which is part of the Swing library,, which is part of the Swing library,javax.swingjavax.swing , which you must import , which you must import
After you create a frame, you should After you create a frame, you should Set itsSet its title,title, usingusing setTitlesetTitle Set itsSet its size,size, usingusing setSizesetSize Set itsSet its location,location, usingusing setLocationsetLocation
Tell Java toTell Java to end the programend the program when someone closeswhen someone closesthe window, usingthe window, using setDefaultCloseOperationsetDefaultCloseOperation Tell Java to make the windowTell Java to make the window visiblevisible usingusing
setVisiblesetVisible
8/8/2019 5 Graphical User Interfaces
5/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 5 5
Frame MethodsFrame Methods
setTitlesetTitle public public void void setTitle(StringsetTitle(String titleToUse) titleToUse) PlacesPlaces titleToUsetitleToUse in blue bar at top of framein blue bar at top of framesetSizesetSize public void public void setSize(setSize( intint width,width, intint height)height) Makes the windowMakes the window widthwidth pixels wide andpixels wide and heightheight
pixels highpixels highsetLocationsetLocation public void public void setLocation(setLocation( intint fromLeft,fromLeft, intint fromTop)fromTop) Places windowPlaces window fromLeftfromLeft pixels from the left side of pixels from the left side of
the screen andthe screen and fromTopfromTop pixels from the top of thepixels from the top of thescreenscreen
8/8/2019 5 Graphical User Interfaces
6/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 6 6
Frame MethodsFrame Methods
setDefaultCloseOperationsetDefaultCloseOperation public void public void setDefaultCloseOperation(setDefaultCloseOperation( intint operation)operation)
Depending on the value of Depending on the value of operationoperation , tells Java what , tells Java what to do when user closes the window (by pressing into do when user closes the window (by pressing inupperupper--right right--hand corner of window) hand corner of window)
Values are given using named constants Values are given using named constants To end the program, useTo end the program, use JFrame.EXIT_ON_CLOSEJFrame.EXIT_ON_CLOSE
setVisiblesetVisible public void public void setVisible(setVisible( boolean boolean whetherToShow)whetherToShow) Shows window or not, depending on value of Shows window or not, depending on value of
whetherToShowwhetherToShow ( ( truetrue oror falsefalse ) ) And And manymany moremore Documentation
8/8/2019 5 Graphical User Interfaces
7/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 7 7
ExampleExample
8/8/2019 5 Graphical User Interfaces
8/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 8 8
Drawing Text using a LabelDrawing Text using a Label
You can't work directly with a frame You can't work directly with a frame You don't put text directly into a frame You don't put text directly into a frame You don't draw directly into a frame You don't draw directly into a frameInsteadInstead Put text or drawings into aPut text or drawings into a component component Add Add the component to the framethe component to the frameFor text, the component you use is aFor text, the component you use is a label labelThe classThe class JLabelJLabel holds text holds text Construct aConstruct a JLabelJLabel containing the text you want containing the text you want Add the label to the frame Add the label to the frame
Documentation
8/8/2019 5 Graphical User Interfaces
9/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 9 9
ExampleExample
8/8/2019 5 Graphical User Interfaces
10/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 10 10
Drawing Text using a LabelDrawing Text using a Label You can use methods You can use methods setFontsetFont andand setColorsetColor of of JLabelJLabel to change the appearance of the text to change the appearance of the text ClassClass FontFont is in the is in the awtawt library library Make a new font, using a name for the font (such asMake a new font, using a name for the font (such as
arial ), a style (such as italics), and a point size arial ), a style (such as italics), and a point size(such as 64) (such as 64)
ClassClass ColorColor is also in the is also in the awtawt library library
Each color is specified by three numbersEach color is specified by three numbers thetheamounts of red, green, and blue in the coloramounts of red, green, and blue in the color Instead of the three numbers, you can use one of theInstead of the three numbers, you can use one of the
named constants,named constants, Color.REDColor.RED ,, Color.BLUEColor.BLUE , etc, etc
Font Documentation Color Documentation
8/8/2019 5 Graphical User Interfaces
11/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 11 11
ExampleExample
8/8/2019 5 Graphical User Interfaces
12/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 12 12
Drawing in a FrameDrawing in a Frame
The component you use to draw in a frame is aThe component you use to draw in a frame is apanelpanelThis is an object of classThis is an object of class JPanelJPanelIn order to draw, you must have aIn order to draw, you must have a graphicsgraphicscontext,context, which is an object of typewhich is an object of type GraphicsGraphicsStepsSteps Make aMake a JPanelJPanel object, and obtain a graphics context object, and obtain a graphics context Use the context to put graphics into the panelUse the context to put graphics into the panel Add the panel to the frame Add the panel to the frame
8/8/2019 5 Graphical User Interfaces
13/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 13 13
Shapes and ColorsShapes and ColorsThe JavaThe Java geometrygeometry library ( library ( java.awt.geomjava.awt.geom ) ) provides a number of basicprovides a number of basic shapesshapes Points, lines, rectangles, ellipses (which includePoints, lines, rectangles, ellipses (which include
circles ), and otherscircles ), and others The class names haveThe class names have 2D2D appended, and you have toappended, and you have to
indicate what kind of numbers you are using forindicate what kind of numbers you are using forcoordinates ( coordinates ( D oubleD ouble oror FloatFloat ))
Example: the class for a line specified using numbersExample: the class for a line specified using numbersof typeof type doubledouble is calledis called Line2 D.D oubleLine2 D.D ouble
8/8/2019 5 Graphical User Interfaces
14/63
8/8/2019 5 Graphical User Interfaces
15/63
8/8/2019 5 Graphical User Interfaces
16/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 16 16
Shapes and ColorsShapes and ColorsIf you change the windowIf you change the window by resizing it, forby resizing it, forexampleexample the drawings disappearthe drawings disappear
You must tell Java how to You must tell Java how to repaint repaint your pictureyour picturewhen necessarywhen necessaryInstead of drawing a panel in theInstead of drawing a panel in the program,program, youyoumust make amust make a new classnew class that that extendsextends thetheJPanelJPanel class, and write aclass, and write a paintComponentpaintComponentmethod within this classmethod within this class Context is a parameterContext is a parameter no need to get it no need to get it The method contains the same code formerlyThe method contains the same code formerlyplaced in the program, except for getting theplaced in the program, except for getting thegraphics context graphics context
8/8/2019 5 Graphical User Interfaces
17/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 17 17
ExampleExample
8/8/2019 5 Graphical User Interfaces
18/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 18 18
Reading Input Reading Input
In a graphical program, there are several waysIn a graphical program, there are several waysto read input to read input
A simple way is to use an A simple way is to use an option pane input option pane input dialog:dialog: Use theUse the showInputDialogshowInputDialog method of themethod of the JOptionPaneJOptionPane
class (in the Swing library )class (in the Swing library ) The method shows aThe method shows a dialog box,dialog box, which asks for input which asks for input
and returns what is entered as a stringand returns what is entered as a string A dialog of this kind forces the user to deal with A dialog of this kind forces the user to deal withit before doing anything elseit before doing anything else
8/8/2019 5 Graphical User Interfaces
19/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 19 19
ExampleExample
8/8/2019 5 Graphical User Interfaces
20/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 20 20
Visual Visual vs.vs. Numerical InformationNumerical Information
Visualization Visualization of information is very helpfulof information is very helpful A picture of some sort that represents numerical A picture of some sort that represents numericalinformation is frequently easier to interpret information is frequently easier to interpret Programs to visualize information are thereforePrograms to visualize information are thereforevery important very important Example: Information on an examinationExample: Information on an examination The number of grades in the categories F, D, C, B,The number of grades in the categories F, D, C, B,
and A areand A are 3, 4, 15, 9, 53, 4, 15, 9, 5 Better: The percentages of grades in the categoriesBetter: The percentages of grades in the categoriesare 8.3%, 11.1%, 41.7%, 25%, and 13.9%are 8.3%, 11.1%, 41.7%, 25%, and 13.9%
Better yet: a pictureBetter yet: a picture
8/8/2019 5 Graphical User Interfaces
21/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 21 21
PicturePicture a Bar Grapha Bar Graph
8/8/2019 5 Graphical User Interfaces
22/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 22 22
Bar GraphBar Graph mainmain
8/8/2019 5 Graphical User Interfaces
23/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 23 23
Bar Graph PanelBar Graph PanelFields and ConstructorFields and Constructor
8/8/2019 5 Graphical User Interfaces
24/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 24 24
Bar Graph PanelBar Graph PanelpaintComponentpaintComponent
8/8/2019 5 Graphical User Interfaces
25/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 25 25
SpreadsheetsSpreadsheets
An example of a program that makes use of An example of a program that makes use of data visualization is adata visualization is a spreadsheet spreadsheet
A spreadsheet allows its user to use a A spreadsheet allows its user to use arectangular table of rows and columns to enterrectangular table of rows and columns to enterand display dataand display dataIt also allows calculations such as addingIt also allows calculations such as addingelements of a row or column, to be specifiedelements of a row or column, to be specified
easilyeasily You can request various visualizations of your You can request various visualizations of yourdata, such as a bar graphdata, such as a bar graph
Excel
8/8/2019 5 Graphical User Interfaces
26/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 26 26
Events And ListenersEvents And Listeners
Using inheritanceUsing inheritanceEvent Event--driven programsdriven programsListenersListenersImplementing and using listenersImplementing and using listenersUsing inner classesUsing inner classes
8/8/2019 5 Graphical User Interfaces
27/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 27 27
Using InheritanceUsing InheritanceReviewReview Main window of a Java GUI is called aMain window of a Java GUI is called a frameframe
A frame holds other GUI components A frame holds other GUI components
TheThe content panecontent pane of a frame is the part you can draw onof a frame is the part you can draw on Doesn't interfere with menus, etcDoesn't interfere with menus, etc
A simple component that holds other components is a A simple component that holds other components is apanelpanel
You can make a panel and put it into a frame You can make a panel and put it into a frame
Instead of constructing a frame and changing it,Instead of constructing a frame and changing it,you can define your ownyou can define your own subclasssubclass of of JFrameJFrame
8/8/2019 5 Graphical User Interfaces
28/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 28 28
Panel into FramePanel into Frame
8/8/2019 5 Graphical User Interfaces
29/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 29 29
Inheriting fromInheriting from JFrameJFrame mainmain
8/8/2019 5 Graphical User Interfaces
30/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 30 30
Inheriting fromInheriting from JFrameJFrame ConstructorConstructor
8/8/2019 5 Graphical User Interfaces
31/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 31 31
Event Event--driven Programsdriven Programs
Old Old--fashioned programs are completely underfashioned programs are completely underthe control of thethe control of the programmerprogrammer Ordinarily, one statement is executed after anotherOrdinarily, one statement is executed after another Changes in execution order are brought about usingChanges in execution order are brought about using
conditional statements and loopsconditional statements and loops When a method is called, execution of programWhen a method is called, execution of program
waits until the method finishes, then continues waits until the method finishes, then continuesModern programsModern programs using a graphical userusing a graphical userinterface (GUI ) interface (GUI ) areare event event--drivendrivenThe controller of an event The controller of an event--driven program is thedriven program is theGUI frameworkGUI framework
8/8/2019 5 Graphical User Interfaces
32/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 32 32
Event Event--driven Programsdriven Programs
The GUI framework is the (behindThe GUI framework is the (behind- -thethe--scenes ) scenes ) "main program""main program" Your Your mainmain method usually just gets thing startedmethod usually just gets thing started
You write methods that You write methods that react to eventsreact to events TheThe useruser can perform any one of many different can perform any one of many different
actions,actions, which your program cannot anticipatewhich your program cannot anticipate The GUI frameworkThe GUI framework detects that andetects that an event event hashas
occurredoccurred TheThe frameworkframework informs your program, which can informs your program, which can
thenthen react react to the event to the event This is doneThis is done by the framework, using your methodsby the framework, using your methods
8/8/2019 5 Graphical User Interfaces
33/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 33 33
ListenersListenersMany events can occurMany events can occur Press mouse button, enter text, etc.Press mouse button, enter text, etc.The framework must inform your programThe framework must inform your program
somehowsomehowIf each of your objects were told about allIf each of your objects were told about allevents, they would be overwhelmed with oftenevents, they would be overwhelmed with oftenirrelevant informationirrelevant information Example: only the window in which text is enteredExample: only the window in which text is entered
would care that text was entered therewould care that text was entered there An object that cares about an event, An object that cares about an event, registersregistersa listenera listener with the GUI frameworkwith the GUI frameworkOnly listeners are informed about eventsOnly listeners are informed about events
8/8/2019 5 Graphical User Interfaces
34/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 34 34
Implementing And Using ListenersImplementing And Using ListenersEach listener is a class written by theEach listener is a class written by theprogrammerprogrammerIn order that the framework know which methodIn order that the framework know which method
to call, the listener class must implement ato call, the listener class must implement aparticularparticular interfaceinterfaceOnce a listener class is implemented, an object Once a listener class is implemented, an object of that type is created, and registered as aof that type is created, and registered as alistenerlistener
Everything after creating original frame isEverything after creating original frame is event event drivendriven events occur, listeners are informed,events occur, listeners are informed,and their methods are called,and their methods are called, by the frameworkby the framework
Documentation for M ouseListener interface
8/8/2019 5 Graphical User Interfaces
35/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 35 35
Using Inner ClassesUsing Inner ClassesExample: a "hello" message that changes to aExample: a "hello" message that changes to a"goodbye" message when the user clicks it "goodbye" message when the user clicks it Several different classes are needed for theSeveral different classes are needed for theevent event--driven approach, and these classes must driven approach, and these classes must communicatecommunicate The frame is the main application window and must The frame is the main application window and must
Create a label to hold the messagesCreate a label to hold the messagesCreate and register a listener for the mouse clickCreate and register a listener for the mouse click
The label holds the message and must The label holds the message and must Be available to both the frame (which sets it up ) and theBe available to both the frame (which sets it up ) and thelistener (which changes its message )listener (which changes its message )
The listener for a mouse click which must The listener for a mouse click which must Be available to the frame (for creation and registration )Be available to the frame (for creation and registration )React to a mouse clickReact to a mouse click
8/8/2019 5 Graphical User Interfaces
36/63
8/8/2019 5 Graphical User Interfaces
37/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 37 37
Example (1 ) Example (1 ) ConstructorConstructor
8/8/2019 5 Graphical User Interfaces
38/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 38 38
Example (2 ) Example (2 ) An Inner Class An Inner Class
8/8/2019 5 Graphical User Interfaces
39/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 39 39
Example (3 ) Example (3 ) Listener ClassListener Class
8/8/2019 5 Graphical User Interfaces
40/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 40 40
LayoutsLayouts
BasicsBasicsFlow layout Flow layout Border layout Border layout Other layoutsOther layouts
8/8/2019 5 Graphical User Interfaces
41/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 41 41
BasicsBasics
A typical GUI application contains many A typical GUI application contains manycomponentscomponents Also called controls or widgets Also called controls or widgets Examples: labels, buttons, text fieldsExamples: labels, buttons, text fieldsThese components must beThese components must be laid out laid out, , i.e., placedi.e., placedon the screenon the screenRather than specify exact locations on theRather than specify exact locations on the
screen, you can leave placement to ascreen, you can leave placement to a layout layout manager,manager, which does the layout automaticallywhich does the layout automatically Redone when window is redrawn or resizedRedone when window is redrawn or resized
8/8/2019 5 Graphical User Interfaces
42/63
8/8/2019 5 Graphical User Interfaces
43/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 43 43
ExampleExample
8/8/2019 5 Graphical User Interfaces
44/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 44 44
Border Layout Border Layout A A border layout border layout places components in different places components in different regions chosen when you add them regions chosen when you add themSizes of added components will be changedSizes of added components will be changed
You can change the layout of a panel You can change the layout of a panel or just or just place components into the frame directly, sinceplace components into the frame directly, sinceframes use border layouts by default frames use border layouts by default
8/8/2019 5 Graphical User Interfaces
45/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 45 45
Giving a Panel a Border Layout Giving a Panel a Border Layout
8/8/2019 5 Graphical User Interfaces
46/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 46 46
Using the Frame s Border Layout Using the Frame s Border Layout
8/8/2019 5 Graphical User Interfaces
47/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 47 47
Other LayoutsOther Layouts
Border and flow layouts are generally allBorder and flow layouts are generally allyou needyou need
Some other layouts you can use ( Some other layouts you can use (see seedocumentationdocumentation )) Grid layout Grid layout Grid bag layout Grid bag layout Box layout Box layout
(You don't actually use a box layout; you just use(You don't actually use a box layout; you just useaa BoxBox instead of ainstead of a JPanelJPanel ))
8/8/2019 5 Graphical User Interfaces
48/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 48 48
ComponentsComponents
PanelsPanelsButtonsButtonsText componentsText componentsChoicesChoicesMenusMenus
8/8/2019 5 Graphical User Interfaces
49/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 49 49
PanelsPanelsThe standard content pane uses a borderThe standard content pane uses a borderlayout, which changeslayout, which changes sizessizes of componentsof components
A panel uses a flow layout, which doesn t A panel uses a flow layout, which doesn t
change sizeschange sizesSolution: add components to panels, then addSolution: add components to panels, then addthe panels to the content panethe panels to the content paneThe most important use of panels is to holdThe most important use of panels is to holdseveralseveral components in the same regioncomponents in the same region
8/8/2019 5 Graphical User Interfaces
50/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 50 50
ExampleExample No PanelsNo Panels
8/8/2019 5 Graphical User Interfaces
51/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 51 51
ExampleExample Using PanelsUsing Panels
8/8/2019 5 Graphical User Interfaces
52/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 52 52
Comparison of Output Comparison of Output Without PanelsWithout Panels
With PanelsWith Panels
8/8/2019 5 Graphical User Interfaces
53/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 53 53
Panels with Many ComponentsPanels with Many Components
8/8/2019 5 Graphical User Interfaces
54/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 54 54
ButtonsButtons
Instead of a label, we can use aInstead of a label, we can use a button,button, whichwhichallowsallows user interactionuser interaction
A button is controlled using an A button is controlled using an action listeneraction listenerThe only method an action listener has isThe only method an action listener has isactionPerformedactionPerformed
If an action listener isIf an action listener is registeredregistered with a button,with a button,itsits actionPerformedactionPerformed method is calledmethod is called by theby theframeworkframework whenever the button is clickedwhenever the button is clicked
8/8/2019 5 Graphical User Interfaces
55/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 55 55
ExampleExample
8/8/2019 5 Graphical User Interfaces
56/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 56 56
Text ComponentsText Components A A text fieldtext field is a window into which you can enteris a window into which you can entera line of text (we've used them already, but just a line of text (we've used them already, but just to show a label inside a bordered rectangle )to show a label inside a bordered rectangle )Since a text field has no label, you usually makeSince a text field has no label, you usually makea panel, and add both a label and a text field toa panel, and add both a label and a text field tothe panelthe panel
An action listener can be added to a text field An action listener can be added to a text field the action occurs when the user presses thethe action occurs when the user presses the
enterenter key after entering text key after entering text A A text areatext area is a twois a two--dimensional window intodimensional window intowhich you can enter text which you can enter text see thesee thedocumentationdocumentation
8/8/2019 5 Graphical User Interfaces
57/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 57 57
ExampleExample
8/8/2019 5 Graphical User Interfaces
58/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 58 58
Improvement Improvement
At beginning, buttons are disabled: enableButtons( false )
Puts focus on one
of the buttons oncea name is entered
8/8/2019 5 Graphical User Interfaces
59/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 59 59
ChoicesChoicesWhen you want the user to make a selectionWhen you want the user to make a selectionfrom among several items, rather than have afrom among several items, rather than have abutton for each item, you may use abutton for each item, you may use a list list Lists (classLists (class JListJList ) have their own kinds of ) have their own kinds of events and listenersevents and listenersOther possibilities exist for listing itemsOther possibilities exist for listing items A A combo boxcombo box allows entering an item as well asallows entering an item as well as
selecting one of those on the list selecting one of those on the list Buttons specialized for making choicesButtons specialized for making choices
Radio buttonsRadio buttons allow you to select allow you to select oneone of several itemsof several itemsCheck boxesCheck boxes allow you to select a number of itemsallow you to select a number of items
8/8/2019 5 Graphical User Interfaces
60/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 60 60
ExampleExample
8/8/2019 5 Graphical User Interfaces
61/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 61 61
MenusMenus
Menus present choices in a special kind of list Menus present choices in a special kind of list Menus (classMenus (class J MenuJ Menu ) are contained in a) are contained in a menumenubarbar (class(class J MenuBarJ MenuBar )), , and containand contain menu itemsmenu items(class(class J MenuItemJ MenuItem ))ProcedureProcedure Make a menu barMake a menu bar Set the menu bar of the frame to the one you'veSet the menu bar of the frame to the one you've
mademade Add menus to the menu bar Add menus to the menu bar To each menu addTo each menu add menu itemsmenu items (A menu is itself a kind of menu item , so you can(A menu is itself a kind of menu item , so you can
have menus within menus )have menus within menus )
8/8/2019 5 Graphical User Interfaces
62/63
Copyright 2008 by John S. MallozziCopyright 2008 by John S. Mallozzi 62 62
MenusMenus (continued) (continued) You can have either You can have either dropdrop--downdown menus ormenus or poppop--up menusup menus See the documentation for popSee the documentation for pop- -up menusup menus
Instead of action listeners, it is convenient toInstead of action listeners, it is convenient touseuse actionsactions An action (implements interface An action (implements interface A ctionA ction , but generally, but generally
extends classextends class A bstract A ctionA bstract A ction ) allows you to use the) allows you to use thesame action for more than one component same action for more than one component
Same methodSame method actionPerformedactionPerformed for bothfor both For example, you can have both menu items andFor example, you can have both menu items andcorresponding buttons behave in the same waycorresponding buttons behave in the same way
Appearance is also the same for components using Appearance is also the same for components usingthe same actionthe same action
8/8/2019 5 Graphical User Interfaces
63/63
ExampleExample
Top Related