Title: Class
111-1-2004
(Lecture 20)
CS8430 OO Analysis and DesignDr. Jose M. Garrido
Class Will Start Momentarily
2GUI
- GUI programming consists of creating objects by
which a user can effectively communicate with the
underlying application program and effect its
state and behavior. - The user must be able to understand the
interface, its functions, its images, and its
logical flow.
3GUI Effectiveness
- The users background, knowledge, experience, and
perspective define a usage context. - Different categories of users will have different
expectations. - The GUI should clearly convey the proper
perspective and level of detail appropriate for
the background of the target audience.
4GUI Principles
- When designing a GUI application, address the
users need first. - The application should be comprehensive,
meaningful, and appealing to the target audience. - The software design should support an interface
with the most meaningful abstractions, and be
intuitive for the user.
5GUI Tools
- C with MFC, OWL, Borland Component Classes,
Motif (Unix), etc. - Visual Basic
- Tcl/Tk
- Java with JFC
- Others.
6Tools (Cont.)
- The tools provide implementations of visual
components that represent familiar objects with
which the user interacts - The software engineer creates visual abstractions
of the interface using elements such as dialogs
buttons, text fields, etc., as building blocks
7Architecture for GUI Applications
- The software engineer must work with two
orthogonal sets of abstractions - The application logic
- The application interface to users
- The challenge to the software engineer is to
bridge these abstractions so they can work
together.
8GUI Client/Server Model
9General Structure of a GUI
10Frames
- The largest type of container is a frame. This
container can be created simply as an object of
class JFrame of the Swing library. - An empty frame window can be built by creating an
object of class JFrame with a specified title and
setting the size for it. The next figure shows an
empty frame (window). The relevant properties of
this frame are its title, color, and size.
11Simple Components
- The simplest types of components are labels,
which can display text titles and images. - Text labels just display their text titles when
they appear on a container of a window. - A text label is defined as an object of class
JLabel The following KJP statements declare two
text labels - object blabel1 of class JLabel // text label
- object blabel2 of class JLabel
12Creating Objects of Class JLabel
- When the objects of class JLabel are created,
their text titles are defined. The following KJP
statements create the two text objects and define
their associated text titles. - create blabel1 of class JLabel using
- "Kennesaw Java Preprocessor"
- create blabel2 of class JLabel using
- "The Language for OOP"
13Image Labels
- Image labels display a picture by indicating the
corresponding icon. - In classes using Swing, a picture is set up into
an icon in a label so that the classes can
position the label in a container and display it.
- The pictures are normally in a standard format
such as JPEG or GIF. - A picture is defined as an icon, which is an
object of class ImageIcon. The icon is then
defined as part of the label.
14Declaring and Creating Objects with Icons
- The following statements declare an object
variable of class ImageIcon and an object of
class JLabel. - object kjpimage of class ImageIcon // image
- object kjplabel of class JLabel // for
image - create kjpimage of class ImageIcon using
kjplogo2.gif - Finally, with the icon object created, it can be
defined as part of a label. The following
statement creates the label object with the icon
defined in object variable kjpimage. - create kjplabel of class JLabel using kjpimage
15Adding Components to a Window
- Components cannot be added directly to a window,
which is an object of class JFrame. - A special container called the content pane
defines the working area for the window. - All the graphical elements, (components) and
smaller containers are added to the content pane.
The content pane is an object of class Container. - There are several ways to arrange graphical
elements in the content pane. The type of
arrangement is defined by the layout manager
selected.
16Layout Managers
- Border, which arranges the components in the
north, east, west, center, and south positions in
the container - Flow, which arranges the components in the
container from left to right - Grid, which arranges the components in a matrix
with row and column positions - Box, which arranges the components in a single
row or single column - Card, which arranges the components in a similar
manner as the stack of cards - Gridbag, which arranges components in a similar
manner as the grid but with variable size cells
17Border Layout
18Using Layout Managers
- To control the arrangement of GUI components,
Java uses layout managers. - For example the GridLayout arranges the
components in a two-dimensional grid. - pane.setLayout (new GridLayout(4, 2))
- This set the grid layout in four rows and two
columns
19import all javax.swing // Library for
graphics import all java.awt description
Create and display a frame window with an image
and two text labels. / class Kjplogo is
public description This is the main
function of the application.
/ function main is constants
integer WIDTH 400 integer HEIGHT 300
20objects object frame_obj of class JFrame //
window object cpane of class Container //
content pane object blabel1 of class JLabel
// text label object blabel2 of class JLabel
object kjpimage of class ImageIcon //
image object kjplabel of class JLabel
// for image object lmanager of class
BorderLayout // layout manager
21 begin create frame_obj of class JFrame
using "KJP logo" create blabel1 of class
JLabel using "Kennesaw Java Preprocessor"
create blabel2 of class JLabel using "The
Language for OOP" create kjpimage of class
ImageIcon using "kjplogo2.gif" create
kjplabel of class JLabel using kjpimage
create lmanager of class BorderLayout set
cpane call getContentPane of frame_obj
call setLayout of cpane using lmanager //
layout manager
22 // add the text image label and text label
components // to the content pane of the
window call add of cpane using kjplabel,
BorderLayout.CENTER call add of cpane using
blabel1, BorderLayout.NORTH call add of
cpane using blabel2, BorderLayout.SOUTH
call setSize of frame_obj using WIDTH, HEIGHT
call setVisible of frame_obj using true
endfun main
23Listener Class Echo
class Echo implements ActionListener public
void actionPerformed (ActionEvent e)
JTextField source (JTextField) e.getSource())
String text source.getText()
System.out.println(text) // end class
Echo
Suppose we input an integer value, include the
statement int value Integer.parseInt
(text.trim())
24A Frame with Three Components
25Attributes of Frames
- Two attributes of frames that are used in the
previous examples are title and size. - The title was set with the constructor of class
JFrame when creating a frame object. This
attribute can be set at any time by invoking
method setTitle with a string argument. - For example, the following statement sets a title
to the frame object declared with reference
frame_obj in the previous example - call setTitle of frame_obj using
- New Frame Title
26Size
- The size of the frame object is normally set
before displaying it on the screen. - As mentioned before, the units for size are in
pixels. - The previous example used two named constants
WIDTH and HEIGHT. This is the recommended manner
to set the values for the size. - The size is set by invoking method setSize with
the values in pixels for width and height of the
frame. For example, to set the size of the frame
referenced by frame_obj, the statement is - call setSize of frame_obj using WIDTH, HEIGHT
27Color
- The third attribute of a frame is the color.
- This attribute is normally set to a container in
the frame such as, the content pane of the frame
or the panels defined and contained in the
content pane. In other words, the color of any of
these containers can directly be set. - The most common method to invoke for a container
is setBackground. The argument is normally a
predefined constant in class Color, which is
available in the AWT package. - These constants represent various colors to apply
as background color to the container.
28Setting the Color
- To set the background color of a container in a
frame object, method setBackground is invoked
with the selected color. This method is defined
in class JFrame. - The following statement sets the background
color to pink in frame frame_obj of the previous
example. - call setBackground of cpane using Color.pink
29Events and Listeners
- An event is a special non-visible object that
represents and an occurrence or signal. It
indicates some occurrence in the interaction
between the user and the executing program. - Usually, the most important events are the ones
originated by some user action. Examples are - the click of the mouse,
- starting of mouse movement,
- a keystroke on the keyboard,
- and so on.
30Listener
- A listener is an object that waits for a specific
event to occur and that responds to the event in
some manner. - Each listener has a relationship with an event or
with a group of similar events. - Listener objects must be carefully designed to
respond to its type of events.
31Components and Events
- Buttons and text fields are examples of graphical
components that generate events as a result of
user actions. - The listener object will respond when the user
clicks on the button.
32An Action Event
33Action Event
- When a user clicks on a button, the type of event
generated by the button is called action event. - The figure illustrates the relationship among the
button object, the action event, and the listener
object. - Creating the action event and invoking the
appropriate function by the listener object to
handle the event is done automatically. -
34Registering the Listener Object
- The action event generated by the button is sent
to a corresponding listener object that responds
to the event. - The listener object must be set to respond to an
event generated by the button object, this is
known as registering the listener object with the
button object.
35Interaction Button - Listener
- The next figure shows the UML collaboration
diagram for an object of class JButton and a
listener object of class Bquithandler. - The button object generates an action event that
it sends to the listener object by invoking
method actionPerformed. - The interaction between these objects occurs
automatically.
36Button and Listener Object
37Declare and Create a Button Object
- The following statement declares an object
variable of class JButton. - object mybutton of class JButton
- The button object is created with a title. The
following statement creates the button object
with title Push to Quit. - create mybutton of class JButton using "Push
to Quit"
38Listener Object
- The listener object will respond when the user
clicks the mouse on the button. - The actual behavior of the listener object is
defined in a class that has to be defined by the
programmer. - The following statements declare and create the
listener object bhandler of class Bquithandler. - object bhandler of class Bquithandler
- ...
- create bhandler of class Bquithandler
39Registering the Listener Object
- The listener object has to be registered as the
listener to the button object. - The following statement invokes function
addActionListener of the button to register its
listener object, bhandler. - call addActionListener of mybutton using bhandler
- Function addActionListener is defined in class
JButton.
40Adding the Button Object to Frame
- The button can now be added to the content pane
of the window. - The following statement adds the button defined
before to the content pane and with the south
position. - call add of cpane using mybutton,
BorderLayout.SOUTH - The content pane uses the border layout manager
in this example.
41Class for Listener Object
- The class definition that implements the behavior
of listener objects depends on the type of events
that these objects can handle (or respond to). - For action events, the class definition must
implement interface ActionListener, which is
included in package AWT. - The only method specified in the interface is
actionPerformed and it has to be completely
implemented in the class defined for action
listener objects.
42Class for Listener
- import all javax.swing
- import all java.awt.event
- description
- This class defines the behavior of listener
- objects for the button. When the user clicks
- the mouse on the button, the program
terminates. - /
- class Bquithandler implements ActionListener is
- public
- description
- The only function in the class. /
- function actionPerformed parameters object
myev of class ActionEvent is - begin
- display Goodbye!
- call System.exit using 0
- endfun actionPerformed
- endclass Bquithandler
43Data Input
- Instead of an object of class JButton, we can
create an object of class JTextField. - The following Java class example, lets the user
type data into the text field
44Java Class InputData
- import java.awt.
- import javax.swing.
- Class InputData
- public static void main (String args)
- JFrame myframe new JFrame(Input data)
- Container pane myframe.getContentPane()
- JTextField indata new JTextField(
- Edit data then press Enter)
- In_listener listener new In_listener()
- indata.addActionListener(listener)
- pane.add(indata)
- myframe.pack()
- myframe.show()
-
45Java Class In_listener
- class In_listener implements ActionListener
- public void actionPerformed (ActionEvent e)
- JTextFiled myinput (JTextField)
e.getSource() - String mydata myinput.getText()
- System.out.println(mydata)
- // end method
- // end class
- If an integer value was expected
- int mynumber Integer.parseInt(mydata.trim())
-
-
46Graphics
- A graphic object (of class Graphics) draws each
pixel in a window - Pixels are dots on the screen used to create
graphic images - Depending on the resolution, the screen has a
large numbers of pixels (gt 786,432) - We use a coordinate system to draw on the screen
- If g is of class Graphics, then to display a
string - g.drawString(Hello KSU!, 30, 40)
47Coordinate Systems
- Each pixel can be identified using a
two-dimensional coordinate system - When referring to a pixel in a Java program, we
use a coordinate system with the origin in the
upper left corner
112
40
(112, 40)
48Representing Color
- A black and white picture can be stored using one
bit per pixel (0 white and 1 black) - A color picture requires more information, and
there are several techniques for representing a
particular color - For example, every color can be represented as a
mixture of the three primary colors Red, Green,
and Blue - In Java, each color is represented by three
numbers between 0 and 255 that are collectively
called an RGB value
49A Simple Applet
Import javax.swing. import java.awt. import
java.util.Calendar public class DigitalClock
extends JApplet implements Runnable
ltFieldsgt ltMethodsgt
50The Applet Methods
- Public void init()... invoked when the applet
is loaded initially - public void start()... invoked when entering
the web page that contains the applet - public void stop()... invoked when leaving the
web page that contains the applet - public void run()... run the applet, i.e., the
main driver of the applet - public void paint(Graphics g)... paint the
picture
51The Life-Cycle of An Applet
52Fields and Initialization
protected Thread clockThread null protected
Font font new Font("Monospaced",
Font.BOLD, 48) protected Color color
Color.green By default all class fields are
automatically initialized to their default
values, usually 0 or null.
53The start() and stop() Methods
- public void start()
- if (clockThread null)
- clockThread new Thread(this)
- clockThread.start()
-
-
- public void stop()
- clockThread null
-
- Start and stop the thread.
- Stopped threads will not consume CPU time.
54The run() Method
- public void run()
- while (Thread.currentThread()
- clockThread)
- repaint()
- try
- Thread.currentThread().sleep(1000)
- catch (InterruptedException e)
-
-
- In each iteration, repaint() is invoked, then
sleep 1 second. - Sleep() must be invoked inside the try block.
55The paint() Method
public void paint(Graphics g) Calendar
calendar Calendar.getInstance() int hour
calendar.get(Calendar.HOUR_OF_DAY) int minute
calendar.get(Calendar.MINUTE) int second
calendar.get(Calendar.SECOND) g.setFont(font)
g.setColor(color) g.drawString(hour
"" minute / 10 minute 10 ""
second / 10 second 10, 10, 60)
56Who Calls run() And paint()?
- clockThread.start() calls DigitalClock.run()
- DigitalClock.repaint() calls
DigitalClock.paint() - The paint() method is usually not called
directly.
57Drawing Strings
g.drawString("A Sample String", x, y)
58HTML Source
lt!--DigitalClockDemo.html--gt lthtmlgt ltheadgt
lttitlegtDigital Clock Appletlt/titlegt
lt/headgt ltbody bgcolorwhitegt lth1gtThe Digital
Clock Appletlt/h1gtltpgt ltapplet codeDigitalClock.cla
ss width250 height80gt lt/appletgt ltpgtlthrgt
lta hrefDigitalClock.javagtThe sourcelt/agt lt/bodygt
lt/htmlgt
59The java.awt.Color Class
- Instances of the Color class represent colors.
- new Color(r, g, b)
- where r, g, b are the values of the red, green,
and blue components, respectively. They are
in the in the range of 0 to 255. - Some common colors are predefined as constants.
- black gray orange yellow
- blue green pink
- cyan lightGray red
- darkGray magenta white
60The java.awt.Font Class
- Fonts are specified with three attributes
- font name Serif Sans-serif Monospaced Dialog
DialogInput TimesRoman Helvetica Courier
Dialog - font style PLAIN BOLD ITALIC
- Styles can be combined Font.BOLDFont.ITALIC
- font size a positive integer
- A font can be created as follows
- new Font(name, style, size)
61- End
- Of
- Todays
- Lecture.
- 11-1-04