GUI Libraries in Java



General Information

Introduction to GUI

Key API's:

Reactive Programming

Callbacks, invisible event loop ... The observer pattern or the publish/subscribe pattern. More efficient than polling.

Appearance is controlled by the invisible agent that notices that the window needs repainting. The programmer must override paint and created the appearance of the entire area (or cobble widgets together that take the responsiblity for their area upon themeselves). Many of the earlier applet examples were of this simple form where paint was overriden.

Example GUI Applications

root pane root pane

paint

The method paint of class Component is called under three circumstances:
  1. whenever you're component is resized (in particular, when it is first mapped to the screen),
  2. whenever the component is fully or partially exposed (that is, when a window that was covering it is moved out of the way), and
  3. if you don't override the component's update method, paint will get called whenever the update method gets called (that is, whenever you call repaint()).

It is usually better to call repaint() then to call paint() directly, because if you call repaint() 10 times before the screen updater actually gets around to doing the painting, your paint method will only get called once, which is more efficient.

Threads and Swing

Updating a component while not executing in an event handler could possiblilty cause a deadlock. To avoid this problem use one of two SwingUtilities: invokeLater or invokeAndWait.

Model-View-Controller

mvc
Java Swing, by Eckstein et al.
delegate
Java Swing, by Eckstein et al.

UI delegate = User-Interface delegate.

Widgets

A combination of a graphic symbol and some program code to perform a specific function, e.g., a scroll-bar or button. In the PC world a widget is sometimes known as a control. Windowing systems usually provide widget libraries containing commonly used widgets drawn in a certain style and with consistent behavior.

AWT versus Swing

AWT: old and ugly; Swing: slow and pretty. Swing replaces all the widgets, but not all the underlying, suppport classes of AWT, e.g., Font, Color. Don't mix AWT and Swing widgets because of z-order. Also AWT components can't print themselves.

AWT are said to be "heavyweight" because they have "peers" (platform specific constructs) that do the real work. Swing components are said to be "lightweight" most of the work is done by Java.

AWT Components

Button, Checkbox, Choice, Label, List, TextComponent, Scrollbar, Canvas
MenuComponent: MenuBar, MenuItem
Container:  Panel, Window

Swing Components

JButton, JCheckBox, JComboBox, JLabel, JList, JTextComponent, JSlider, JScrollBar, JProgressBar
Menus: JMenuBar
Fancy: JTable, JTree, JInternalFrame
JTable JTree internal frames
Containers:  JPanel, JWindow, JFrame, JApplet, 
Specialty Containers:  JScrollPane, JLayeredPane, JSplitPane, JTabbedPane
scroll layered split tabbed
Dialogs: JDialog, JFileChooser, JColorChooser
Other:  Borders

Swing Tour

Screen shots of version 1.1 JFC Swing demo called "SwingSet." Better to execute latest version from JDK demo directory (part of the documentation download, not the main JDK download).
java -jar demo/jfc/SwingSet/SwingSet.jar

Look-and-Feel

Every UI delegate consults a UI manager. The UI manager controls many common resources (fonts, colors) and is initialized when the look-and-feel is first established.

Solaris

Swing Widgets (Metal)
java -Dswing.defaultlaf=com.sun.java.swing.plaf.motif.MotifLookAndFeel JWidgets
Swing Widgets (Motif)

Windows

Swing Widgets (Metal)
java -Dswing.defaultlaf=com.sun.java.swing.plaf.motif.MotifLookAndFeel JWidgets
Swing Widgets (Motif)
java -Dswing.defaultlaf=com.sun.java.swing.plaf.windows.WindowsLookAndFeel JWidgets
Swing Widgets (Windows)

Ubuntu

Swing Widgets (Ubuntu)
Swing Widgets (Ubuntu)
Swing Widgets (Ubuntu)
Mac look-and-feel exists. It is possible to create your own look-and-feel.

See all the Java SwingSet demo.

Hierarchical Windows

Two hierarchies --- each is important.

Notice that a container is a (extends a) component in the usual inheritance hierarchy. Some are containers --- they extend . Others components are widgets -- fundamental GUI units.

A particular GUI is orgainized by putting some set of widgets in a container. These containers (which are components) may be put in other containers and so on.

You only need one container (the window) and you can put all the widgets in it. But is far better to orgainize the widgets in small groups in their own containers. This leads to a second hierarchy.

 
Also, logical layout.

All the components in a Java GUI will print themselves to System.err if you press control+shift+F1.

Coordinate System

coordinate system

Graphics Object

What is that argument to paint? Ultimately all shapes, text, and images are drawn by a Graphics object. A class encompassing all the state necessary to describe such drawing: color, font, and options.

Java 2D

Java 2D Graphics in the Java Tutorial.

Shapes

The classes in the java.awt.geom package define common graphics primitives, such as points, lines, curves, arcs, rectangles, and ellipses.

Classes in the java.awt.geom Package
Arc2D Ellipse2D QuadCurve2D
Area GeneralPath Rectangle2D
CubicCurve2D Line2D RectangularShape
Dimension2D Point2D RoundRectangle2D

Arc2D, Ellipse2D, Rectangle2D, RoundRectangle2D all extend RectangularShape. They are also specified using x, y, width, and height.

drawing rectangle

Original (non "2D") Graphics

public abstract class Graphics extends Object {
   public void draw3DRect (int x, int y, int width, int height, boolean raised)
   public void drawArc (int x, int y, int width, int height, int startAngle, int arcAngle)
   public void drawLine (int x1, int y1, int x2, int y2)
   public void drawOval (int x, int y, int width, int height)
   public void drawPolygon (int[] xs, int[] ys, int n)
   public void drawRect (int x, in y, int width, int height)
   public void drawString (string str, int x, in y)
   public void drawImage (image img, int x, int y, int width, int height, ImageObserver obs
}

Color

Constants in class Color:
    Color white     = new Color(255, 255, 255);
    Color lightGray = new Color(192, 192, 192);
    Color gray      = new Color(128, 128, 128);
    Color darkGray  = new Color(64, 64, 64);
    Color black     = new Color(0, 0, 0);
    Color red       = new Color(255, 0, 0);
    Color pink      = new Color(255, 175, 175);
    Color orange    = new Color(255, 200, 0);
    Color yellow    = new Color(255, 255, 0);
    Color green     = new Color(0, 255, 0);
    Color magenta   = new Color(255, 0, 255);
    Color cyan      = new Color(0, 255, 255);
    Color blue      = new Color(0, 0, 255);
brighter () is RGB / 0.7  (ie., 1.42 * RGB)
  darker () is RGB * 0.7

Fonts

Dialog
Helvitica
TimesRoman
Courier
DialogInput
ZapfDingbats
style:  PLAIN, BOLD, ITALIC, Font.BOLD|Font.ITALIC
Starting with J2SDK 1.2.1, Java applications require a font property file to properly display the application's AWT windowing and Java2D components. This file contains mappings of Java logical font names to physical fonts on the X server. Previous versions of the JDK 1.1.n did not require this file. Instead of using Java default fonts, which were resolved at run-time by the X server to physical fonts on the display side, the font.properties file provides a mapping of the Java logical font names to fonts on the system.
Available Fonts:
  
  Akhbar MT
  ...

Images

Atomic Components

JButton

JCheckBox

JTextField

JFormattedTextField (J2SE 1.4)

Regular Expression Based AbstractFormatter

JComboBox

JList

You can specify a different selection mode by calling the setSelectionMode method on the list. The following table describes the three list selection modes:

ModeDescriptionExample
SINGLE_SELECTION Only one item can be selected at a time. When the user selects an item, any previously selected item is deselected first. Single selecti
on means only one item can be selected at once
SINGLE_INTERVAL_SELECTION Multiple, contiguous items can be selected. When the user begins a new selection range, any previously selected items are deselected first. Single
 interval selection means multiple, contiguous items can be selected at once
MULTIPLE_INTERVAL_SELECTION The default. Any combination of items can be selected. The user must explicitly deselect items. Mult
iple interval selection means any combination of items can be selected at once

Events

AWTEvents

Event CategoryDescription
actioninitiated by, e.g., buttons, to indicate a command should be performed
adjustmentinitiated by, e.g., scrollbars, to indicate a value has been changed
ancesterinitiated by any component when it has been reparented
componentinitiated by any component when it has been moved or resized
focusinitiated by any component when it has lost or gained the focus
iteminitiated by, e.g., list boxes, to indicate the state of an item has changed
input methodIf the text component that's currently using the input method is an active client, the event is dispatched to that component. Otherwise, it is dispatched to a separate composition window.
internal framesupport for Swing JInternaFrame
invocationAn event which executes the run() method on a Runnable when dispatched by the AWT event dispatcher thread
keyinitiated by a key press or release
mouseinitiated by a mouse movements or clicks
textinitiated by text componentes to indicate a change in the text
windowinitiated by windows when closed, iconfied, etc.

ActionEventActionListener
actionPerformed(ActionEvent)
Button
List
TextField
MenuItem
AdjustmentEventAdjustmentListener
adjustmentValueChanged(AdjustedEvent)
Component
ComponentEventComponentListener
componentMoved(ComponentEvent)
componentHidden(ComponentEvent)
componentResized(ComponentEvent)
componentShown(ComponentEvent)
Component
FocusEventFocusListener
focusGained(FocusEvent)
focusLost(FocusEvent)
Scrollbar
ItemEventItemListener
itemStateChanged(ItemEvent)
Checkbox
MenuItem
Choice
List
KeyEventKeyListener
keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTyped(KeyEvent)
Component
MouseEventMouseListener
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
mouseClicked(MouseEvent)
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
Component
MouseMotionListener
mouseDragged(MouseEvent)
mouseMoved(MouseEvent)
Component
TextEventTextListener
textValueChanged(TextEvent)
TextComponent
WindowEventWindowListener
windowClosing(WindowEvent)
windowOpened(WindowEvent)
windowIconified(WindowEvent)
windowDeiconified(WindowEvent)
windowClosed(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)
Window

Adapter classes for java.awt (JDK 1.3)
Event ClassListener InterfaceAdapter Class
ComponentEventComponentListenerComponentAdapter
ContainerEventContainerListenerContainerAdapter
FocusEventFocusListenerFocusAdapter
HierarchyBoundsEventHierarchyBoundsListenerHierarchyBoundsAdapter
KeyEventKeyListenerKeyAdapter
MouseEventMouseListenerMouseAdapter
MouseMotionEventMouseMotionListenerMouseMotionAdapter
WindowEventWindowListenerWindowAdapter
Event ClassListener InterfaceAdapter Class
InternalFrameEventInternalFrameListenerInternalFrameAdapter
MouseInputEventMouseInputListenerMouseInputAdapter

Why are the decorations lost on Windows?

Layout

Composite Components

Why does border not get set right?

JTable

Here is series of increasingly sophisticated examples of JTable based on Chapter 6 “Swing's JTable Compentent” of Brent Spell's book Professional Java Programming.
JTable window dump
JTable window dump
JTable window dump
JTable window dump
JTable window dump

Borders

Borders See also the BorderDemo application.

Menu Bar

Menu demo screen dump Menu demo screen dump Menu demo screen dump

Data Transfer

A clipboard is an area within memory for storing temporary information in support of cut, copy, and paste tasks. There is a "System" clipboard to share data between applications and you can create private clipboards for sharing data within a single application.
Ryan Stansifer <ryan@cs.fit.edu>
Last modified: Tue Nov 15 16:09:33 EST 2011