Chapter 7 GUI design
description
Transcript of Chapter 7 GUI design
Chapter 7 GUI design
So far this semesterHave programmed in a stop and wait mode
Program displays dialog box and waits for user to respondThis was the way programs were previously created (back in my early days)
Modern design (Event driven)Today’s users control the program
They decide what they want to do nextUser’s control the flow of the programThing about MS word• many options to choose from
Programming in an event driven environment requires careful GUI design
Section 7.1 AWT, SwingGUI design is also a study of Object Orientation
Creating GUI is done by using pre-existing objects
Early versions of Java used AWTJava 1.2 introduced a new library called Swing
Swing versus AWTAWT matches corresponding components in the OS
platform dependentSwing API looks the same on all platforms
platform independent
AWT versus SwingAWT relies on the platform peer component to draw it.Swing uses components written entirely in Java is called lightweight component
Categories of ClassesSwing GUI componentAWT layout managerAWT event classesAWT listener classes
Top of page 441
GUI component classesIncludes windows objects
buttonstext fieldsmenu itemscontainers• panels• applets
ExampleSee components bottom of page 441GUI design page 442
HierarchyPage 4434 abstract classes
ContainerComponentJComponentAbstractButton
ContainersContainers hold components
Panels are containers• group components
Windows are containers• top level displayed by OS windows
contains panelsApplet is special kind of container• Applet is contained in a window,
specifically the browser
Browser applet InteractionApplet context is the browser or applet viewerApplets are caused to run in the browser via the applet tag
bottom of page 444
Browser create objectThe browser instantiates your object and then calls init
DistanceGUI dGUI new DistanceGUI();dGUI.init();
When user loads different page or overlays browser calls stopWhen user returns calls startUser exits browser calls destroy
Your taskProperly override the init method in Japplet to perform the necessary tasks.See diagram top of page 446.
Designing your GUIThis is the GUI we need to create
Adding componentsWe need to add the components in the proper orderSee code pages 448 - 449
OrderWe declare as class data fields
inputoutputtoKmstoMiles
need to be used though out the class
OrderDeclare as local variables (to init())
inputLabdataPanelbuttonPanel
These are the “objects” we are placing in our GUI (this slide and previous)
Placing objectsNow that we declared objects we must place them correctly
First we set the layout manager • We set this to FlowLayout (left to right)
(top to bottom) more laterWe add components to the container via add() methodWe must add the components before adding the container.
CodedataPanel.add(inputLab);
adds the inputLab label to the PaneldataPanel.add(input);
adds the input field to the PanelgetContentPane().add(dataPanel);
What does “getContentPane” look like?Adds the dataPanel to the applets content pane
Data Panel
Input Label
Input Field has “focus”
Codeinput.requestFocus();
puts the cursor in the input field it “has focus”
code then repeats previous slide to add the buttons to the button panel and the panel to the pane
Code getContentPane().add(output);
adds the output area to the pane
Output area
2 more important lines toMiles.addActionListener(this);
toKms.addActionListener(this);
Makes the buttons “work” Has them listen for user eventsMore in next section 7.3
“Extras”Other methods exist to change components appearancecomponent.setBackground(Color col);component.setForeground(Color col);component.setBorder(Border bor);
ExamplebuttonPanel.setBorder(BorderFactory.
createTitledBorder("Control Panel"));
Java Event Driven ModelOn the scale of “cool”, “very cool” or “super cool”Event driven programming is “super cool”Our program then responds to the user rather then the user responding to our program.
Java Event ModelHaw events are handled is the event model.An event generator is an object that generates events.An event listener is an object that listens for and responds to events.The AWTEvent class handles these functions for Java
How toThe event generator and event listener must “know about” each other for this to work.Must register itself with listener.
// Register applet as listener for button toMiles.addActionListener(this); toKms.addActionListener(this);
FormatgeneratorObject.addActionListener
(listenerObject);
ActionListener is an interface not a classA class must implement ActionListener
Now What?We have solved half the problemWe have a listener registered for the generatorsNow we must make the program respond to these events
InterfaceRemember interfaces contain abstract methods.Implementers must define those methodsActionListener has one method
actionPerformed(ActionEvent e);
AutomaticactionPerformed method is called automatically when event occurs.You do not need to call this, java does this for youWhat do we want to do when event occurs?See code page 458
Methods and ObjectsSee table of methods bottom page 459Doing GUI design is simply a matter of learning to use the java GUI classes and methods
SwingAWT
BTWDid you notice something “very cool” about the applet?No loop but program continues runningJust keeps responding to the eventA “built in” loop until you exit the app
Section 7.4 GUI in applicationCreating a GUI “application”Use the same basic techniques as for AppletBasically 3 changes to our applet GUI will make it an application
Step 1Instead of extending JApplet we extend Jframe
JFrame is a typical GUI “window”It has:• border• title• buttons, minimize, maximize, close
Step 2Replace the init() method with a constructor.The new constructor has the same body as init().Used when application creates an instance of the object.
Step 3Write a main method for the application class.Create the object and takes care of properly closing it when user “closes” window.
ExampleCode on pages 462-463 of text.Application class on 464.See running code in Jbuilder and a “new” way of testing our code.
embed main method directly in the worker class.Creates instance of itself
Section 7.5 Making choicesLook at Check boxes
not mutually exclusivecan check many
Look at Radio buttonsmutually exclusivecan only check one
Check boxesProvide boolean data to program
true (checked)false (not checked)
See GUI page 465See code pages 466 – 467Run code in JbuilderAlso look at in HTML
Radio ButtonsSince radio buttons are designed to be mutually exclusive
can put radio buttons in a grouponly one can be pickedswing class ButtonGroupButtonGroup controls that can only select one
CodeCode puts buttons into an array
see page 469first create array of buttonsfor loop to • put buttons on panel• add buttons to group• registers action listener
Bottom loop to find one choosen
Code complete exampleReview code pages 470 – 4713 arrays of radio buttons3 groups of code to set these upactionPerformed checks array to see one choosenlook at in HTML
Combo boxesAllows selection of one of many choicessetSelectedIndex() returns index of the selection (starts with 0)Can initialize using arrays of strings
can also use addItem to add individuallyReview code 472-473Look at in JBuilder
ReviewMethods for making choices
page 475
Section 7.6This is our old friend the phone book classYou looked at this several different time.They have now front-ended it with a GUIReview the code pages 480 - 483
Section 7.7 Inner classesSometimes methods get quite lengthyFor instance the actionPerformed()You can create separate listener classes
respond to specific eventrespond to group of events
These should be inner classeswholly contained in GUI classallows for referencing private data fields
Differences?Class visibility is private
only used within the classAction event only for submit button
do not need to check sourcealready checked before sent to this class
See code pages 486 – 487See code page 488
Changes to originalThe class (PhoneBookGUI) no longer implements ActionListenerBottom of page 488 shows code to register new inner classes as ActionListeners.Inner classes nested somewhere in ClassNot in method
typically at very beginningOr more likely at very end
Java Layout ManagersDetermines size and placements of objectsDefaults
Applet flowJApplet borderPanel or JPanel flow
Can change via setLayout()
Flow LayoutSimplestPuts as many components in row as possibleWhen row is filled go to next rowIn row components are centered (default), left or right justified
Border LayoutSets up 5 areas
1 component per areaCan put a container (panel) with multiple components in an area
See layout middle page 491
Box layoutNew layout in SwingPlacement in
single row (X_AXIS)single column (Y_AXIS)
See example middle 492See total example pages 493 - 495
Grid LayoutAllows use to create a 2d grid to place components.See 4x3 example top of page 497Code page 498 - 499
Payroll appReview application page 499 – 508Show GUI designer in Jbuilder
newapplicationthen use designer tabcreate panel set flow manager to nulladd some controls
Common Programming errorsCreate listener for event generatorMake sure you implement required interface.