57
Java Foundation Classes (JFC/Swing) Carl Alphonce revised Spring 2007 (with contributions from Alan Hunt)

Java Foundation Classes (JFC/Swing) Carl Alphonce revised Spring 2007 (with contributions from Alan Hunt)

Embed Size (px)

Citation preview

Java Foundation Classes

(JFC/Swing)

Carl Alphoncerevised Spring 2007

(with contributions from Alan Hunt)

JFC/Swing lectures

Java 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.

JFC/Swing lectures

Overview Patterns Containers and Components Threads

JFC/Swing lectures

Some patterns used OBSERVER STRATEGY COMPOSITE DECORATOR

JFC/Swing lectures

Some patterns used - examples OBSERVER – event handling STRATEGY – layout management COMPOSITE – containers are also components DECORATOR – scrollbars, streams

JFC/Swing lectures

java.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.

JFC/Swing lectures

Containers

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

JFC/Swing lectures

javax.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.

JFC/Swing lectures

An 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();

}

}

JFC/Swing lectures

Composite Pattern

JFC/Swing lectures

Composite 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

JFC/Swing lectures

Input 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.

Let’s first examine the JButton.

JFC/Swing lectures

Button Example

JButton button = new JButton("Push Me");

f.getContentPane().add(button);

button.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {

label.setText("Clicked");}

});

JFC/Swing lectures

OBSERVER PATTERN – general form

Idea: decouple event from event handling

Concrete Observable

Abstract Observable

Concrete Observer

0..*

Abstract Observable

attach(Observer)

detach(Observer)

notifyObservers()

Abstract ObservableAbstract Observer

update()

JFC/Swing lectures

JFC 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.

JFC/Swing lectures

OBSERVER PATTERN - applied

In JFC/Swing, Observer is realized for different event types, with methods named accordingly.

Abstract Observable

0..*

JButton

addActionListener(ActionListener)

removeActionListener(ActionListener)

fireActionPerformed(ActionEvent)

Abstract ObservableActionListener

actionPerformed(ActionEvent)

attach addActionListenerdetach removeActionListenernotifyObservers fireActionPerformed

update actionPerformed

JFC/Swing lectures

Multiple 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);

}

});

JFC/Swing lectures

DECORATOR A decorator adds functionality while

maintaining an interface. One example:

InputStreamReader wraps InputStream BufferedReader wraps InputStreamReader

Another example: JScrollPane wraps Jlist

JFC/Swing lectures

STRATEGY 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.

JFC/Swing lectures

Layout Managers Swing has several different layout

managers. Some of the most common are FlowLayout, BorderLayout, GridLayout, and GridBag Layout. Each has advantages and disadvantages.

JFC/Swing lectures

BorderLayout

The BorderLayout manager creates an object that resembles a picture with a four sided frame, or border.

JFC/Swing lectures

FlowLayout 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.

JFC/Swing lectures

GridLayout GridLayout arranges its components in an

equally spaced grid of cells. Will take as much space as is available to it.

JFC/Swing lectures

GridBag 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.

JFC/Swing lectures

Topic overview Processes & Threads Containers (graphical) Components Layout managers Event handling Inner classes

JFC/Swing lectures

Processes and Threads What is a process? What is a thread? two special Java threads

main thread event-dispatching thread

the Runnable interface

JFC/Swing lectures

Processes 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

JFC/Swing lectures

Threads 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

JFC/Swing lectures

Two 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.

JFC/Swing lectures

Runnable interface The Runnable interface specifies one method:

public interface Runnable { /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run();}

JFC/Swing lectures

How 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.

JFC/Swing lectures

What 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.

JFC/Swing lectures

Graphical 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

JFC/Swing lectures

Example 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

JFC/Swing lectures

Adding components Top-level containers have multiple panes Content pane is the one which holds

components call getContentPane() on frame to get frame’s

content pane call add(…) on content pane to add a

component

JFC/Swing lectures

A simple component A JLabel is a component that can display

text or an image. Go look at example_set_2

JFC/Swing lectures

Layout managers What happens if we add another JLabel?

Go look at example_set_3

JFC/Swing lectures

Another 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.

JFC/Swing lectures

Event 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

JFC/Swing lectures

Event 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

JFC/Swing lectures

Inner 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.

JFC/Swing lectures

Event handling - 3 Go look at example_set_4

JFC/Swing lectures

Putting it all together Go look at example_set_5

JFC/Swing lectures

Topic 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

JFC/Swing lectures

Containers Top-level containers

JApplet, JFrame, JDialog (and subclasses) They can serve as the top of a (graphical) containment

hierarchy (i.e. they don’t 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

Won’t go into these here.

JFC/Swing lectures

Controls Swing provides many controls “Separable model architecture” We’ll touch on:

check box list menu spinner your choice, time permitting

JFC/Swing lectures

Views Views are information displays that cannot

be edited. labels, progress bars, tooltips

JFC/Swing lectures

Editors Editors are information displays which

allow editing. editor pane, text pane, color chooser, file

chooser, table, etc. Can be very complex.

JFC/Swing lectures

Containers 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.

JFC/Swing lectures

JScrollPane (see session5.scrollpane)

JFC/Swing lectures

JSplitPane (see session5.splitpane)

JFC/Swing lectures

JTabbedPane (see session5.tabbedpane) Show tooltips. Show mnemonics.

JFC/Swing lectures

Combining containers! (see session5.combined)

JFC/Swing lectures

JCheckBox (see session5.checkbox)

JFC/Swing lectures

Model-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

C

M

V

M

C

JFC/Swing lectures

Models 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.

JFC/Swing lectures

How 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.