Upload
sharyl-french
View
223
Download
0
Tags:
Embed Size (px)
Citation preview
1
Intro to Programming & Algorithm Design
GUI
Copyright 2003 by Janson Industries
This presentation can be viewed on line in a file named: ch11.IntrotoProg.GUI.ppt
Copyright 2014 by Janson Industries2
Objectives Explain
Event driven programming
Designing a GUI
Threads
Demonstrate
GUI components
How to code a GUI
Animation
Copyright 2014 by Janson Industries3
GUI What do you think of the command
line interface?
That's why there are GUI's
Instead of commands and syntax, GUI's allow users to point and click on:
Icons
Buttons
Menu items
Copyright 2014 by Janson Industries4
GUI GUI's help to cut down on errors
by only allowing valid input
Instead of letting users specify a value, user given
A menu of values
Checkboxes associated with values
A drop down list of values
Copyright 2014 by Janson Industries5
Events An event is when a user does something Clicks, double clicks, right clicks,
presses a key, etc.
Each GUI component is tied to an event handler (in Java a listener)
The listener "reacts" to an event Of course, the programmer codes this
"reaction" Yep, sequence, selection and loops!
This type of programming is called event-driven
Copyright 2014 by Janson Industries6
GUI Components Labels: display text
Text fields: accept and display text
Button: small square that when clicked, appears to go down
List box: a text field and a small button usually with an arrow head icon Clicking the button results in the text
field being expanded and a menu being displayed inside it
Copyright 2014 by Janson Industries7
Components Check box: label and a small
square text field that can display a check mark
Option buttons: label and a small round text field that can display a black dot Only one option button can be
selected Also called radio buttons or a check
box group
Copyright 2014 by Janson Industries8
Components Have properties that are
controlled with setters/getters
Common properties
Size
Location
Text Font, size, foreground color,
background color, alignment, etc.
Copyright 2014 by Janson Industries9
Components Most IDEs provide a drag/drop
visual editor to define the GUI Drag and drop the GUI components
from a "tool box" The IDE generates the code
Clicking on a component will display a list of all the properties values Programmer can change the values
and the IDE will generate the code
Copyright 2014 by Janson Industries10
In RAD, components dragged and
dropped from the palette
Copyright 2014 by Janson Industries11
Property pane provides control
over all properties values
When component selected, resize handles allow you to
control size
Copyright 2014 by Janson Industries12
Events Components react to different
events Clicking a label does nothing
Even if 2 components react to the same event they may react differently
Clicking a text field puts the cursor in the text field
Clicking a check box selects or deselects the check box
Copyright 2014 by Janson Industries13
Designing a GUI It should be predictable (follow
standards) Menu bars at top of screen
Standard icons
Using unusual icons or layouts will cause confusion
Users will make mistakes
May not use application
Copyright 2014 by Janson Industries14
Designing a GUI It should be pleasing to the eye
No weird color combinations
No distracting graphics
It should be easy to read
No fancy fonts or small size
Good contrast between text color and background color
Not too many components or options
Copyright 2014 by Janson Industries15
Designing a GUI Customizable
Users can drag components where they want them
Change color schemes Suppress/add options or components
Forgiving No dead ends Help info Easy navigation
Application index, search
Copyright 2014 by Janson Industries16
Designing a GUI GUI is only a means to an end
The GUI should make the user more productive
Enable users to specify the input and actions more efficiently
After all options specified, the real work of the application begins
Copyright 2014 by Janson Industries17
Story Boards Mock ups of the screens
Shows each individual screen and all of its components.
Welcome to the Pizza Palace
What would you like to order?
Pizza Soda
Finished Exit
Copyright 2014 by Janson Industries18
Story Boards In addition, create
Object dictionary
Interactivity diagram
Pizza Order
Size? Toppings Double Triple
6 inch Pepperoni12 inch Ham18 inch Mushroom
Order Exit
Copyright 2014 by Janson Industries19
Object Dictionary Will list each component and
Screens it appears on Variables it can affect Any methods/modules tied to
Soda Order
Size? Flavor?
12 oz Cola20 oz Lemon/Lime46 oz Cherry
Order Exit
Copyright 2014 by Janson Industries
Order Total
The following items were ordered:
# size item: ###.### size item: ###.## # size item: ###.##
For a total of:
# soda(s) and # pizza(s)
The order amount is $#,###.##
20
Story Boards
Print Exit
Copyright 2014 by Janson Industries21
Designing a GUI Each component is an object
Like all other objects, usually assigned to a variable
Considered the name of the GUI component
Copyright 2014 by Janson Industries22
Object Screen Variables MethodsLabel welcomeLbl Welcome none noneLabel orderLbl Welcome none noneRadioButton pizzaRB Welcome none getItem()RadioButton sodaRB Welcome none getItem()Button finishedBtn Welcome sodaCtr, pizzaCtr,
orderTotalcalcTotals(orderedItems)
Button exitBtn All none windowClosing(Window Event)Label pizzaOrdLbl PizzaOrder none noneLabel pizzaSizeLbl PizzaOrder none noneLabel toppingsLbl PizzaOrder none noneRadioButton 6inRB PizzaOrder pizza noneRadioButton 12inRB PizzaOrder pizza noneRadioButton 18inRB PizzaOrder pizza noneCheckbox pepCB PizzaOrder selectedToppings noneCheckbox hamCB PizzaOrder selectedToppings noneCheckbox shroomCB PizzaOrder selectedToppings noneRadioButton dblPepRB PizzaOrder selectedToppings noneRadioButton dblHamRB PizzaOrder selectedToppings noneRadioButton dblShroomRB PizzaOrder selectedToppings noneRadioButton tplPepRB PizzaOrder selectedToppings noneRadioButton tplHamRB PizzaOrder selectedToppings noneRadioButton tplShroomRB PizzaOrder selectedToppings noneButton orderPizzaBtn PizzaOrder pizza getPizza()
Copyright 2014 by Janson Industries23
Object Screen Variables MethodsLabel sodaOrdLbl SodaOrder none noneLabel sodaSizeLbl SodaOrder none noneLabel sodaFlavorsLbl SodaOrder none noneRadioButton 12ozRB SodaOrder soda noneRadioButton 20ozRB SodaOrder soda noneRadioButton 46ozRB SodaOrder soda noneRadioButton colaRB SodaOrder soda noneRadioButton lemLimeRB SodaOrder soda noneRadioButton cherryRB SodaOrder soda noneButton orderSodaBtn SodaOrder soda getSoda()Label ordTotLbl OrderTotal none noneLabel itemsLbl OrderTotal none noneLabel itemLbl1-10 OrderTotal none noneLabel itemsTotLbl OrderTotal none noneLabel itemsTotInfoLbl OrderTotal none noneLabel ordAmountLbl OrderTotal none noneButton printBtn OrderTotal soda printReceipt()
Object Dictionary
Copyright 2014 by Janson Industries24
Why bother?
Besides clearly defining each component
When changing a component, can easily find affected screens
Therefore can test more easily to see affect of the change
Object Dictionary
Copyright 2014 by Janson Industries25
Show which screens call other screens
PizzaApp pretty simple
Interactivity Diagram
Welcome
SodaOrder
PizzaOrder
OrderTotal
Copyright 2014 by Janson Industries26
As mentioned, GUI component properties must be specified Size and location
For Java frames, must set visible property to true
For frame components, must add them to the frame
To react to actions, must define listeners and add to components
GUI Java Example
Copyright 2014 by Janson Industries27
So, to get our Frame as seen here, need a class that extends Frame and imports all the component classes
Copyright 2014 by Janson Industries28
GUI Java Exampleimport java.awt.Frame;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;import java.awt.CheckboxGroup;import java.awt.Rectangle;import java.awt.Label;import java.awt.Font;import java.awt.Checkbox;import java.awt.Dimension;import java.awt.Point;import java.awt.Button;
public class Welcome extends Frame implements ActionListener, WindowListener, ItemListener {
Copyright 2014 by Janson Industries
this.setLayout(null);this.setTitle("Frame");
this.setBounds(new Rectangle(100, 100, 700, 500));this.setVisible(true);
29
GUI Java Example
private Label welcomeLbl = null;private Label orderLbl = null;private Checkbox pizzaRB = null;private Checkbox sodaRB = null;private Button exitBtn = null;private Button finishedBtn = null;private CheckboxGroup itemCBG = new CheckboxGroup();
Create variables for the GUI componentsWhere did the names
come from?
Set some frame properties
Copyright 2014 by Janson Industries30
GUI Java Example
orderLbl = new Label();orderLbl.setFont(new Font("Verdana", Font.PLAIN, 28));orderLbl.setSize(new Dimension(377, 39));orderLbl.setLocation(new Point(161, 148));orderLbl.setText("What would you like to order?");
welcomeLbl = new Label();welcomeLbl.setBounds(new Rectangle(5, 56, 689, 39));welcomeLbl.setFont(new Font("Verdana", Font.PLAIN, 36));welcomeLbl.setAlignment(Label.CENTER);welcomeLbl.setText("Welcome to the Pizza Palace");
Create the label objects and set their
properties
Copyright 2014 by Janson Industries31
GUI Java Exampleprivate Checkbox getPizzaRB() {
if (pizzaRB == null) { pizzaRB = new Checkbox(); pizzaRB.setBounds(new Rectangle(295, 240, 89,
23)); pizzaRB.setFont(new Font("Verdana", Font.PLAIN,
24)); pizzaRB.setLabel(" Pizza"); pizzaRB.setCheckboxGroup(itemCBG);}return pizzaRB;
}private Checkbox getSodaRB() {
if (sodaRB == null) { sodaRB = new Checkbox(); sodaRB.setLabel(" Soda"); sodaRB.setSize(new Dimension(89, 23)); sodaRB.setLocation(new Point(295, 282)); sodaRB.setFont(new Font("Verdana", Font.PLAIN,
24)); sodaRB.setCheckboxGroup(itemCBG);}return sodaRB;
}
For more complicated objects, create a separate method
Copyright 2014 by Janson Industries32
GUI Java Exampleprivate Button getExitBtn() {
if (exitBtn == null) { exitBtn = new Button(); exitBtn.setBounds(new Rectangle(601, 457, 58,
23)); exitBtn.setLabel("Exit");}return exitBtn;
}
private Button getFinishedBtn() {if (finishedBtn == null) { finishedBtn = new Button(); finishedBtn.setBounds(new Rectangle(510, 457, 58,
23)); finishedBtn.setLabel("Finished");}return finishedBtn;
}
Copyright 2014 by Janson Industries33
GUI Java Example
this.add(welcomeLbl, null);this.add(orderLbl, null);this.add(getPizzaRB(), null);this.add(getSodaRB(), null);this.add(getExitBtn(), null);this.add(getFinishedBtn(), null);
Must add all the components to the
frame
Frame will look good but only problem is that it doesn't do anything
You can click all you want but none of the components are "enabled"
Need listeners!
Copyright 2014 by Janson Industries34
Lots of different types WindowListener ItemListener ActionListener
Can create a separate class and define it as a listener
Or simply have the frame implement the listener interface That's what we did
Java Listeners
public class Welcome extends Frame implements ActionListener, WindowListener, ItemListener {
Copyright 2014 by Janson Industries35
Each listener requires at least one method be coded in the "implementing class" When an event occurs the
associated method will be called
ActionListener requires actionPerformed method
Java Listeners
public void actionPerformed(ActionEvent e) {
System.exit(0);}
Copyright 2014 by Janson Industries36
Must tie listener to a component
WindowListener requires seven methods to be coded
Java Listeners
private Button getExitBtn() {if (exitBtn == null) {
exitBtn = new Button();exitBtn.setBounds(new Rectangle(601, 457, 58,
23));exitBtn.setLabel("Exit");exitBtn.addActionListener(this);
}return exitBtn;
}
Copyright 2014 by Janson Industries37
Of course, they all don't have to do something
Java Listeners
public void windowActivated(WindowEvent e) { }
public void windowClosed(WindowEvent e) { }
public void windowClosing(WindowEvent e) { this.dispose();
}
public void windowDeactivated(WindowEvent e) { }
public void windowDeiconified(WindowEvent e) { }
public void windowIconified(WindowEvent e) { }
public void windowOpened(WindowEvent e) { }
Copyright 2014 by Janson Industries38
The ItemListener poses a special problem Going to be tied to 2 components
When itemStateChanged (the associated method) invoked Needs to figure out which radio
button was clicked
Easiest way: check each radio buttons state
Java Listeners
Copyright 2014 by Janson Industries
public void itemStateChanged(ItemEvent e) {
if (pizzaRB.getState()) {new PizzaOrder();
}else if (sodaRB.getState()) {
new SodaOrder(); }
} 39
First have to add listener to the radio buttons
Then code itemStateChanged
Java Listeners
pizzaRB.addItemListener(this);
sodaRB.addItemListener(this);
Copyright 2014 by Janson Industries40
Java Listeners Must compile PizzaOrder and
SodaOrder before Welcome
Copyright 2014 by Janson Industries41
When Welcome displayed, Close Window and Exit button should work
Copyright 2014 by Janson Industries42
Clicking Pizza Radio Button...
Copyright 2014 by Janson Industries43
Clicking Soda Radio Button...
Copyright 2014 by Janson Industries44
How could the PizzaApp GUI be improved?
More efficient?
More functions? Let user specify total number of
pizzas and sodas on welcome screen Display shopping cart of items Allow editing of items from shopping
cart and order total screen
GUI Improvements
Copyright 2014 by Janson Industries45
Sunflower Floral Designs customers can order Floral arrangement ($25) Cut flowers ($15) Corsage ($10)
Choose flower type: Roses (extra $5) Daisies Chrysanthemums Irises
GUI Exercise
Copyright 2014 by Janson Industries46
Customer clicks Order Now button and the price of the order is displayed
Create: Story Board Interactivity program Object dictionary
Given the solutions the pseudocode would be….
GUI Exercise
Answer1
Answer2
Answer3
Copyright 2014 by Janson Industries47
Class Screen1
Public Module Screen1()setSizePosition(600, 330, 100, 100)
Declare Label labelSunflower = New Label()labelSunflower.setPositionSize(150, 40, 300, 23)
labelSunflower.setText("Sunflower Floral Designs") labelSunflower.setFont(Verdana", 24)
Declare Label labelDesign = New Label() labelDesign. setPositionSize(31, 85, 85, 23) labelDesign.setText("Design") labelDesign.setFont(new Font ("Verdana", 24)
Declare Label labelFlower = New Label() labelFlower.setPositionSize(332, 85, 85, 23) labelFlower.setText("Flower") labelFlower.setFont("Verdana", 24)
PseudocodeModule main() Declare Screen1 screen = New Screen1() screen.display()End Module Pgm that
gets the app rolling
Define the component properties
Copyright 2014 by Janson Industries48
PseudocodeDeclare RadioButton radioButtonFloral = New RadioButton()radioButtonFloral.setPositionSize(31, 136, 232, 23)radioButtonFloral.setText ("Floral Arrangement")radioButtonFloral.setFont("Verdana", 24)
Declare RadioButton radioButtonCut = New RadioButton()radioButtonCut.setPositionSize(31, 172, 232, 23)radioButtonCut.setText (“Cut Flowers")radioButtonCut.setFont("Verdana", 24)
Declare RadioButton radioButtonCorsage = New RadioButton()radioButtonCorsage.setPositionSize(31, 208, 232, 23)radioButtonCorsage.setText ("Corsage")radioButtonCorsage.setFont("Verdana", 24)
Declare RadioButton radioButtonRoses = New RadioButton()radioButtonRoses.setPositionSize(332, 136, 202, 23)radioButtonRoses.setText ("Roses")radioButtonRoses.setFont("Verdana", 24)
Declare RadioButton radioButtonDaisies = New RadioButton()radioButtonDaisies.setPositionSize(332, 172, 202, 23)radioButtonDaisies.setText ("Daisies")radioButtonDaisies.setFont("Verdana", 24)
Copyright 2014 by Janson Industries49
Declare RadioButton radioChrisanthemums = New RadioButton()radioButtonChrisanthemums.setPositionSize(332, 208, 202, 23)radioButtonChrisanthemums.setText ("Chrisanthemums")radioButtonChrisanthemums.setFont("Verdana", 24)
Declare RadioButton radioButtonIrises = New RadioButton()radioButtonIrises.setPositionSize (332, 244, 202, 23)radioButtonIrises.setText ("Irises")radioButtonIrises.setFont("Verdana", 24)
Declare Button orderButton = New Button()orderButton.setPositionSize(504, 293, 80, 23)orderButton.setText("Order Now")orderButton.registerListener(orderRoutine())
add(labelSunflower)add(labelDesign)add(radioButtonFloral)add(radioButtonCut)add(radioButtonCorsage)add(labelFlower)add(radioButtonRoses)add(radioButtonDaises)add(radioButtonChrisanthemums)add(radioButtonIrises)add(orderButton)
End Module
PseudoCode
Tie the listener to a component and
specify the module to execute
Copyright 2014 by Janson Industries50
PseudoCodePublic Module orderRoutine()
Declare Integer FLORAL_AMT = 25, CUT_AMT = 15, CORSAGE_AMT = 10, ROSE_AMT = 5, totalPrice
If radioButtonFloral.getChecked() ThentotalPrice = FLORAL_AMT
ElseIf radioButtonCut.getChecked() Then
totalPrice = CUT_AMTElse
If radioButtonCorsage.getChecked() ThentotalPrice = CORSAGE_AMTEnd If
End IfEnd If
If radioButtonRoses.getChecked() ThentotalPrice = totalPrice + ROSE_AMT
End If
Declare Screen2 screen = new Screen2()screen.display(totalPrice)remove()
End Module
End Class
Copyright 2014 by Janson Industries51
Class Screen2
Public Module Screen2(Integer price)setSizePosition(600, 275, 100, 100)
Declare Label labelSunflower = New Label()labelSunflower.setPositionSize(150, 40, 300, 23)
labelSunflower.setText("Sunflower Floral Designs") labelSunflower.setFont(Verdana", 24)
Declare Label labelPrice = New Label() labelPrice.setPositionSize(125, 225, 85, 23) labelPrice.setText("Price of your order:") labelPrice.setFont("Verdana", 24)
Declare Label labelPriceAmt = New Label() labelPriceAmt.setPositionSize(375, 85, 85, 23) labelPriceAmt.setText(“$“, price) labelPriceAmt.setFont("Verdana", 24)
Declare Button ExitButton = New Button()exitButton.setPositionSize(504, 239, 80, 23)exitButton.setText(“Exit")exitButton.registerListener(exitRoutine())
PseudoCode
Copyright 2014 by Janson Industries52
add(RadioButtonDaises)add(RadioButtonChrisanthemums)add(RadioButtonIrises)add(exitButton)
End Module
Public Module exitRoutine()remove()
End Module
End Class
Pseudocode
Copyright 2014 by Janson Industries53
Animation Used sparingly in applications
Very popular on the web, especially in ads
Really just a series of still pictures displayed rapidly Gives the illusion of motion
Like GUI components, animation must specify location as x and y coordinates of still pictures
Copyright 2014 by Janson Industries54
Animation Then slightly modify the image
and redisplay
Most languages come with predefined graphics classes that make this easier
But can be done without special graphics classes Do need several new classes in
java i.e. Runnable interface
Copyright 2014 by Janson Industries55
Java Animation
public void update() { if (fontSize <50) { fontSize = fontSize + 1; urgentMsgLbl.setFont(new Font("Arial", Font.PLAIN, fontSize)); } else { sleepInterval = 1000; if (showLabel) { urgentMsgLbl.setForeground(Color.RED); showLabel = false;} else { urgentMsgLbl.setForeground(Color.WHITE); showLabel = true;} }}
Assuming this is in a loop, what do you think this does?
Copyright 2014 by Janson Industries56
Java Animation Download UrgentMsg.java,
compile and run to see what update does
Animation can be a resource hog Slows down the application
Multithreading can be used to help with this
Copyright 2014 by Janson Industries57
Thread Set of instructions that are
executed In old days, all computers were
single-threaded First job submitted, first job executed All other jobs wait for first job to finish
Problems?• What if first job is payroll and runs for 3
hours• All other work on hold
Copyright 2014 by Janson Industries58
Thread Computers nowadays will switch
between threads/tasks If first program waiting for file data,
CPU works on different program/thread
Computers are so fast, users/apps don't even notice the lack of attention
Many languages allow a programmer to define threads within a single program
Copyright 2014 by Janson Industries59
Thread So animation can run and user can still click buttons
Need a Thread variable and object
Programmer can make the thread wait for a certain number of milliseconds (thousandths of a second)
Thread thread;thread = new Thread(this);thread.start();
thread.sleep(sleepInterval);
Copyright 2014 by Janson Industries60
Thread Invoking the thread start() method causes the JVM to invoke the run() method
run() issues the repaint command Which runs the paint() method
paint() runs update()
update() is the method that changes the size and color
Copyright 2014 by Janson Industries61
Thread and Animation To see another example of
animation and threads
Download and run BouncingBall
Copyright 2014 by Janson Industries62
Points to Remember GUI's should make the user more
efficient
GUI's help to cut down on errors by only allowing valid input
Listeners are tied to GUI components and react to events
Story boards and interactivity diagrams are used to design a GUI
Copyright 2014 by Janson Industries63
Points to Remember
Animation can be used to enhance a GUI
Animation is often resource intensive so it should be run in a separate thread