The Java Foundation Classes (JFC) are a comprehensive set of GUI components and services which dramatically simplify the development and deployment of commercial-quality desktop and Internet/Intranet applications.
Size: 742.75 KB
Language: en
Added: Mar 11, 2025
Slides: 110 pages
Slide Content
JAVA FOUNDATION CLASSES
Arun Seetharaman
March 10, 1998
OVERVIEW
•What is Java Foundation Classes?
•Building UI using Swing components
•MVC-enabled components
•Common dialogs
JDK1.1 GOALS
•More Components
•ScrollPane, PopupMenu
•Data Transfer APIs
•Cut and Paste operations
•Lightweight UI Framework
•Java Beans
WHAT JFC IS
•Comprehensive component suite
•Not a replacement for AWT
•Look and Feel independent
•Application services -pluggable
•Support “Accessibility”
JFC CONSTITUENTS
•JFC consists of five major packages
•Swing
•PLAF
•Drag and Drop
•Java 2D
•Accessibility
SWING V/S AWT
•Lighter than AWT
•AWT continues for compatibility and to allow transition
•Menus are first class components
•can be fitted on containers
•Support for Image labels
JROOTPANE -THE
PARENT
•JRootPane is fundamental to the JFC/Swing window,
frame, and pane containers
•The container classes delegate operations to a
JRootPane instance
•JFrame, JDialog, JWindow, and JApplet are all
heavyweight containers
•The JInternalFrame is a the lightweight container
JROOTPANE HIERARCHY
JROOTPANE -
CONSTITUENTS
•A JRootpane is made up of a glassPane, an optional
menuBar, and a contentPane
•The glassPane sits over the top of everything
•The contentPane must be the parent of any children of
the JRootPane
•The menuBar component is optional
JROOTPANE
ORGANIZATION
JCOMPONENT -THE
ROOT
•Base for all Swing components
•Derived from the Container class of AWT
•Carries the additional overhead of the container class,
though may not be used
•Can be combined or extended to create custom
components
PROPERTIES OF
JCOMPONENT
•Client properties
•ToolTip support
•Border property
•Size preferences
•KeyStroke handling
•Double-buffering
•DebugGraphics
CLIENT PROPERTIES
•A per-instance hashtable associated with every
component
•APIs to manipulate the hashtable
•putClientProperty(Object,Object)
•getClientProperty(Object)
•If value is null, the property is removed
•Changes can be reported using the
PropertyChange events
TOOLTIP SUPPORT
•Used to display a "Tip" for a Component
•Use the setToolTipText method to specify the
text for a standard tool tip
•The setToolTipLocation method can be used
to specify the upper left corner of the tool tip
•Can create a custom ToolTip display can override
JComponent's createToolTipmethod
JTOOLTIP -AN EXAMPLE
b1.setToolTipText("Click this
button to disable the middle
button.");
BORDERS
•Describes a border around the edges of a Swing
component
•Border supercedes the inset mechanism
•The paintBorder()method paints the border
•Use the setBorder(Border) API to set the
borders for any component
THE “BORDER”
INTERFACE
•Interface describing an object capable of rendering a
border
•Some implemented border styles
•EmptyBorder
•BevelBorder
•TitledBorder
•MatteBorder
•CompundBorder
SOME SWING BORDERS
SIZING OF COMPONENTS
•Swing components also have preferred, minimum and
maximum sizes
•Swing introduces setters for all these sizes
setPreferredSize(Dimension)
setMinimumSize(Dimension)
setMaximumSize(Dimension)
•If the dimension is null, default values are restored
KEYSTROKE HANDLING
•The JComponent class provides a wealth of keystroke
handling functionality
•Registering a keyboard action enables keyboard
events for that component
•KeyStroke objects are used to define high-level
(semantic) action events
•Stores a Hashtable of registered keyboard actions as a
client property
RECEIVING KEYSTROKES
•The void registerKeyboardAction(
ActionListener,String,KeyStroke,
int)method registers the key stroke
•Conditions for a action could be
•WHEN_FOCUSED
•WHEN_IN_FOCUSED_WINDOW
•WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
THE “KEYSTROKE” OBJECT
•Can be used with modifiers like alt, shift etc
•For virtual keys use the KeyEvent class
•All KeyStrokeobjects are immutable and unique.
•KeyStrokeobjects are cached and accessed using
the getKeyStroke() method
KeyStroke getKeyStroke(char);
KeyStroke getKeyStroke(int, int);
AUTOSCROLLING
•Provides components like JScrollPane and JViewPort
•JComponent class supports autoscrolling
•The setAutoscrolls method is used to enable or
disable autoscrolling
•Autoscrolling is not a bound property in the
JComponent class
DEBUGGRAPHICS
•Graphics subclass supporting graphics debugging
•Overrides all the methods of the Graphics class
button.setDebugGraphicsOptions(
DebugGraphics.FLASH_OPTION);
•Double buffering, if enabled must be turned off
RepaintManager setDouble
BufferingEnabled(boolean);
ICONS AND
IMAGEICONS
•An icon is a small fixed size picture, typically used to
decorate components
•ImageIconis an implementation of the Icon
interface that paints Icons
•The paintIconmethods paints the content on the
specified graphics object
ImageIcon bulb1 = loadImageIcon
("images/bulb2.gif","light bulb");
button.setSelectedIcon(bulb2);
THE “BUTTON”
HIERARCHY
•The AbstractButton class is at the top of the button
hierarchy
•Provides the default properties required for buttons like
text, alignment etc.
•Provides for interaction with a button model
•The doClick()allows the button to be clicked
programmatically
JBUTTON -THE SIMPLEST
•The most commonly used button is the JButton, that defines
a normal push button
JButton ok = new JButton( "OK" );
ok.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e) {
JButton button = e.getSource();
ButtonModel b = button.getModel();
// Print the various states of the button
}
SOME SWING BUTTONS
TOGGLE BUTTONS
•The JToggleButton defines the implementation of a
two-state button
•Two important subclasses:
•JRadioButton
•JCheckBox
•Use the ButtonGroup to create a logical grouping of
radio buttons
SOME RADIO BUTTONS
MODEL-VIEW-
CONTROLLER
•Popularly known as MVC pattern
•Not a new architecture, has been used by programmer
for years
•Data is represented in a model
•Viewspresent the data
•Controllersare used to interact with the model
JFC AND MVC
•JFC implements a slight variant of MVC
•The visual components are both views and controllers
•Models are represented by interfaces
•Default implementation of models are available
•More efficient as multiple copies are not maintained by
the component
MODEL INTERFACES IN
JFC
•Some examples of model interfaces
•ButtonModel
•ComboBoxModel
•ListModel
•ListSelectionModel
•SingleSelectionModel
LISTS AND COMBOS
•Components that allow users to select from a list of
choices
•JList -allows single or multiple selection
•JComboBox -allows only single selection
•Data models are very similar with the ComboBoxModel
derived from ListModel
•Defines a separate model for selection
A CUSTOM LISTMODEL
class TestListModel extends
AbstractListModel {
String[] fruits = {"Apple",
"Banana","Orange","Pear"};
public int getSize() {
return( fruits.length );
}
public Object getElementAt(int
index) {
return( fruits[ index ] );
}
}
SOME SWING COMBO
BOXES
RENDERERS
•The “Renderer” interface defines the requirements for
an object for rendering
•Renderers available for component specific rendering
•DefaultListRenderer
•BasicComboBoxRenderer
•TableCellRenderer
A CUSTOM RENDERER
class MyCellRenderer extends Jlabel
implements ListCellRenderer {
// Implement getListCellRendererComponent
}
Jlist list = new Jlist();
list.setCellRenderer(new MyCellRenderer());
BOUND COMPONENTS
•Components having values represented by a
numerical range
•Scroll bars, sliders, progress bars etc. are good
examples
•Use the BoundRangeModel to manage the range and
values
THE “BOUNDRANGEMODEL”
INTERFACE
•Defines four interrelated integer properties: minimum,
maximum, extent and value
minimum <= value <=
value+extent <= maximum
•The four BoundedRangeModel values are defined as
Java Beans properties
•Swing ChangeEvents are used to notify clients of
changes rather than PropertyChangeEvents, to lesser
overhead
CHANGE EVENT AND
LISTENER
•Defines the responsibilities of listeners to a
BoundedRangeModel instance
•The stateChanged() method is invoked whenever
the properties in an bound range model change
•The ChangeEventobject can be queried for the
source of the event
A JSLIDER EXAMPLE
JSlider slider = new JSlider();
slider.setMajorTickSpacing( 20 );
slider.setMinorTickSpacing( 5 );
slider.setPaintTicks( true );
slider.setPaintLabels( true );
slider.setLabelTable( table );
slider.setBorder( BorderFactory.
createLoweredBevelBorder());
SOME SWING SLIDERS
SCROLLING
COMPONENTS
•Many JFC components like lists and combo boxes need
a scrolling capability
•Delegate the scrolling capability to a single component
than have the same built in every component
•Similar to the ScrollPane class introduced in JDK 1.1x
•Provides a viewport in addition
THE “JVIEWPORT” CLASS
•Used to manage the view of the underlying
component
•A viewport can be thought of as the viewer on a
camcorder
•Different movements result in visibility of different
portions of the component
•Initially, the upper-left corner of the component is
aligned with that of viewport
MORE ON JVIEWPORT
•A viewport can be configured to create an offscreen
image that buffers the visual representation
•This offscreen image is known as the backing store,
helping in faster scrolling
•Trade-off between time and memory
•Once allocated, backing store will not be garbage
collected until the viewport is garbage collected
VIEWPORT LAYOUT
•JViewport classes uses an instance of ViewportLayout
to manage its child
•It assumes it is managing a JViewport and hence
cannot be used as a general-purpose layout
•If components are smaller, extra space is created to
the right or bottom of the component
THE “JSCROLLPANE”
CLASS
•A class typically used for scrolling a component
•It manages a JViewport instance, scrollbars and
viewport headings
•The viewport is specified by using the
setViewport() method
•If the setViewportView() method is used,
JScrollPane creates the view itself
SCROLL PANE AND
VIEWPORT
JSCROLLPANE -AN
EXAMPLE
Font ourFont = new Font(
"Helvitica",Font.BOLD,24);
JLabel label = new JLabel();
label.setText( "This is a long message that
will not" + " fit on may displays. " +
"Better scroll it!" );
label.setFont( ourFont );
box.add( label );
JScrollPane scrollPane = new
JScrollPane(box);
frame.getContentPane().add(
scrollPane, BorderLayout.CENTER );
THE “JTABBEDPANE”
CLASS
•A visual component that allows multiple panels to be
viewed one at a time
•The tabs on the tabbed panel represent the complete
set of options available for configuration
•A great deal of information to be presented to the user
in a relatively small amount of screen
JTABBEDPANE -AN
EXAMPLE
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(new JLabel(name),
BorderLayout.NORTH);
JTextField textField = new
JTextField(name );
panel.add(textField,
BorderLayout.SOUTH );
tabbedPane.add(panel,name);
tabbedPane.revalidate();
MENUS
•Created as first class Swing components
•Menu components are:
•JMenuBar
•JMenu
•JMenuItem
•JCheckBoxMenuItem
•JRadioButtonMenuItem
•JPopupMenu
A JMENU EXAMPLE
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu( "File" );
file.add( "New" );
file.add( "Open..." );
file.add( "Save" );
file.add( "Save As..." );
file.addSeparator();
file.add(“Exit”);
menubar.add(file);
A SWING MENU
TOOLBARS
•The JToolBar class facilitates creating and adding
toolbars to your application
•Current version of Swing is designed for a single toolbar
•Toolbar follows a BoxLayout and orients itself along the
x-axis or y-axis
•Should be added to the application using a
BorderLayout
JTOOLBAR -AN EXAMPLE
JToolBar toolBar = new JToolBar();
// Add items to the toolbar.
toolBar.add(new JButton(newIcon));
toolBar.add(new JButton(openIcon));
toolBar.add(new JButton(saveIcon));
toolBar.addSeparator();
toolBar.add(new JButton(printIcon));
toolBar.addSeparator();
toolBar.add(new JButton(exitIcon));
A SWING JTOOLBAR
THE “JTABLE”
COMPONENT
•The most complex of the JFC components to construct
•Undergone lot of modifications since its early release to
be more stable
•High performance views of tabular data
•Highly customizable the table appearance based on
requirements
A SIMPLE TABLE
Vector data = new Vector();
Vector row = new Vector();
row.addElement( "Mari" );
row.addElement( Color.red );
data.addElement( row );
// Add more rows like above
Vector columnNames = new Vector();
columnNames.addElement( "Name" );
columnNames.addElement( "Color" );
JTable table = new JTable(
data,columnNames);
A SAMPLE JTABLE
THE “JTABLEHEADER”
CLASS
•Represents the column header for a JTable component
•Allows to change column widths and column ordering
•Columns names can be dragged to reorder the
columns in the table
•Shares the same TableColumnModel that is associated
with the JTable
TABLE SELECTION
MODELS
•JTable uses the ListSelectionModel for its selection
abilities
•Use the setSelectionMode(int) to specify the
selection mode
•SINGLE_SELECTION -Only one index can be
selected
•SINGLE_INTERVAL_SELECTION -Allows single
continuous selection
•MULTIPLE_INTERVAL_SELECTION -No
restriction on what can be selected
ROW AND COLUMN
SELECTION
•In addition to the specified list selection model, JTable
allows row and column selection
•setRowSelectionAllowed(boolean)
•setColumnSelectionAllowed(boolean)
•Both the value being false indicate cell selection
USING MODELS FOR
JTABLE
•The TableModelinterface specifies the methods the
JTable will use to interrogate the data model
•This information is used to select appropriate editors
and renderers
•Implementing class needs to manage all
TableModelListeners
•Can also use the AbstractTableModel class
TABLEMODEL -AN
EXAMPLE
String[] columnNames = {”Entity",
"Pressure","Temperature"} ;
Vector rows = new Vector() ;
public String getColumnName(int) { }
public Class getColumnClass(int) { }
public int getColumnCount() { }
public int getRowCount() { }
public Object getValueAt(int,int) { }
public void setValueAt(Object,
int,int) { }
USING THE
“TABLECOLUMNMODEL”
•Delegate of the JTable’s column model
•Not normally implemented by developers
•Use the DefaultTableColumnModel instead
•The view and model are connected through interfaces,
providing highly customizable implementations
•Can be changed dynamically
RENDERING JTABLE
•The createDefaultRenderers() method is
responsible for creating renderers
•Checkbox for boolean values
•Right alignment for number
•Icon for images
•Can be set globally or for a TableColumn instance
•Use setCellRenderer() of TableColumn
CELL EDITORS
•The createDefaultEditor() methods creates and
registers default editors for the table
•Can be explicitly registered using the setDefaultEditor()
method
•The TableCellEditor interface defines the methods for
objects interested in being editors
RENDERING AND EDITING
JComboBox comboBox = new JComboBox();
comboBox.addItem(Color.black);
comboBox.addItem(Color.gray);
comboBox.addItem(Color.red);
comboBox.addItem(Color.green);
comboBox.addItem(Color.blue);
comboBox.addItem(Color.white);
comboBox.setRenderer(new
ColorCellRenderer());
table.setDefaultEditor(Color.class,
new DefaultCellEditor(comboBox));
AN TABLE RENDERER
AND EDITOR
THE “JTREE”
COMPONENT
•Implementation of a control that represents
hierarchical data
•Create an easy tree-like configuration
•Consists of nodes and leaves
•Starts with a root node
•Creation and manipulation similar to using a JTable
component
A SIMPLE JTREE
Vector data = new Vector();
data.addElement( "Mike" );
data.addElement( "Mari" );
data.addElement( "Molly" );
JTree tree = new JTree( data );
frame.getContentPane().add( tree,
BorderLayout.CENTER );
A SAMPLE JTREE
TEXTUAL COMPONENTS
•Replacement for AWT text components
•JTextField
•JTextArea
•A new generation of components
•JPasswordField
•JTextPane
•JEditorPane
DOCUMENT MODEL
•Serves as the Model for text components
•Unit structure is an element, and views are built on
elements
•Defined in the Document interface, but the
AbstractDocument is more often used
•Provides for a built-in locking mechanism
THE JEDITORPANE CLASS
•Component to edit various kinds of content
•Morphs into the appropriate editor based on the
content type
•Currently support three styles:
•text/plain
•text/html
•text/rtf
•Hyperlink events generated if the pane is non-editable
HTML CONTENT
•JEditorPane supports content type using a plug-in
mechanism named Editor-kits
•HTMLEditorKit supports HTML 3.2
•Certain tags like <APPLET> not supported
•Modeled using a HTML document
•Uses the parser implemented in the HotJava browser
UNDO CAPABILITIES
•The javax.swing.undo package contain undo/redo for
applications like editors
•StateEditable defines the interface for objects that can
have their state undone/redone
•StateEdit is a general edit for objects that change state
•Store object state in Hashtables before and after
editing occurs
UNDO AND REDO -AN
EXAMPLE
public void restoreState(Hashtable state) {
Object data = state.get(KEY_STATE);
if (data != null)
setText((String)data);
}
public void storeState(Hashtable state) {
state.put(KEY_STATE, getText());
}
public boolean undo() {
undoManager.undo();
return true;
}
CREATING SPLITTER
WINDOWS
•The JSplitPane class manages two components
separated by a divider
•Can be split either horizontally or vertically
splitPane = new JSplitPane(
JSplitPane.VERTICAL_SPLIT,
topComponent,bottomComponent);
splitPane = new JSplitPane(
JSplitPane.HORIZONTAL_SPLIT,
leftComponent,rightComponent);
DIVIDER
CONFIGURATION
•Divider size if platform dependent
•Windows: 3 pixels
•Java: 8 pixels
•Motif: 18 pixels
•Can be configured using setDividerSize()
•Collapses and expands on a single click
splitPane.setOneTouchExpandable(true);
A SPLITPANE EXAMPLE
MDI APPLICATIONS
•Help in frame management
•Represent an MDI-like application
•JInternalFrameprovides the frame
•JDesktopPaneprovides the frame management
pane to add frames
•The DesktopManager is responsible for platform specific
issues
THE JINTERNALFRAME
CLASS
•A lightweight object that provides many of the features
of a native frame
•Delegates it child components to a JRootPane
instance
•Look and feel specific-actions are then delegated to
the DesktopManager
THE JDESKTOPPANE
CLASS
•A container used to create a multiple-document
interface or a virtual desktop
•JDesktopPane extends JLayeredPane to manage the
potentially overlapping internal frames
•Delegates operation on internal frames to a desktop
manager
USING TIMERS IN JFC
•A JFC class that causes an action to occur at a
predefined rate
•Timers maintain a list of ActionListeners and a delay
void start();
void stop();
void setCoalesce(boolean);
void setDelay(int);
void setRepeats(boolean);
TIMER -AN EXAMPLE
Timer timer = new Timer(5000,
new ActionListener() {
// Method called each time
public void actionPerformed(
ActionEvent event) {
System.out.println("Tick");
}
} );
// Start timer
timer.start();
COMMON DIALOGS IN
JFC
•AWT lacked good common dialogs except for a
FileDialog
•JFC provides some important class to fill the need for
common dialogs:
•Color chooser
•File chooser
•JOptionPane
CHOOSING COLORS
•JColorChooser provides a pane of controls designed to
allow a user to manipulate and select a color
•Select the color using any of the three options provided
•Color palette
•HSB Color Model
•RGB Color Model
THE “JCOLORCHOOSER”
CLASS
CHOOSING A FILE
•JFileChooser provides a simple mechanism for the user
to chooser a file
•Can be used with filters, extensions, descriptions etc.
•FileSystemView is JFileChooser's gateway to the file
system
•FileSystemView will eventually delegate its
responsibilities to I/O File classes
THE “JFILECHOOSER”
CLASS
JFILECHOOSER -AN
EXAMPLE
JFileChooser chooser =
new JFileChooser();
ExtensionFileFilter filter = new
ExtensionFileFilter();
filter.addExtension("jpg");
filter.setDescription("JPG Images");
chooser.setFileFilter(filter);
int returnVal =
chooser.showOpenDialog(parent);
THE “JOPTIONPANE”
CLASS
•Helps popup standard dialog boxes using static
methods
•showConfirmDialog(): Asks a confirming
question, like yes/no/cancel
•showInputDialog(): Prompt for some user input
•showMessageDialog(): Tell the user about
something that has happened
REVIEW
•Swing provides for some high components
•MVC pattern helps Swing components to manages
data efficiently
•High performance views using JTable, JTree etc.
•Document-based text components
•Support for common dialogs