Swing
Based on Chapters 19,21 and 22 from the book "Just Java 2" by Peter van der
Linden (5th. Edition).
You can find a good tutorial about Swing in the Java site at:
http://java.sun.com/docs/books/tutorial/uiswing/
Event Handlers (Chapter 19)
GUI libraries have four basic areas of functionality:
- Creation of components (buttons, labels, text areas).
- Giving behavior to the components: Tying GUI events to code.
- Placing and grouping components on the screen.
- Access to window manager facilities
One of Java's most important goals is portability. Java code should
run on different environments without recompilation.
In the first releases, GUI operations were supported using
a set of classes called AWT (Abstract Window
Toolkit).
AWT provides a way of taking advantage of the local Window Management
Environment by using the native library part of the Java distribution.
Swing is an all-Java GUI. It uses basic native canvases, but the
rest of the behavior is implemented in Java.
Classes in Swing start with the upper case letter J.
When programming an application with a GUI in Java the following steps
are necessary:
- Declare componentes as buttons, menus and choices
- Implement an interface to supply an event handler that will respond
to user actions on the components. It is possible to use anonymous classes
to implement this code.
- Add the components to a container. Containers are displayed on the screen.
A container can hold several components.
Event handling is asynchronous. It is not possible to predict
in which particular order the user will interact with the components
on a GUI. Therefore, an event-driven style of programming is used:
The runtime system contains a main loop that waits for the user
to perform an input action (for instance clicking on a button
or moving the mouse).
When the user performs an action, the operating system notifies
the window manager. The window manager generates an event.
Inside the program's runtime environment there is a table that specifies
which particular object
should be called when a particular event occurs.
If no object was registered for a this event, the event is ignored.
This process is called a callback.
The code that is called is a callback routine, because the window system
calls back to it when the event happens.
In Java, the events that are sent to the event-handlers are objects
passed as arguments to a method call. All events in Java are children
of the class
A number of different interfaces have been designed to handle
different kinds of events.
Part of these interfaces are part of the package
java.awt.event.
And there are other events and listeners declared in the package
javax.swing.event.
One writes code in an event handler to implement the appropriate kind of
interface, in other words, one needs to supply code for the methods
promised in the interface that one is implementing.
The basic framework for event handlers is:
- Write a class that implements a "Something"Listener interface.
- Declare an object of the class above and call it mySomethingHandler
- On the component, call the addSomethingListener(mySomethingHandler) method.
When writing an event handler class, it is possible to use inner classes:
Classes whose entire code appears right in the place where they
are used and instantiated (see page 637 in the book for an example).
The class that will handle the events does not have to be a separate
class from the main class in the GUI.
The main class in the GUI can also be the event handler by
implementing the appropriate interface(s) required to handle
the user's actions (see page 638 in the book for an example
or the sample applet available in the Syllabus).
Because implementing Event Handling Interfaces is so common,
"adapter" classes have been added to the Java library that simplify
the writing classes to implement Event Handling Interfaces.
An "adapter" class contains all the methods specified in
the interface it implements but all those methods contain no code
(see example in page 639).
So if one needs to write code to handle a certain event,
one can extend an "adapter" class and override only the
method that one is interested in. Thus, one avoids having to
type empty bodies for all the other methods in the interface
that one is not interested in implementing.
JFC and Swing (Chapter 21)
Java Foundation Classes
The Swing components replace the AWT versions of these components.
AWT is still used for layout control and printing.
Browsers now support Swing through the use of plug-ins.
AWT components were heavyweight components: They used objects
from the host operating system.
Swing components are lightweight components. They are drawn
by Java code on a piece of the screen that already belongs to Java.
It is drawn in a container.
Mouse events on a lightweight component are delivered to its container.
If you want a JButton to get mouse events, add the listener to
the container.
It is better not to mix Swing JComponents with AWT components.
JComponent is the parent class for most objects that can appear on
screen.
The main categories of Swing components are:
- Basic Controls:
JButton,
JCheckBox,
JRadioButton,
JComboBox,
JList,
JMenu,
JMenuBar,
JMenuItem,
JSlider, JToolbar, JTextField, JPasswordField,JTextArea, JFormattedTextField.
- Uneditable Displays:
JLabel, JToolTip, JProgressBar.
- Editable Displays: JTable, JTextPane, JTextArea,
JEditorPane, JTree, JColorChooser,
JFileChooser, JSpinner
- Space-Saving Containers: JScrollPane, JScrollBar, JSplitPane, JTabbedPane
- Top-Level Containers:
JFrame,
JApplet,
JDialog,
JOptionPane.
- Other Containers: JPanel, JInternalFrame, JLayeredPane, JRootPane
The components are added to the content pane of their container
(not directly to the container itself as in AWT) using a call similar to:
myJContainer.getContentPane().add(myJComponent)
If one is writing an Applet using Swing components, one should JApplet.
The container must be setup before the components are added.
Look at this example (taken from page 686 in the book):
// All three packages should be imported.
// Swing requires AWT
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Demo {
static JFrame jframe = new JFrame("Example");
public static void setupJFrame() {
// Set the size of the frame
jframe.setSize(400,100);
// Make it visible
jframe.setVisible(true);
// Specify the kind of layout that will be used
jframe.getContentPane().setLayout( new FlowLayout() );
// The following piece of code is an example of an inner class.
// It is used as the handler for Window events
// In this particular case, an adapter is used and only one method
// is overridden.
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
jframe.addWindowListener(l);
public static void main(String [] args)
{
setupJFrame();
JButton jb = new JButton("Pressure");
jframe.getContentPane().add(jb);
jframe.setVisible(true);
}
}
Containers and Layouts (Chapter 22)
With Swing, it is possible to select the "Look and Feel" of the window.
One can choose between a Java look, a Unix look or a Windows look
(see illustration in page 713).
The elements that will be part of the GUI need a container to be placed.
Depending on the kind of application, there are two main kinds of containers
in Swing:
-
JFrame: Which can be used in regular applications
-
JApplet: Which can be used in Applets
There are other containers available:
JPanel: A generic container that is always in some other container.
This serves a glue to bind several components in a single unit.
JWindow: A totally blank window. Usually one uses either JFrame or JDialog instead.
JDialog: This is typically used to create a subwindow that asks the user
for particular additional information.
The parent class of containers is
Container
whose methods will allow the programmer to:
- Specify the layout manager
- Adding a ContainerListener for ContainerEvents
- Adding, removing or retriving a list of components
- Setting the size
- Paint when graphics are being used.
Layouts
To specify the locations of the components in a Container, Layouts
are used.
There are several layouts available:
These layouts can be combined.