Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing...

27
11/3/16 1 Objec&ves Programming Paradigms Introduc&on to GUIs in Java Ø Event handling Nov 4, 2016 Sprenkle - CSCI209 1 One More Plugin: Project Usus hLps://github.com/usus/usus-plugins/wiki Says has metrics capabili&es, but they weren’t working for me. Makes nice visual representa&ons of a project’s classes: Nov 4, 2016 Sprenkle - CSCI209 2

Transcript of Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing...

Page 1: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

1

Objec&ves• ProgrammingParadigms•  Introduc&ontoGUIsinJava

Ø Eventhandling

Nov4,2016 Sprenkle-CSCI209 1

OneMorePlugin:ProjectUsus• hLps://github.com/usus/usus-plugins/wiki• Sayshasmetricscapabili&es,buttheyweren’tworkingforme.

• Makesnicevisualrepresenta&onsofaproject’sclasses:

Nov4,2016 Sprenkle-CSCI209 2

Page 2: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

2

PROGRAMMINGPARADIGMS

Nov4,2016 Sprenkle-CSCI209 3

ProgrammingParadigms• OurfocushasbeenObject-orientedandProceduralparadigms

• OtherparadigmsØ Event-driven

• GUIs,Webapplica&onsØ Distributed

• Webapplica&ons,Grid,CloudØ ConcurrentØ ParallelØ Aspect-oriented

Nov4,2016 Sprenkle-CSCI209 4

Blurred lines �between paradigms,

Not completely independent

Page 3: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

3

GUISINJAVA

Nov4,2016 Sprenkle-CSCI209 5

JavaGUILibraries:AWT&Swing• AWT:AbstractWindowingToolkit

Ø OriginalGUItoolkitØ Reliesonopera&ngsystemtorenderGUIs

• Benefit:Matchlookandfeelofpla^ormØ Classesinjava.awt.*

• Swing:addedtoJava2Ø Classesinjavax.swing.*Ø ExtendsAWTØ ProvidesJavalookandfeelforapplica&ons

• Butcanpluginotherlook&feelsNov4,2016 Sprenkle-CSCI209 6

Page 4: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

4

Swing&AWT• SwingdoesnotcompletelyreplaceAWT• UsingtheSwinggraphicsprogrammingmodel

Ø ImprovesperformanceØ AllowsmoreefficientdevelopmentofGUIs

• WewilluseSwingmostlyØ LeverageAWT

Nov4,2016 Sprenkle-CSCI209 7

Swing:MadeupofComponents• Top-levelcomponents

Ø ~Hold GUI elements Ø Examples: JFrame, JWindow, JDialog, JApplet

• GUIElementsØ ~ThingsuserinteractswithØ Examples: JButton, JLabel, JMenuBar

Nov4,2016 Sprenkle-CSCI209 8

Page 5: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

5

JFRAMESANDPARENTCLASSES

Nov4,2016 Sprenkle-CSCI209 9

Frames• Frame:Mostbasicunitofgraphicsprogramming• Exampleofacontainer

Ø AcontainercontainsotherUIcomponents

•  Atop-levelwindowØ Notcontainedwithinanotherwindow

• Swing’sJFrame classimplementsaframe

Nov4,2016 Sprenkle-CSCI209 10

Page 6: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

6

ExampleFrame

Nov4,2016 Sprenkle-CSCI209 11

public class Game extends JFrame implements KeyListener {

public static void main(String[] args) {Game session = new Game();session.init();

}

public void init() {// Top-left corner is (0,0)// width/height: XBOUND, YBOUNDsetBounds(0, 0, XBOUND, YBOUND);// Shows the windowsetVisible(true);…

}}

FrameInheritance• Classhierarchy

• JFrameisderivedfromjava.awt.FrameØ Frame classisderivedfromContainer class• Container:anythingthatcancontainUIcomponents

Ø Lotsofmethodsavailablefromthehierarchy

Nov4,2016 Sprenkle-CSCI209 12

Page 7: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

7

Components&Containers• Component

Ø AbstractclassØ Everythingyouseeisacomponent

• Allnonmenu-relatedAWTcomponentsØ Manymethods

• Somedeprecated:becareful

• ContainerØ Concreteimplementa&onofComponentØ Baseclassofmanyclasses

Nov4,2016 Sprenkle-CSCI209 13

Container Methods• add(Component c)• setSize

Ø Setssizeofframeinpixels

• setLocationØ Setsloca&onofframe

• Coordinatesoftop-lefcorner• setBounds

Ø Setsbothsizeandloca&onofframe• Providesinforma&onneededforsetSize andsetLocation

Nov4,2016 Sprenkle-CSCI209 14

Page 8: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

8

Window Methods• Top-levelwindow• Noborders• NoMenuBar• dispose()

Ø Closeswindowandreclaimsresourcesassociatedwithit

• toBack()Ø Sendswindowtoback,maylosefocus/ac&va&on

• toFront()Ø Bringtofront,makethisthefocusedwindow

Nov4,2016 Sprenkle-CSCI209 15

Frame’sMethods

• Top-levelwindowwith3tleandborders• setTitle(String title)

Ø Sets&tleofframe(displayedin&tlebar)

• setResizable(boolean resizable)Ø Cantheuserresizetheframe?

Nov4,2016 Sprenkle-CSCI209 16

Page 9: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

9

AnatomyofanApplica&onGUI

Nov4,2016 Sprenkle-CSCI209 17

JPanel

JButton

JFrame

JLabel

GUI Internal structure

JFrame

JPanel

JButton JLabel

containers

Implemen&ngaGUIComponent1.  Createit2.  Configureit3.  Addchildren(ifcontainer)4.  Addtoparent(ifnotJFrame)5.  Listentoit

Nov4,2016 Sprenkle-CSCI209 18

order�important

Page 10: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

10

Implemen&ngaGUIComponent1.  Createit

JButton b = new JButton();2.  Configureit

b.setText("press me");b.setForeground(Color.blue);

3.  Addittoparentpanel.add(b);

4.  ListentoitØ  Events:Listeners

Nov4,2016 19Sprenkle-CSCI209

Nov4,2016 Sprenkle-CSCI209 20

JFrame

• ContainsContentPaneØ AContainer objectthatholdscomponentsyouadd,placingthemintheframe

Ø ThepartoftheframethatholdsUIcomponents

JFrame

ContentPane

Page 11: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

11

BuildingaGUI1.  Create(topdown):

Ø FrameØ ContainerØ ComponentsØ Listeners

2.  Add(boLomup):Ø Listenersintocomponents

Ø ComponentsintopanelØ Panelintoframe

Container

JButton

Listener

JFrame

JLabel

Nov4,2016 21Sprenkle-CSCI209

Content Pane Create Ad

d

ExampleCode// create the componentsJFrame f = new JFrame("title");f.setBounds(0, 0, 100, 100);Container pane = f.getContentPane();JButton b = new JButton("press me");

// add button to panelpane.add(b);

// show the framef.setVisible(true);

Nov4,2016 22Sprenkle-CSCI209

Page 12: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

12

MoreGUIComponents•  Choice

Ø Drop-downlist•  FileDialog

Ø Openingandsavingfiles•  List

Ø  ScrollableØ Allowsmul&pleselec&ons

•  ScrollPaneØ  scrollbars

•  TextFieldØ  Singlelineoftext

•  TextAreaØ Mul&plelinesoftext

Nov4,2016 Sprenkle-CSCI209 23

Menus• MenuBar

Ø ThingacrosstopofframeØ Frame: setMenuBar(MenuBar mb);

• MenuØ ThedropdownpartØ AsequenceofMenuItemsØ Menu isasubclassofMenuItems,socanhavesubmenus

Nov4,2016 Sprenkle-CSCI209 24

Page 13: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

13

Prac&ce:CombiningComponents• CreateapanelwiththreebuLonsonit

Nov4,2016 Sprenkle-CSCI209 25

ButtonPanel.java

PlacementofComponents

• HowdoesthepanelknowwheretoplaceabuLon?

• HowdoesthepanelknowwheretoplacethenextbuLon?

• Howdoesthepanelknowwheretoplaceanycomponentthatisaddedtoit?

Nov4,2016 Sprenkle-CSCI209 26

Page 14: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

14

LAYOUTMANAGERS

Nov4,2016 Sprenkle-CSCI209 27

LayoutManagers• Javauseslayoutmanagerstoplacecomponentsinsideacontainer

• LayoutManagerautoma&callyhandlesplacementofcomponentsØ Whenacomponentisaddedtoacontainer(throughadd),layoutmanagerdecideswheretoplacethecomponent

Nov4,2016 Sprenkle-CSCI209 28

Page 15: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

15

DefaultLayoutManagers• JFrame’scontentpane:BorderLayout• JPanel’s:FlowLayout

Nov4,2016 Sprenkle-CSCI209 29

TheFlowLayoutManager• Defaultlayoutmanagerforapanel

• Linescomponentsuphorizontallyun&lnomoreroomincontainerØ Thenstartsanewrowofcomponents

•  Ifuserresizescomponent,layoutmanagerautoma&callyreflowscomponents

Nov4,2016 Sprenkle-CSCI209 30

Page 16: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

16

TheFlowLayoutManager• Canchoosehowtoarrangecomponentsinarow

Ø Default:centereachrowØ Otherop&ons:leforrightalign

• ChangealignmentusingsetLayout

Ø Panelsettouseaflowlayoutmanagerwithrowcomponentsalignedtothelef

• Anotherconstructorhashgap andvgap forgapstoputaroundcomponents

Nov4,2016 Sprenkle-CSCI209 31

setLayout(new FlowLayout( FlowLayout.LEFT ));

BorderLayoutManager• DefaultlayoutmanagerofthecontentpaneforJFrame

• Letsyouchoosewhereyouwanttoplaceeachcomponent

Nov4,2016 Sprenkle-CSCI209 32

with respect to the container

Center

North

South

West East

Page 17: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

17

BorderLayoutRegions

• Edgecomponentsarelaidoutfirst• Centeroccupiesremainingspace

Nov4,2016 Sprenkle-CSCI209 33

Center

North

South

West East

BorderLayoutRules• Growsallcomponentstofillavailablespace•  Ifcontainerisresized,edgecomponentsareredrawnandcenterregionsizerecomputed

• ToaddacomponenttoacontainerusingaborderlayoutØ Ex:JFrame’scontentpane

Nov4,2016 Sprenkle-CSCI209 34

Container contentPane = getContentPane();contentPane.add(button, BorderLayout.SOUTH);

Page 18: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

18

AddingComponentsUsingaBorderLayout

•  Ifnoregionspecified,assumescenterregion

Ø Recall:borderlayoutgrowscomponenttofitspecifiedregion

Nov4,2016 Sprenkle-CSCI209 35

Container contentPane = getContentPane();contentPane.add(button, BorderLayout.SOUTH);

What happens if we add multiple components, e.g., three buttons, without specifying a region?

ABorderLayoutLimita&on

• LastbuLonaddedgrowstocompletelyfillcenterregion

• FirsttwobuLonswerediscarded/overwriLenbyeachsubsequentlyaddedcomponent

Nov4,2016 Sprenkle-CSCI209 36

Three

Page 19: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

19

ChangingLayoutManagers• Anycontainercanuseanylayoutmanager• UsesetLayout tochangelayoutmanagerbeforeaddingcomponents

Nov4,2016 Sprenkle-CSCI209 37

// sets layout to a new flow layout manager that// aligns row components to the left and uses a 20 pixel// horizontal separation and 20 pixel vertical separationsetLayout(new FlowLayout(FlowLayout.LEFT, 20, 20));

// sets layout to a new border layout manager that// uses a 45 pixel horizontal separation between// components (regions) and a 20 pixel vertical separationsetLayout(new BorderLayout(45, 20));

CombiningPanels• Panelsactas(smaller)containersforUIelements

• Canbearrangedinsidealargerpanelbyalayoutmanager

• Useaddi&onalpanelstocustomizelookØ CreateapanelØ AddsomebuLonstoitØ Addthatpaneltoaregionincontentpane

Nov4,2016 Sprenkle-CSCI209 38

Page 20: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

20

CombiningPanels

Nov4,2016 Sprenkle-CSCI209 39

JButton JButton

JTextArea

CombiningPanels

Nov4,2016 Sprenkle-CSCI209 40

North

JPanel: BorderLayout

Center

JFrame

JPanel: FlowLayout

JButtonJButton

JTextArea

Page 21: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

21

UsingAddi&onalPanels• Getfairlyaccurateandpreciseplacementofcomponents

• Usenestedpanelswith

Nov4,2016 Sprenkle-CSCI209 41

FlexibleLayout.java

Layout UseBorderLayout Contentpanesandenclosingpanels

Flow Layouts PanelscontainingbuLonsandotherUIcomponents

AnotherLayoutManager:Grid• Dividescontainerintocolumnsandrowsofequalsize,whichcollec&velyoccupytheen&recontainerregion

• RowsandcolumnsarealignedlikeatableØ Whencontainerisresized,the“cells”growand/orshrink

Ø Cellsalwaysmaintainiden&calsizes

• Example:

Nov4,2016 Sprenkle-CSCI209 42

panel.setLayout(new GridLayout(5, 4)); // 5 rows, 4 cols

Page 22: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

22

• Componentsaddedsequen3ally• 1staddaddscomponentto1strow,1stcol• 2ndaddaddscomponentto1strow,2ndcol

• Andsoforthun&l1strowisfilled• Then2ndrowbeginswiththe1stcolumn• Con&nuesun&ltheen&recontainerisfilled

AddingComponentstoaGridLayout

Nov4,2016 Sprenkle-CSCI209 43

GridLayoutRules• Componentsareresizedtotakeupen&recell• Restric&vebutcanbeusefulforsomeapplica&ons

• Example:CreatearowofbuLonsofiden&calsize1.  Makeapanelthathasagridlayoutwithonerow2.  AddabuLontoeachcell3.  Sethoriz/vertsepara&onsobuLonsarenot

touching

Nov4,2016 Sprenkle-CSCI209 44

Page 23: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

23

LayoutManagerHeuris&cs

Nov4,2016 Sprenkle-CSCI209 45

Left to right,

Top to bottom

c

n

s

e w

FlowLayout GridLayout

BorderLayout

none, programmer sets x,y,w,h

null

One at a time

CardLayout GridBagLayout

JButton

HANDLINGUSERINTERACTIONS

Nov4,2016 Sprenkle-CSCI209 46

Page 24: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

24

Event-DrivenProgramming• Userac&ons(e.g.,mouseclicks,keypresses),sensoroutputs,ormessagesfromotherapplica&onsdetermineflowofprogram

• Applica&onarchitecture:

Nov4,2016 Sprenkle-CSCI209 47

while ( true ) {event = waitForEvent();handleEvent(event);

}

EventBasics

• AneventisgeneratedfromaneventsourceandistransmiLedtoaneventlistener

• EventsourcesalloweventlistenerstoregisterwiththemØ Registeredlistenerrequestseventsourcesenditseventtolistenerwheneventoccurs

Nov4,2016 Sprenkle-CSCI209 48

Event Source

Event Listener

Event

Page 25: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

25

JavaEventHandling• Alleventsareobjectsofeventclasses

Ø Derivefromjava.util.EventObject• Eventsource

Ø Sendsouteventobjectstoallregisteredlistenerswhenthateventoccurs

• ListenerØ ImplementsalistenerinterfaceØ UsesEventObjecttodetermineitsreac&ontotheevent

Nov4,2016 Sprenkle-CSCI209 49

JavaEventHandling• Registeralistenerwithaneventsource:

• Example:

Ø Wheneveran“ac&onevent”occursonbutton,listenerisno&fied• ForbuLons,anac&oneventisabuLonclick

Nov4,2016 Sprenkle-CSCI209 50

ActionListener listener = . . .;JButton button = new Jbutton("Click Me!");button.addActionListener(listener);

eventSourceObject.addEventListener(eventListenerObject);

Page 26: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

26

ListenerObjects• AlistenerobjectmustbeaninstanceofaclassthatimplementstheappropriateinterfaceØ ForbuLons,that’sActionListener

• ListenerclassmustimplementactionPerformed(ActionEvent event)

Nov4,2016 Sprenkle-CSCI209 51

ListenerObjectsandEventHandling• WhenauserclicksabuLon,JButton objectgeneratesanActionEvent object

• JButton callslistenerobject’sactionPerformedmethod,passinggeneratedeventobject

• Asingleeventsourcecanhavemul3plelistenerslisteningforitseventsØ SourcecallsactionPerformedoneachofitslisteners

Nov4,2016 Sprenkle-CSCI209 52

WhichmakesJButton awhat?

Page 27: Objecves - Washington and Lee Universitysprenkle/cs209/pre_class/20-guis.pdf · • Using the Swing graphics programming model Ø Improves performance Ø Allows more efficient development

11/3/16

27

AnExampleofEventHandling• SupposewewanttomakeapanelthathasthreebuLonsonitØ EachbuLonhasacolorassociatedwithitØ WhenuserclicksabuLon,backgroundcolorofpanelchangestothecorrespondingcolor

• Weneed1.  Apanelwith3buLonsonit2.  3listenerobjects,oneregisteredtolistenfora

buLon’sevents

Nov4,2016 Sprenkle-CSCI209 53