Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science...

51
(IN)FORMATIVE ASSESSMENT: CHANGING CLASSROOM PRACTICE

Transcript of Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science...

Page 1: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Comp 249 Programming Methodology

Chapter 17Swing I

Prof. Aiman HannaDepartment of Computer Science & Software Engineering

Concordia University, Montreal, Canada

These slides has been extracted, modified and updated from original slides of Absolute Java 3 rd Edition by Savitch; which has originally been prepared by Rose Williams of Binghamton University. Absolute Java is published by

Pearson Education / Addison-Wesley.

Copyright © 2007 Pearson Addison-WesleyCopyright © 2013 Aiman Hanna

All rights reserved

Page 2: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Introduction to SwingIntroduction to Swing The Java The Java AWT (Abstract Window Toolkit)AWT (Abstract Window Toolkit) package package

is the original Java package for doing is the original Java package for doing GUIsGUIs

A A GUIGUI (graphical user interface)(graphical user interface) is a windowing is a windowing system that interacts with the usersystem that interacts with the user

The Swing package is an improved version of AWTThe Swing package is an improved version of AWT However, it does not completely replace AWTHowever, it does not completely replace AWT Some AWT classes are replaced by Swing classes, but Some AWT classes are replaced by Swing classes, but

other AWT classes are needed when using Swingother AWT classes are needed when using Swing

Swing GUIs are designed using a form of object-Swing GUIs are designed using a form of object-oriented programming known as oriented programming known as event-driven event-driven programmingprogramming

17-2

Page 3: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

EventsEvents Event-driven programmingEvent-driven programming is a programming is a programming

style that uses a signal-and-response style that uses a signal-and-response approach to programmingapproach to programming

An An eventevent is an object that acts as a signal to is an object that acts as a signal to another object know as a another object know as a listenerlistener

The sending of an event is called The sending of an event is called firing the firing the eventevent The object that fires the event is often a GUI The object that fires the event is often a GUI

component, such as a button that has been clickedcomponent, such as a button that has been clicked

17-3

Page 4: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

ListenersListeners

A listener object performs some A listener object performs some action in response to the eventaction in response to the event A given component may have any A given component may have any

number of listenersnumber of listeners

Each listener may respond to a different Each listener may respond to a different kind of event, or multiple listeners kind of event, or multiple listeners might may respond to the same eventsmight may respond to the same events

17-4

Page 5: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Exception ObjectsException Objects

An exception object is an eventAn exception object is an event The throwing of an exception is an The throwing of an exception is an

example of firing an eventexample of firing an event

The listener for an exception object The listener for an exception object is the is the catchcatch block that catches the block that catches the eventevent

17-5

Page 6: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Event HandlersEvent Handlers

A listener object has methods that A listener object has methods that specify what will happen when events specify what will happen when events of various kinds are received by itof various kinds are received by it These methods are called These methods are called event handlersevent handlers

The programmer using the listener The programmer using the listener object will define or redefine these object will define or redefine these event-handler methodsevent-handler methods

17-6

Page 7: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Event Firing and an Event Firing and an Event ListenerEvent Listener

17-7

Page 8: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Event-Driven Event-Driven ProgrammingProgramming

Event-driven programming is very Event-driven programming is very different from most programming seen up different from most programming seen up until nowuntil now So far, programs have consisted of a list of So far, programs have consisted of a list of

statements executed in orderstatements executed in order When that order changed, whether or not to When that order changed, whether or not to

perform certain actions (such as repeat perform certain actions (such as repeat statements in a loop, branch to another statements in a loop, branch to another statement, or invoke a method) was controlled statement, or invoke a method) was controlled by the logic of the programby the logic of the program

17-8

Page 9: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Event-Driven Event-Driven ProgrammingProgramming

In event-driven programming, In event-driven programming, objects are created that can fire objects are created that can fire events, and listener objects are events, and listener objects are created that can react to the eventscreated that can react to the events

The program itself no longer The program itself no longer determines the order in which things determines the order in which things can happencan happen Instead, the events determine the orderInstead, the events determine the order

17-9

Page 10: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Event-Driven Event-Driven ProgrammingProgramming

In an event-driven program, the next In an event-driven program, the next thing that happens depends on the next thing that happens depends on the next eventevent

In particular, In particular, methods are defined that methods are defined that will never be explicitly invoked in any will never be explicitly invoked in any programprogram Instead, methods are invoked automatically Instead, methods are invoked automatically

when an event signals that the method needs when an event signals that the method needs to be calledto be called

17-10

Page 11: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

A Simple WindowA Simple Window A simple window can consist of an object of the A simple window can consist of an object of the JFrameJFrame class class A A JFrameJFrame object includes a border and the usual three object includes a border and the usual three

buttons for minimizing, changing the size of, and closing the buttons for minimizing, changing the size of, and closing the windowwindow

The The JFrameJFrame class is found in the class is found in the javax.swingjavax.swing package packageJFrame firstWindow = new JFrame();JFrame firstWindow = new JFrame();

A A JFrameJFrame can have components added to it, such as can have components added to it, such as buttons, menus, and text labelsbuttons, menus, and text labels These components can be programmed for actionThese components can be programmed for action

firstWindow.add(endButton);firstWindow.add(endButton); It can be made visible using the It can be made visible using the setVisiblesetVisible method method

firstWindow.setVisible(true);firstWindow.setVisible(true);

See Swing1.javaSee Swing1.javaSee Swing2.javaSee Swing2.java

17-11

Page 12: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Some Methods in the Class Some Methods in the Class JFrame JFrame (Part 1 of 3)(Part 1 of 3)

17-12

Page 13: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Some Methods in the Class Some Methods in the Class JFrame JFrame (Part 2 of 3)(Part 2 of 3)

17-13

Page 14: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Some Methods in the Class Some Methods in the Class JFrame JFrame (Part 3 of 3)(Part 3 of 3)

17-14

Page 15: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Pixels and the Relationship Pixels and the Relationship between Resolution and Sizebetween Resolution and Size

A A pixelpixel is the smallest unit of space on a is the smallest unit of space on a screenscreen Both the size and position of Swing objects are Both the size and position of Swing objects are

measured in pixelsmeasured in pixels The more pixels on a screen, the greater the screen The more pixels on a screen, the greater the screen

resolutionresolution A high-resolution screen of fixed size has A high-resolution screen of fixed size has

many pixelsmany pixels Therefore, each one is very smallTherefore, each one is very small

A low-resolution screen of fixed size has fewer A low-resolution screen of fixed size has fewer pixelspixels Therefore, each one is much largerTherefore, each one is much larger

Therefore, a two-pixel figure on a low-Therefore, a two-pixel figure on a low-resolution screen will look larger than a two-resolution screen will look larger than a two-pixel figure on a high-resolution screen pixel figure on a high-resolution screen

17-15

Page 16: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Pitfall: Forgetting to Program the Pitfall: Forgetting to Program the Close-Window ButtonClose-Window Button

The following lines from the The following lines from the FirstSwingDemo FirstSwingDemo program ensure that when the user clicks program ensure that when the user clicks the the close-window buttonclose-window button, nothing happens, nothing happensfirstWindow.setDefaultCloseOperation(firstWindow.setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE);JFrame.DO_NOTHING_ON_CLOSE);

If this were not set, the default action would If this were not set, the default action would be be JFrame.HIDE_ON_CLOSEJFrame.HIDE_ON_CLOSE This would make the window invisible and This would make the window invisible and

inaccessible, but would not end the programinaccessible, but would not end the program Therefore, given this scenario, there would be no Therefore, given this scenario, there would be no

way to click the "Click to end program" buttonway to click the "Click to end program" button Note that the close-window and other two Note that the close-window and other two

accompanying buttons are part of the accompanying buttons are part of the JFrameJFrame object, and not separate buttons object, and not separate buttons

17-16

Page 17: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

ButtonsButtons

A A buttonbutton object is created from the class object is created from the class JButtonJButton and can be added to a and can be added to a JFrameJFrame The argument to the The argument to the JButtonJButton constructor is constructor is

the string that appears on the button when it the string that appears on the button when it is displayedis displayed

JButton endButton = new JButton endButton = new

JButton("Click to end program.");JButton("Click to end program.");

firstWindow.add(endButton);firstWindow.add(endButton);

17-17

Page 18: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Action Listeners and Action Listeners and Action EventsAction Events

Clicking a button fires an eventClicking a button fires an event The event object is "sent" to another object The event object is "sent" to another object

called a listenercalled a listener This means that a method in the listener object is This means that a method in the listener object is

invoked automaticallyinvoked automatically Furthermore, it is invoked with the event object as its Furthermore, it is invoked with the event object as its

argumentargument

In order to set up this relationship, a GUI In order to set up this relationship, a GUI program must do two thingsprogram must do two things

1.1. It must specify, for each button, what objects are its It must specify, for each button, what objects are its listeners, i.e., it must register the listenerslisteners, i.e., it must register the listeners

2.2. It must define the methods that will be invoked It must define the methods that will be invoked automatically when the event is sent to the listenerautomatically when the event is sent to the listener

17-18

Page 19: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Action Listeners and Action Listeners and Action EventsAction Events

EndingListener buttonEar = newEndingListener buttonEar = new

EndingListener());EndingListener());

endButton.addActionListener(buttonEar);endButton.addActionListener(buttonEar);

Above, a listener object named Above, a listener object named buttonEarbuttonEar is created and registered as a is created and registered as a listener for the button named listener for the button named endButtonendButton

17-19

Page 20: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Action Listeners and Action Listeners and Action EventsAction Events

Different kinds of component require Different kinds of component require different kinds of classes to handle the events different kinds of classes to handle the events they firethey fire

A button fires events known as A button fires events known as action eventsaction events, , which are handled by listeners known as which are handled by listeners known as action listenersaction listeners

An action listener is an object whose class An action listener is an object whose class implements the implements the ActionListenerActionListener interface interface The The ActionListenerActionListener interface has one interface has one

method heading that must be implementedmethod heading that must be implemented

public void actionPerformed(ActionEvent public void actionPerformed(ActionEvent e)e)

17-20

Page 21: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Action Listeners and Action Listeners and Action EventsAction Events

public void actionPerformed(ActionEvent e)public void actionPerformed(ActionEvent e){{ System.exit(0);System.exit(0);}}

The The EndingListenerEndingListener class defines its class defines its actionPerformedactionPerformed method as above method as above When the user clicks the When the user clicks the endButtonendButton, an action , an action

event is sent to the action listener for that buttonevent is sent to the action listener for that button The The EndingListenerEndingListener object object buttonEarbuttonEar is the is the

action listener for action listener for endButtonendButton The action listener The action listener buttonEarbuttonEar receives the action receives the action

event as the parameter event as the parameter ee to its to its actionPerformedactionPerformed method, which is automatically invokedmethod, which is automatically invoked

Note that Note that ee must be received, even if it is not used must be received, even if it is not used

17-21

Page 22: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Pitfall: Changing the Heading for Pitfall: Changing the Heading for actionPerformedactionPerformed

When the When the actionPerformedactionPerformed method is method is implemented in an action listener, its header must implemented in an action listener, its header must be the one specified in the be the one specified in the ActionListenerActionListener interfaceinterface It is already determined, and may not be changedIt is already determined, and may not be changed Not even a throws clause may be addedNot even a throws clause may be added

public void actionPerformed(ActionEvent e)public void actionPerformed(ActionEvent e)

The only thing that can be changed is the name of The only thing that can be changed is the name of the parameter, since it is just a placeholderthe parameter, since it is just a placeholder Whether it is called Whether it is called ee or something else does not matter, or something else does not matter,

as long as it is used consistently within the body of the as long as it is used consistently within the body of the methodmethod

17-22

Page 23: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Tip: Ending a Swing Tip: Ending a Swing ProgramProgram

GUI programs are often based on a kind of GUI programs are often based on a kind of infinite loopinfinite loop The windowing system normally stays on the screen The windowing system normally stays on the screen

until the user indicates that it should go awayuntil the user indicates that it should go away If the user never asks the windowing system to If the user never asks the windowing system to

go away, it will never go awaygo away, it will never go away In order to end a GUI program, In order to end a GUI program, System.exitSystem.exit

must be used when the user asks to end the must be used when the user asks to end the programprogram It must be explicitly invoked, or included in some It must be explicitly invoked, or included in some

library code that is executedlibrary code that is executed Otherwise, a Swing program will not end after it has Otherwise, a Swing program will not end after it has

executed all the code in the programexecuted all the code in the program

17-23

Page 24: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Defining Jframe - The More Defining Jframe - The More Standard WayStandard Way

It is better to extend It is better to extend JFrameJFrame This is the normal way to define a windowing This is the normal way to define a windowing

interfaceinterface

The constructor in the new class starts by The constructor in the new class starts by calling the constructor for the parent class calling the constructor for the parent class using using super();super(); This ensures that any initialization that is normally This ensures that any initialization that is normally

done for all objects of type done for all objects of type JFrameJFrame will be done will be done

Almost all initialization for the window Almost all initialization for the window FirstWindowFirstWindow is placed in the constructor for is placed in the constructor for the classthe class

See Swing3.javaSee Swing3.java

17-24

Page 25: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

LabelsLabels

A A label label is an object of the class is an object of the class JLabelJLabel Text can be added to a Text can be added to a JFrameJFrame using a label using a label The text for the label is given as an argument The text for the label is given as an argument

when the when the JLabelJLabel is created is created The label can then be added to a The label can then be added to a JFrameJFrame

JLabel greeting = new JLabel("Hello");JLabel greeting = new JLabel("Hello");

add(greeting);add(greeting);

17-25

Page 26: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

ColorColor In Java, a In Java, a colorcolor is an object of the class is an object of the class ColorColor

The class The class ColorColor is found in the is found in the java.awt java.awt packagepackage There are constants in the There are constants in the ColorColor class that represent a class that represent a

number of basic colorsnumber of basic colors A A JFrame JFrame can not be colored directly can not be colored directly

Instead, a program must color something called the Instead, a program must color something called the content panecontent pane of the of the JFrameJFrame

Since the content pane is the "inside" of a Since the content pane is the "inside" of a JFrameJFrame, , coloring the content pane has the effect of coloring the coloring the content pane has the effect of coloring the inside of the inside of the JFrameJFrame

Therefore, the background color of a Therefore, the background color of a JFrameJFrame can be set can be set using the following code:using the following code:getContentPane().setBackground(getContentPane().setBackground(ColorColor););

See Swing4.javaSee Swing4.java

17-26

Page 27: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

The Color ConstantsThe Color Constants

17-27

Page 28: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Containers and Layout Containers and Layout ManagersManagers

Multiple components can be added to Multiple components can be added to the content pane of a the content pane of a JFrameJFrame using the using the addadd method method However, the However, the addadd method does not specify method does not specify

how these components are to be arrangedhow these components are to be arranged To describe how multiple components To describe how multiple components

are to be arranged, a are to be arranged, a layout managerlayout manager is usedis used There are a number of layout manager There are a number of layout manager

classes such as classes such as BorderLayoutBorderLayout, , FlowLayoutFlowLayout, and , and GridLayoutGridLayout

If a layout manager is not specified, a If a layout manager is not specified, a default layout manager is useddefault layout manager is used

17-28

Page 29: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

BorderLayoutBorderLayout Regions Regions

17-29

See Swing5.java

Page 30: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Border Layout ManagersBorder Layout Managers

A A BorderLayoutBorderLayout manager places the manager places the components that are added to a components that are added to a JFrameJFrame object into five regionsobject into five regions These regions are:These regions are: BorderLayout.NORTH BorderLayout.NORTH, , BorderLayout.SOUTHBorderLayout.SOUTH, , BorderLayout.EASTBorderLayout.EAST, , BorderLayout.WESTBorderLayout.WEST, and , and BorderLayout.CenterBorderLayout.Center

A A BorderLayoutBorderLayout manager is added to a manager is added to a JFrameJFrame using the using the setLayoutsetLayout method method For example:For example:

setLayout(new BorderLayout()); setLayout(new BorderLayout());

17-30

Page 31: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Border Layout ManagersBorder Layout Managers The previous diagram shows the arrangement of The previous diagram shows the arrangement of

the five border layout regionsthe five border layout regions Note: None of the lines in the diagram are normally Note: None of the lines in the diagram are normally

visiblevisible

When using a When using a BorderLayoutBorderLayout manager, the manager, the location of the component being added is given location of the component being added is given as a second argument to the as a second argument to the addadd method methodadd(label1, BorderLayout.NORTH);add(label1, BorderLayout.NORTH); Components can be added in any order since their Components can be added in any order since their

location is specifiedlocation is specified

17-31

Page 32: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Flow Layout ManagersFlow Layout Managers The The FlowLayoutFlowLayout manager is the simplest manager is the simplest

layout managerlayout managersetLayout(new FlowLayout());setLayout(new FlowLayout()); It arranges components one after the other, It arranges components one after the other,

going from left to rightgoing from left to right Components are arranged in the order in Components are arranged in the order in

which they are addedwhich they are added Since a location is not specified, the Since a location is not specified, the addadd

method has only one argument when method has only one argument when using the using the FlowLayoutManagerFlowLayoutManageradd.(label1);add.(label1);

See Swing6.javaSee Swing6.java

17-32

Page 33: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Grid Layout ManagersGrid Layout Managers A A GridLayoutGridLayout manager arranges components in a manager arranges components in a

two-dimensional grid with some number of rows two-dimensional grid with some number of rows and columnsand columnssetLayout(new GridLayout(rows, columns));setLayout(new GridLayout(rows, columns)); Each entry is the same sizeEach entry is the same size The two numbers given as arguments specify the number The two numbers given as arguments specify the number

of rows and columnsof rows and columns Each component is stretched so that it completely fills its Each component is stretched so that it completely fills its

grid positiongrid position

Note: None of the lines in the diagram are normally Note: None of the lines in the diagram are normally visiblevisible

17-33

Page 34: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Grid Layout ManagersGrid Layout Managers When using the When using the GridLayoutGridLayout class, the class, the

method method addadd has only one argument has only one argumentadd(label1);add(label1); Items are placed in the grid from left to rightItems are placed in the grid from left to right The top row is filled first, then the second, and The top row is filled first, then the second, and

so forthso forth Grid positions may not be skippedGrid positions may not be skipped

See Swing7.javaSee Swing7.java

17-34

Page 35: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Some Layout ManagersSome Layout Managers

17-35

Page 36: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

PanelsPanels

A GUI is often organized in a hierarchical A GUI is often organized in a hierarchical fashion, with containers called fashion, with containers called panelspanels inside other containersinside other containers

A panel is an object of the A panel is an object of the JPanel JPanel class class that serves as a simple containerthat serves as a simple container It is used to group smaller objects into a larger It is used to group smaller objects into a larger

component (the panel)component (the panel) One of the main functions of a One of the main functions of a JPanelJPanel object is object is

to subdivide a to subdivide a JFrameJFrame or other container or other container

17-36

Page 37: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

PanelsPanels Both a Both a JFrameJFrame and each panel in a and each panel in a JFrameJFrame can can

use different layout managersuse different layout managers Additional panels can be added to each panel, and Additional panels can be added to each panel, and

each panel can have its own layout managereach panel can have its own layout manager This enables almost any kind of overall layout to be This enables almost any kind of overall layout to be

used in a GUIused in a GUIsetLayout(new BorderLayout());setLayout(new BorderLayout());JPanel somePanel = new JPanel();JPanel somePanel = new JPanel();somePanel.setLayout(new FlowLayout());somePanel.setLayout(new FlowLayout());

Note that panel and button objects, for Note that panel and button objects, for instance, can be given color using the instance, can be given color using the setBackgroundsetBackground method without invoking method without invoking getContentPanegetContentPane The The getContentPanegetContentPane method is only used when method is only used when

adding color to a adding color to a JframeJframe

See Swing8.javaSee Swing8.java 17-37

Page 38: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

The The ContainerContainer Class Class Any class that is a descendent class of the class Any class that is a descendent class of the class

Container is considered to be a container classContainer is considered to be a container class The The ContainerContainer class is found in the class is found in the java.awtjava.awt package, package,

not in the Swing librarynot in the Swing library

Any object that belongs to a class derived from Any object that belongs to a class derived from the the ContainerContainer class (or its descendents) can class (or its descendents) can have have componentscomponents added to it added to it

The classes The classes JFrameJFrame and and JPanelJPanel are descendent are descendent classes of the class classes of the class ContainerContainer Therefore they and any of their descendents can serve Therefore they and any of their descendents can serve

as a containeras a container

17-38

Page 39: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

The The JComponentJComponent Class Class

Any descendent class of the class Any descendent class of the class JComponentJComponent is called a is called a component component classclass Any Any JComponentJComponent object or object or componentcomponent

can be added to any container class can be added to any container class objectobject

Because it is derived from the class Because it is derived from the class ContainerContainer, a , a JComponentJComponent can also be can also be added to another added to another JComponentJComponent

17-39

Page 40: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Objects in a Typical GUIObjects in a Typical GUI

Almost every GUI built using Swing Almost every GUI built using Swing container classes will be made up container classes will be made up of three kinds of objects:of three kinds of objects:

1.1. The container itself, probably a panel The container itself, probably a panel or window-like objector window-like object

2.2. The components added to the The components added to the container such as labels, buttons, and container such as labels, buttons, and panelspanels

3.3. A layout manager to position the A layout manager to position the components inside the containercomponents inside the container

17-40

Page 41: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Hierarchy of Swing and AWT Hierarchy of Swing and AWT ClassesClasses

17-41

Page 42: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Tip: Code a GUI's Look and Tip: Code a GUI's Look and Actions SeparatelyActions Separately

The task of designing a Swing GUI can be The task of designing a Swing GUI can be divided into two main subtasks:divided into two main subtasks:

1.1. Designing and coding the appearance of the GUI on Designing and coding the appearance of the GUI on the screenthe screen

2.2. Designing and coding the actions performed in Designing and coding the actions performed in response to user actionsresponse to user actions

In particular, it is useful to implement the In particular, it is useful to implement the actionPerformedactionPerformed method as a method as a stubstub, until the , until the GUI looks the way it shouldGUI looks the way it shouldpublic void actionPerformed(ActionEvent e)public void actionPerformed(ActionEvent e){}{}

17-42

Page 43: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Menu Bars, Menus, and Menu Menu Bars, Menus, and Menu ItemsItems

A A menumenu is an object of the class is an object of the class JMenuJMenu A choice on a menu is called a A choice on a menu is called a menu itemmenu item, ,

and is an object of the class and is an object of the class JMenuItemJMenuItem A menu can contain any number of menu itemsA menu can contain any number of menu items A menu item is identified by the string that labels A menu item is identified by the string that labels

it, and is displayed in the order to which it was it, and is displayed in the order to which it was added to the menuadded to the menu

The The addadd method is used to add a menu item method is used to add a menu item to a menu in the same way that a component to a menu in the same way that a component is added to a container objectis added to a container object

See Swing9.javaSee Swing9.java

17-43

Page 44: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Nested MenusNested Menus

The class The class JMenuJMenu is a descendent of is a descendent of the the JMenuItemJMenuItem class class Every Every JMenuJMenu can be a menu item in can be a menu item in

another menuanother menu Therefore, menus can be nestedTherefore, menus can be nested

Menus can be added to other menus Menus can be added to other menus in the same way as menu itemsin the same way as menu items

See Swing10.javaSee Swing10.java17-44

Page 45: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

The The AbstractButtonAbstractButton and and DimensionDimension ClassesClasses

The classes The classes JButtonJButton and and JMenuItemJMenuItem are derived classes of the abstract are derived classes of the abstract class named class named AbstractButtonAbstractButton All of their basic properties and methods All of their basic properties and methods

are inherited from the class are inherited from the class AbstractButtonAbstractButton

Objects of the Objects of the DimensionDimension class are class are used with buttons, menu items, and used with buttons, menu items, and other objects to specify a sizeother objects to specify a size The The DimensionDimension class is in the package class is in the package java.awtjava.awtDimension(int width, int height)Dimension(int width, int height)

Note: Note: widthwidth and and heightheight parameters are in parameters are in pixelspixels

17-45

Page 46: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

The The setActionCommandsetActionCommand MethodMethod

When a user clicks a button or menu item, an When a user clicks a button or menu item, an event is fired that normally goes to one or more event is fired that normally goes to one or more action listenersaction listeners The action event becomes an argument to an The action event becomes an argument to an actionPerformedactionPerformed method method

This action event includes a This action event includes a StringString instance variable instance variable called the called the action commandaction command for the button or menu item for the button or menu item

The default value for this string is the string written on The default value for this string is the string written on the button or the menu itemthe button or the menu item

This string can be retrieved with the This string can be retrieved with the getActionCommandgetActionCommand methodmethode.getActionCommand()e.getActionCommand()

17-46

Page 47: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

The The setActionCommandsetActionCommand MethodMethod

The The setActionCommandsetActionCommand method can be method can be used to change the action command for a used to change the action command for a componentcomponent This is especially useful when two or more This is especially useful when two or more

buttons or menu items have the same default buttons or menu items have the same default action command stringsaction command stringsJButton nextButton = new JButton("Next");JButton nextButton = new JButton("Next");nextButton.setActionCommand("Next Button");nextButton.setActionCommand("Next Button");

JMenuItem choose = new JMenuItem("Next");JMenuItem choose = new JMenuItem("Next");choose.setActionCommand("Next Menu Item");choose.setActionCommand("Next Menu Item");

17-47

Page 48: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Some Methods in the Class Some Methods in the Class AbstractButtonAbstractButton (Part 1 of 3) (Part 1 of 3)

17-48

Page 49: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Some Methods in the Class Some Methods in the Class AbstractButtonAbstractButton (Part 2 of 3) (Part 2 of 3)

17-49

Page 50: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Some Methods in the Class Some Methods in the Class AbstractButtonAbstractButton (Part 3 of 3) (Part 3 of 3)

17-50

Page 51: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Listeners as Inner Listeners as Inner ClassesClasses

Often, instead of having one action listener Often, instead of having one action listener object deal with all the action events in a object deal with all the action events in a GUI, a separate GUI, a separate ActionListenerActionListener class is class is created for each button or menu itemcreated for each button or menu item Each button or menu item has its own unique Each button or menu item has its own unique

action listeneraction listener There is then no need for a multiway if-else There is then no need for a multiway if-else

statementstatement

When this approach is used, each class is When this approach is used, each class is usually made a private inner classusually made a private inner class

17-51

Page 52: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Text FieldsText Fields

A A text fieldtext field is an object of the class is an object of the class JTextFieldJTextField It is displayed as a field that allows the user to It is displayed as a field that allows the user to

enter a single line of textenter a single line of textprivate JTextField name;private JTextField name;

. . .. . .

name = new JTextField(NUMBER_OF_CHAR);name = new JTextField(NUMBER_OF_CHAR);

In the text field above, at least In the text field above, at least NUMBER_OF_CHARNUMBER_OF_CHAR characters can be visible characters can be visible

See Swing11.javaSee Swing11.java17-52

Page 53: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Text FieldsText Fields There is also a constructor with one additional There is also a constructor with one additional StringString parameter for displaying an initial parameter for displaying an initial StringString in the text fieldin the text fieldJTextField name = new JTextField(JTextField name = new JTextField( "Enter name here.", 30);"Enter name here.", 30);

A Swing GUI can read the text in a text field A Swing GUI can read the text in a text field using the using the getTextgetText methodmethodString inputString = name.getText();String inputString = name.getText();

The method The method setTextsetText can be used to display a can be used to display a new text string in a text fieldnew text string in a text fieldname.setText("This is some output");name.setText("This is some output");

17-53

Page 54: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Text AreasText Areas A A text areatext area is an object of the class is an object of the class JTextAreaJTextArea

It is the same as a text field, except that it allows multiple It is the same as a text field, except that it allows multiple lineslines

Two parameters to the Two parameters to the JTextAreaJTextArea constructor specify the constructor specify the minimum number of lines, and the minimum number of minimum number of lines, and the minimum number of characters per line that are guaranteed to be visiblecharacters per line that are guaranteed to be visibleJTextArea theText = new JTextArea(5,20);JTextArea theText = new JTextArea(5,20);

Another constructor has one addition Another constructor has one addition StringString parameter for parameter for the string initially displayed in the text areathe string initially displayed in the text areaJTextArea theText = new JTextArea(JTextArea theText = new JTextArea( "Enter\ntext here." 5, 20);"Enter\ntext here." 5, 20);

See Swing12.javaSee Swing12.javaSee Swing13.javaSee Swing13.java

17-54

Page 55: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Text AreasText Areas

The line-wrapping policy for a The line-wrapping policy for a JTextAreaJTextArea can be set using the method can be set using the method setLineWrapsetLineWrap The method takes one The method takes one booleanboolean type argument type argument If the argument is If the argument is truetrue, then any additional , then any additional

characters at the end of a line will appear on characters at the end of a line will appear on the following line of the text areathe following line of the text area

If the argument is If the argument is falsefalse, the extra characters , the extra characters will remain on the same line and not be visiblewill remain on the same line and not be visibletheText.setLineWrap(true);theText.setLineWrap(true);

17-55

Page 56: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Text Fields and Text Text Fields and Text AreasAreas

A A JTextFieldJTextField or or JTextAreaJTextArea can be set so can be set so that it can not be changed by the userthat it can not be changed by the user

theText.setEditable(false);theText.setEditable(false);

This will set This will set theTexttheText so that it can only be so that it can only be edited by the GUI program, not the useredited by the GUI program, not the user

To reverse this, use true instead (this is the To reverse this, use true instead (this is the default)default)theText.setEditable(true);theText.setEditable(true);

17-56

Page 57: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Tip: Labeling a Text Tip: Labeling a Text FieldField

In order to label one or more text In order to label one or more text fields:fields: Use an object of the class Use an object of the class JLabelJLabel Place the text field(s) and label(s) in a Place the text field(s) and label(s) in a JPanelJPanel

Treat the Treat the JPanelJPanel as a single component as a single component

17-57

Page 58: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Numbers of Characters Numbers of Characters Per LinePer Line

The number of characters per line for a The number of characters per line for a JTextFieldJTextField or or JTextAreaJTextArea object is the object is the number of number of emem spaces spaces

An An em spaceem space is the space needed to hold is the space needed to hold one uppercase letter one uppercase letter MM The letter The letter MM is the widest letter in the alphabet is the widest letter in the alphabet A line specified to hold 20 A line specified to hold 20 MM 's will almost 's will almost

always be able to hold more than 20 always be able to hold more than 20 characterscharacters

17-58

Page 59: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Tip: Inputting and Outputting Tip: Inputting and Outputting NumbersNumbers

When attempting to input numbers from When attempting to input numbers from any Swing GUI, input text must be any Swing GUI, input text must be converted to numbersconverted to numbers If the user enters the number If the user enters the number 4242 in a in a JTextFieldJTextField, the program receives the string , the program receives the string "42""42" and must convert it to the integer and must convert it to the integer 4242

The same thing is true when attempting The same thing is true when attempting to output a numberto output a number In order to output the number In order to output the number 4242, it must first , it must first

be converted to the string be converted to the string "42""42"

17-59

Page 60: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

The Class The Class JTextComponentJTextComponent

Both Both JTextFieldJTextField and and JTextAreaJTextArea are are derived classes of the abstract class derived classes of the abstract class JTextComponentJTextComponent

Most of their methods are inherited from Most of their methods are inherited from JTextComponentJTextComponent and have the same and have the same meaningsmeanings Except for some minor redefinitions to account Except for some minor redefinitions to account

for having just one line or multiple linesfor having just one line or multiple lines

17-60

Page 61: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Some Methods in the Class Some Methods in the Class JTextComponent JTextComponent (Part 1 of 2)(Part 1 of 2)

17-61

Page 62: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Some Methods in the Class Some Methods in the Class JTextComponent JTextComponent (Part 2 of 2)(Part 2 of 2)

17-62

Page 63: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

A Swing CalculatorA Swing Calculator A GUI for a simple calculator keeps a A GUI for a simple calculator keeps a

running total of numbersrunning total of numbers The user enters a number in the text field, and The user enters a number in the text field, and

then clicks either + or –then clicks either + or – The number in the text field is then added to The number in the text field is then added to

or subtracted from the running total, and or subtracted from the running total, and displayed in the text fielddisplayed in the text field

This value is kept in the instance variable This value is kept in the instance variable resultresult

When the GUI is first run, or when the user When the GUI is first run, or when the user clicks the clicks the ResetReset button, the value of button, the value of resultresult is is set to zeroset to zero

17-63

Page 64: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

A Swing CalculatorA Swing Calculator

If the user enters a number in an If the user enters a number in an incorrect format, then one of the incorrect format, then one of the methods throws a methods throws a NumberFormatExceptionNumberFormatException The exception is caught in the catch The exception is caught in the catch

block inside the block inside the actionPerformedactionPerformed methodmethod

Note that when this exception is Note that when this exception is thrown, the value of the instance thrown, the value of the instance variable variable resultresult is not changed is not changed

17-64

Page 65: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

A Simple Calculator (Part A Simple Calculator (Part 1 of 11)1 of 11)

17-65

Page 66: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

A Simple Calculator (Part A Simple Calculator (Part 2 of 11)2 of 11)

17-66

Page 67: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

A Simple Calculator (Part A Simple Calculator (Part 3 of 11)3 of 11)

17-67

Page 68: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

A Simple Calculator (Part A Simple Calculator (Part 4 of 11)4 of 11)

17-68

Page 69: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

A Simple Calculator (Part A Simple Calculator (Part 5 of 11)5 of 11)

17-69

Page 70: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

A Simple Calculator (Part A Simple Calculator (Part 6 of 11)6 of 11)

17-70

Page 71: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

A Simple Calculator (Part A Simple Calculator (Part 7 of 11)7 of 11)

17-71

Page 72: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

A Simple Calculator (Part A Simple Calculator (Part 8 of 11)8 of 11)

17-72

Page 73: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

A Simple Calculator (Part A Simple Calculator (Part 9 of 11)9 of 11)

17-73

Page 74: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

A Simple Calculator (Part A Simple Calculator (Part 10 of 11)10 of 11)

17-74

Page 75: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

A Simple Calculator (Part A Simple Calculator (Part 11 of 11)11 of 11)

17-75

Page 76: Comp 249 Programming Methodology Chapter 17 Swing I Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,

Uncaught ExceptionsUncaught Exceptions

In a Swing program, throwing an In a Swing program, throwing an uncaught exception does not end the GUIuncaught exception does not end the GUI However, it may leave it in an unpredictable However, it may leave it in an unpredictable

statestate It is always best to catch any exception It is always best to catch any exception

that is thrown even if all the catch block that is thrown even if all the catch block does is output an error message, or ask does is output an error message, or ask the user to reenter some inputthe user to reenter some input

17-76