Chapter 7 GUI design

58
Chapter 7 GUI design

description

Chapter 7 GUI design. So far this semester. Have programmed in a stop and wait mode Program displays dialog box and waits for user to respond This was the way programs were previously created (back in my early days). Modern design (Event driven). Today’s users control the program - PowerPoint PPT Presentation

Transcript of Chapter 7 GUI design

Page 1: Chapter 7 GUI design

Chapter 7 GUI design

Page 2: 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)

Page 3: Chapter 7 GUI design

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

Page 4: Chapter 7 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

Page 5: Chapter 7 GUI design

Swing versus AWTAWT matches corresponding components in the OS

platform dependentSwing API looks the same on all platforms

platform independent

Page 6: Chapter 7 GUI design

AWT versus SwingAWT relies on the platform peer component to draw it.Swing uses components written entirely in Java is called lightweight component

Page 7: Chapter 7 GUI design

Categories of ClassesSwing GUI componentAWT layout managerAWT event classesAWT listener classes

Top of page 441

Page 8: Chapter 7 GUI design

GUI component classesIncludes windows objects

buttonstext fieldsmenu itemscontainers• panels• applets

Page 9: Chapter 7 GUI design

ExampleSee components bottom of page 441GUI design page 442

Page 10: Chapter 7 GUI design

HierarchyPage 4434 abstract classes

ContainerComponentJComponentAbstractButton

Page 11: Chapter 7 GUI design

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

Page 12: Chapter 7 GUI design

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

Page 13: Chapter 7 GUI design

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

Page 14: Chapter 7 GUI design

Your taskProperly override the init method in Japplet to perform the necessary tasks.See diagram top of page 446.

Page 15: Chapter 7 GUI design

Designing your GUIThis is the GUI we need to create

Page 16: Chapter 7 GUI design

Adding componentsWe need to add the components in the proper orderSee code pages 448 - 449

Page 17: Chapter 7 GUI design

OrderWe declare as class data fields

inputoutputtoKmstoMiles

need to be used though out the class

Page 18: Chapter 7 GUI design

OrderDeclare as local variables (to init())

inputLabdataPanelbuttonPanel

These are the “objects” we are placing in our GUI (this slide and previous)

Page 19: Chapter 7 GUI design

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.

Page 20: Chapter 7 GUI design

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

Page 21: Chapter 7 GUI design

Data Panel

Input Label

Input Field has “focus”

Page 22: Chapter 7 GUI design

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

Page 23: Chapter 7 GUI design

Code getContentPane().add(output);

adds the output area to the pane

Output area

Page 24: Chapter 7 GUI design

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

Page 25: Chapter 7 GUI design

“Extras”Other methods exist to change components appearancecomponent.setBackground(Color col);component.setForeground(Color col);component.setBorder(Border bor);

Page 26: Chapter 7 GUI design

ExamplebuttonPanel.setBorder(BorderFactory.

createTitledBorder("Control Panel"));

Page 27: Chapter 7 GUI design

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.

Page 28: Chapter 7 GUI design

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

Page 29: Chapter 7 GUI design

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);

Page 30: Chapter 7 GUI design

FormatgeneratorObject.addActionListener

(listenerObject);

ActionListener is an interface not a classA class must implement ActionListener

Page 31: Chapter 7 GUI design

Now What?We have solved half the problemWe have a listener registered for the generatorsNow we must make the program respond to these events

Page 32: Chapter 7 GUI design

InterfaceRemember interfaces contain abstract methods.Implementers must define those methodsActionListener has one method

actionPerformed(ActionEvent e);

Page 33: Chapter 7 GUI design

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

Page 34: Chapter 7 GUI design

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

Page 35: Chapter 7 GUI design

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

Page 36: Chapter 7 GUI design

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

Page 37: Chapter 7 GUI design

Step 1Instead of extending JApplet we extend Jframe

JFrame is a typical GUI “window”It has:• border• title• buttons, minimize, maximize, close

Page 38: Chapter 7 GUI design

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.

Page 39: Chapter 7 GUI design

Step 3Write a main method for the application class.Create the object and takes care of properly closing it when user “closes” window.

Page 40: Chapter 7 GUI design

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

Page 41: Chapter 7 GUI design

Section 7.5 Making choicesLook at Check boxes

not mutually exclusivecan check many

Look at Radio buttonsmutually exclusivecan only check one

Page 42: Chapter 7 GUI design

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

Page 43: Chapter 7 GUI design

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

Page 44: Chapter 7 GUI design

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

Page 45: Chapter 7 GUI design

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

Page 46: Chapter 7 GUI design

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

Page 47: Chapter 7 GUI design

ReviewMethods for making choices

page 475

Page 48: Chapter 7 GUI design

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

Page 49: Chapter 7 GUI design

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

Page 50: Chapter 7 GUI design

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

Page 51: Chapter 7 GUI design

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

Page 52: Chapter 7 GUI design

Java Layout ManagersDetermines size and placements of objectsDefaults

Applet flowJApplet borderPanel or JPanel flow

Can change via setLayout()

Page 53: Chapter 7 GUI design

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

Page 54: Chapter 7 GUI design

Border LayoutSets up 5 areas

1 component per areaCan put a container (panel) with multiple components in an area

See layout middle page 491

Page 55: Chapter 7 GUI design

Box layoutNew layout in SwingPlacement in

single row (X_AXIS)single column (Y_AXIS)

See example middle 492See total example pages 493 - 495

Page 56: Chapter 7 GUI design

Grid LayoutAllows use to create a 2d grid to place components.See 4x3 example top of page 497Code page 498 - 499

Page 57: Chapter 7 GUI design

Payroll appReview application page 499 – 508Show GUI designer in Jbuilder

newapplicationthen use designer tabcreate panel set flow manager to nulladd some controls

Page 58: Chapter 7 GUI design

Common Programming errorsCreate listener for event generatorMake sure you implement required interface.