Title: Java Foundation Classes (JFC/Swing)
1Java Foundation Classes(JFC/Swing)
- Carl Alphonce
- revised Spring 2007
- (with contributions from Alan Hunt)
2Java Swing Toolkit Graphics
- The key to effectively using graphics in Java is
understanding - the basic components of the graphics library
- the patterns that are used to combine components
- Must also understand how multiple threads of
execution are used to run graphical applications.
3Overview
- Patterns
- Containers and Components
- Threads
4Some patterns used
- OBSERVER
- STRATEGY
- COMPOSITE
- DECORATOR
5Some patterns used - examples
- OBSERVER event handling
- STRATEGY layout management
- COMPOSITE containers are also components
- DECORATOR scrollbars, streams
6java.awt.Component
- All displayable objects in the graphics hierarchy
extend this base class. You will never create an
instance of this class directly (since it is
abstract), but instead use the pre-defined GUI
elements that Java provides.
7Containers
- A container is the basic enclosing element of a
graphical application. You cannot have a
graphical application without a container to hold
the rest of your graphical components. - The top level container for an application is
usually a javax.swing.JFrame
8javax.swing.JFrame
- A JFrame is a top-level container (meaning it
does not need to be contained within any other
container). - A JFrame is a window with a title and a border.
- JFrames also support menu bars.
9An example using a JFrame(this is not
"thread-safe")
- public class JFrameExample
- public JFrameExample()
- JFrame f new JFrame()
- f.pack()
- f.setVisible(true)
-
- public static void main(String args)
- new JFrameExample()
-
10Composite Pattern
11Composite Pattern
- The whole graphical framework is a hierarchy of
components. This is an almost textbook example
of the composite pattern - a frame contains many children, which all comply
to the same interface (Component) - a call to, for example, repaint() on the frame
will also call repaint() on all its children
12Input Elements
- The whole point of a Graphical User Interface
(GUI) is to accept user input and do something
with it. To this end, there are a large number
of input components in Swing. - Lets first examine the JButton.
13Button Example
- JButton button new JButton("Push Me")
- f.getContentPane().add(button)
- button.addActionListener(new ActionListener()
- public void actionPerformed(ActionEvent e)
- label.setText("Clicked")
-
- )
14OBSERVER PATTERN general form
- Idea decouple event from event handling
Abstract Observable
Abstract Observable
Abstract Observable
Abstract Observer
attach(Observer) detach(Observer) notifyObservers(
)
update()
0..
Concrete Observable
Concrete Observer
15JFC use of OBSERVER
- The observer pattern is used for event
notification. - Observables (classes like JButton) generate
events. - An observable can have many observers.
- The pattern is applied several times in design of
class library. - Pattern is tailored to application method names
are suitable for each application.
16OBSERVER PATTERN - applied
- In JFC/Swing, Observer is realized for different
event types, with methods named accordingly.
attach ? addActionListener detach ?
removeActionListener notifyObservers ?
fireActionPerformed
update ? actionPerformed
Abstract Observable
Abstract Observable
JButton
ActionListener
addActionListener(ActionListener) removeActionList
ener(ActionListener) fireActionPerformed(ActionEve
nt)
actionPerformed(ActionEvent)
0..
17Multiple Observers
- We can add more than one observer to our button.
All observers are notified when a button event
occurs. Let us add an observer that will also
change the color of the label. - button.addActionListener(new ActionListener()
- public void actionPerformed(ActionEvent e)
- label.setForeground(Color.RED)
-
- )
18DECORATOR
- A decorator adds functionality while maintaining
an interface. - One example
- InputStreamReader wraps InputStream
- BufferedReader wraps InputStreamReader
- Another example
- JScrollPane wraps Jlist
19STRATEGY
- A layout manager has responsibility for laying
out components within a container. - Unlike in NGP, JFC containers do not have fixed
layout managers. - Layout managers are treated as strategies.
- Strategies can be swapped.
20Layout Managers
- Swing has several different layout managers.
Some of the most common are FlowLayout,
BorderLayout, GridLayout, and GridBag Layout.
Each has advantages and disadvantages.
21BorderLayout
- The BorderLayout manager creates an object that
resembles a picture with a four sided frame, or
border.
22FlowLayout
- FlowLayout is arguably the simplest layout
manager. It just stacks up components in a row,
right to left. If it runs out of space, it wraps
to a new line. This is the default layout
manager for JPanel. You can see the behavior in
how the button, text area, and combo box are laid
out.
23GridLayout
- GridLayout arranges its components in an equally
spaced grid of cells. Will take as much space as
is available to it.
24GridBag Layout
- GridBag is both the most flexible of the layout
managers, and the most difficult to use. It
allows you customize the size and growth of all
the components separately, but setting it up is a
pain.
25Topic overview
- Processes Threads
- Containers (graphical)
- Components
- Layout managers
- Event handling
- Inner classes
26Processes and Threads
- What is a process?
- What is a thread?
- two special Java threads
- main thread
- event-dispatching thread
- the Runnable interface
27Processes
- A program that is running on a computer is called
a process. - most consumer OSes allow many processes to run
simultaneously - a single program can give rise to many processes
- bob runs Netscape one process
- sally runs Netscape another process
- multitasking at the operating system level
28Threads
- Each process has its own (main) thread of
execution - A process can spawn several threads
- multitasking is happening at the level of the
process, not at the level of the operating system - a process with multiple threads is called a
multithreaded application
29Two Java threads
- Every Java program has a main thread of
execution. - starts with public static void main(String
args) - Graphical applications have an event-dispatching
thread too. - It is important for the proper functioning of
graphical, event-driven programs that graphics be
run on the event-dispatching thread.
30Runnable interface
- The Runnable interface specifies one method
- public interface Runnable
- /
- When an object implementing interface
ltcodegtRunnablelt/codegt is used - to create a thread, starting the thread
causes the object's - ltcodegtrunlt/codegt method to be called in
that separately executing - thread.
- ltpgt
- The general contract of the method
ltcodegtrunlt/codegt is that it may - take any action whatsoever.
-
- _at_see java.lang.Threadrun()
- /
- public abstract void run()
-
31How is Runnable used?
- An object which is Runnable has a run method.
- An object which is Runnable can be run in a
specific thread. - The javax.swing.SwingUtilities class provides a
method, invokeLater, which takes a Runnable, and
calls its run method once other events queued on
the event-dispatching thread have been handled.
32What does this have to do with graphics?
- To be thread safe graphical applications should
run their GUI code on the event-dispatching
thread. - They do this by starting their GUI on the
event-dispatching thread - write the GUI creation code in a Runnable
- pass this object to the invokeLater method.
33Graphical containers
- All graphical elements are contained inside some
graphical container, except the so-called
top-level containers. - Containers can contain other containers
- Top-level containers
- JFrame
- JDialog
- JApplet
34Example
- Creating just a frame
- new javax.swing.JFrame()
- Creating a frame with a title
- new javax.swing.JFrame(My title)
- Making the frame visible
- call setVisible(true) on the frame
- Making application close when window is closed
- call setDevaultCloseOperation(JFrame.EXIT_ON_CLOSE
) on the frame - Go look at example_set_1
35Adding components
- Top-level containers have multiple panes
- Content pane is the one which holds components
- call getContentPane() on frame to get frames
content pane - call add() on content pane to add a component
36A simple component
- A JLabel is a component that can display text or
an image. - Go look at example_set_2
37Layout managers
- What happens if we add another JLabel?
- Go look at example_set_3
38Another component
- A JButton is a component which is typically set
up to react to clicks. - Clicks on buttons, mouse movements, etc. are all
considered events. - A program can react to events by setting up event
handlers. - Like an exception handler, an event handler
defines what should happen when a particular
event occurs.
39Event handling 1
- The component which gives rise to an event is
decoupled from the part of the code that handles
the event. - This is called the observer pattern.
- General form
- www.research.ibm.com/designpatterns/example.htm
40Event handling 2
- Observer pattern in Java
- An observer is called a listener in Java
- Button clicks are ActionEvents.
- Handlers for ActionEvents are ActionListeners.
- An event-generator can have many listeners
- Use addActionListener method to register a
listener with a component
41Inner Classes
- An inner class is a class defined inside another
class. - An inner class is within the scope of the
surrounding class (and therefore has access to
private variables and methods defined in class). - An anonymous inner class is an inner class
defined without a name (a one-off class) - saw this earlier with Runnable interface
implementation - Inner classes are often used to define event
handlers, especially anonymous inner classes.
42Event handling - 3
43Putting it all together
44Topic overview
- Swing components in (more) detail
- Containers
- top-level containers
- general containers
- special-purpose containers
- Controls
- Views (uneditable displays)
- Editors
- Layout managers in (more) detail
45Containers
- Top-level containers
- JApplet, JFrame, JDialog (and subclasses)
- They can serve as the top of a (graphical)
containment hierarchy (i.e. they dont need to be
contained within another container). - General containers
- panels, scroll panes, split panes and tabbed
panes - They provide fairly general ways of organizing
information visually. - Special-purpose containers
- Wont go into these here.
46Controls
- Swing provides many controls
- Separable model architecture
- Well touch on
- check box
- list
- menu
- spinner
- your choice, time permitting
47Views
- Views are information displays that cannot be
edited. - labels, progress bars, tooltips
48Editors
- Editors are information displays which allow
editing. - editor pane, text pane, color chooser, file
chooser, table, etc. - Can be very complex.
49Containers
- JPanel is a very generic container.
- JScrollPane is a container that can provide
scrollbars to shift a viewport to show
different parts of an underlying view. - JSplitPane provides a movable partition between
two parts of a pane. - JTabbedPane provides a tabbed environment for
displaying different views.
50JScrollPane
- (see session5.scrollpane)
51JSplitPane
52JTabbedPane
- (see session5.tabbedpane)
- Show tooltips.
- Show mnemonics.
53Combining containers!
54JCheckBox
55Model-View-Controller
- The Model-View-Controller pattern is often used
to help architect GUI applications - the model holds data
- a view displays data from the model to user
- a controller handles user input and communicates
with the model
V
V
M
M
C
C
56Models and Views
- Use lists as an example.
- The model (the data provider) of a list is
separate from its View/Controller. - A JList is the view-controller, which
communicates with an underlying ListModel.
57How do you create a model?
- You can implement the ListModel interface to
create a custom data model. - The JList constructor allows you to pass in an
array or a vector of data elements, which it then
uses to build a default ListModel automagically.