SlideShare a Scribd company logo
JAVA FOUNDATION CLASSES
Arun Seetharaman
March 10, 1998
OVERVIEW
• What is Java Foundation Classes?
• Building UI using Swing components
• MVC-enabled components
• Common dialogs
JDK 1.0X DEVELOPER
FEEDBACK
• More built-in components
• Too primitive
• Needed lighter components
• native code is expensive
• APIs cleaned
• Easily extensible
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
Java Foundation Classes - Building Portable GUIs
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 createToolTip method
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 KeyStroke objects are immutable and unique.
• KeyStroke objects 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
• ImageIcon is an implementation of the Icon
interface that paints Icons
• The paintIcon methods 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
Java Foundation Classes - Building Portable GUIs
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
• Views present the data
• Controllers are 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());
Java Foundation Classes - Building Portable GUIs
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 ChangeEvent object 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());
Java Foundation Classes - Building Portable GUIs
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
Java Foundation Classes - Building Portable GUIs
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);
Java Foundation Classes - Building Portable GUIs
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 TableModel interface 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
Java Foundation Classes - Building Portable GUIs
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) { }
Java Foundation Classes - Building Portable GUIs
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));
Java Foundation Classes - Building Portable GUIs
Java Foundation Classes - Building Portable GUIs
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
Java Foundation Classes - Building Portable GUIs
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;
}
Java Foundation Classes - Building Portable GUIs
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
• JInternalFrame provides the frame
• JDesktopPane provides 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
Java Foundation Classes - Building Portable GUIs
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

More Related Content

PPT
2.swing.ppt advance java programming 3rd year
PPTX
Java_unit_1_AWTvsSwing.pptxn k , jlnninikkn
PDF
Eclipse e4
PDF
Modernize Your Real-World Application with Eclipse 4 and JavaFX
PDF
Java development with the dynamo framework
PPTX
Getting started with jQuery
PPTX
Knockout implementing mvvm in java script with knockout
PPTX
Mod_5 of Java 5th module notes for ktu students
2.swing.ppt advance java programming 3rd year
Java_unit_1_AWTvsSwing.pptxn k , jlnninikkn
Eclipse e4
Modernize Your Real-World Application with Eclipse 4 and JavaFX
Java development with the dynamo framework
Getting started with jQuery
Knockout implementing mvvm in java script with knockout
Mod_5 of Java 5th module notes for ktu students

Similar to Java Foundation Classes - Building Portable GUIs (20)

PDF
better-apps-angular-2-day1.pdf and home
PDF
Awesome html with ujs, jQuery and coffeescript
PDF
Micronaut and the Power of Ahead of Time Compilation - Devnexus 2019
PPT
14a-gui.ppt
PPTX
MvvmQuickCross for Windows Phone
PDF
Learn about Eclipse e4 from Lars Vogel at SF-JUG
PDF
Building React Applications with Redux
PDF
PDF
Bundle deployment at state machine level - Ales Justin, JBoss
PDF
Angular Application Testing
PDF
Anylogic and Java development. How to develop java applicaiton in anylogic
PDF
InterConnect 2016, OpenJPA and EclipseLink Usage Scenarios (PEJ-5303)
PPTX
Angular js 2
PDF
Angular 2 for Java Developers
PDF
[React Native Tutorial] Lecture 7: Navigation - Scene Transition - ListView
PPTX
React.js - The Dawn of Virtual DOM
PPTX
PDF
Introduction of openGL
PPT
Spring - a framework written by developers
PPTX
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter
better-apps-angular-2-day1.pdf and home
Awesome html with ujs, jQuery and coffeescript
Micronaut and the Power of Ahead of Time Compilation - Devnexus 2019
14a-gui.ppt
MvvmQuickCross for Windows Phone
Learn about Eclipse e4 from Lars Vogel at SF-JUG
Building React Applications with Redux
Bundle deployment at state machine level - Ales Justin, JBoss
Angular Application Testing
Anylogic and Java development. How to develop java applicaiton in anylogic
InterConnect 2016, OpenJPA and EclipseLink Usage Scenarios (PEJ-5303)
Angular js 2
Angular 2 for Java Developers
[React Native Tutorial] Lecture 7: Navigation - Scene Transition - ListView
React.js - The Dawn of Virtual DOM
Introduction of openGL
Spring - a framework written by developers
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter
Ad

More from Arun Seetharaman (14)

PDF
Implementing Load Balancing in COM+ Applications
PDF
Advanced Windows DNA Scripting with Visual InterDev
PDF
Implementing DHTML Behavior Script Components
PDF
Creating Data-based Applications Using DHTML
PDF
COM Events for Late-bound Delivery of Information
PDF
Understanding Windows NT Internals - Part 4
PDF
Understanding Windows NT Internals - Part 5
PDF
Understanding Windows NT Internals - Part 3
PDF
Understanding Windows NT Internals - Part 1
PDF
Understanding Windows NT Internals - Part 2
PDF
OLE DB Provider Development - Encapsulating a Service Provider
PDF
OLE DB 2.0 Architecture - Supporting Remote Data Exchange
PDF
Data Structures in Java and Introduction to Collection Framework
PDF
AWT Enhancements in V1.1 - Supporting Richer GUI Development
Implementing Load Balancing in COM+ Applications
Advanced Windows DNA Scripting with Visual InterDev
Implementing DHTML Behavior Script Components
Creating Data-based Applications Using DHTML
COM Events for Late-bound Delivery of Information
Understanding Windows NT Internals - Part 4
Understanding Windows NT Internals - Part 5
Understanding Windows NT Internals - Part 3
Understanding Windows NT Internals - Part 1
Understanding Windows NT Internals - Part 2
OLE DB Provider Development - Encapsulating a Service Provider
OLE DB 2.0 Architecture - Supporting Remote Data Exchange
Data Structures in Java and Introduction to Collection Framework
AWT Enhancements in V1.1 - Supporting Richer GUI Development
Ad

Recently uploaded (20)

PDF
A comparative analysis of optical character recognition models for extracting...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPT
Teaching material agriculture food technology
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Big Data Technologies - Introduction.pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Spectroscopy.pptx food analysis technology
PDF
Electronic commerce courselecture one. Pdf
PDF
Assigned Numbers - 2025 - Bluetooth® Document
DOCX
The AUB Centre for AI in Media Proposal.docx
A comparative analysis of optical character recognition models for extracting...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Dropbox Q2 2025 Financial Results & Investor Presentation
Reach Out and Touch Someone: Haptics and Empathic Computing
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Teaching material agriculture food technology
20250228 LYD VKU AI Blended-Learning.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Empathic Computing: Creating Shared Understanding
Big Data Technologies - Introduction.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
Machine learning based COVID-19 study performance prediction
Spectroscopy.pptx food analysis technology
Electronic commerce courselecture one. Pdf
Assigned Numbers - 2025 - Bluetooth® Document
The AUB Centre for AI in Media Proposal.docx

Java Foundation Classes - Building Portable GUIs

  • 1. JAVA FOUNDATION CLASSES Arun Seetharaman March 10, 1998
  • 2. OVERVIEW • What is Java Foundation Classes? • Building UI using Swing components • MVC-enabled components • Common dialogs
  • 3. JDK 1.0X DEVELOPER FEEDBACK • More built-in components • Too primitive • Needed lighter components • native code is expensive • APIs cleaned • Easily extensible
  • 4. JDK1.1 GOALS • More Components • ScrollPane, PopupMenu • Data Transfer APIs • Cut and Paste operations • Lightweight UI Framework • Java Beans
  • 5. WHAT JFC IS • Comprehensive component suite • Not a replacement for AWT • Look and Feel independent • Application services - pluggable • Support “Accessibility”
  • 6. JFC CONSTITUENTS • JFC consists of five major packages • Swing • PLAF • Drag and Drop • Java 2D • Accessibility
  • 8. 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
  • 9. 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
  • 11. 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
  • 13. 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
  • 14. PROPERTIES OF JCOMPONENT • Client properties • ToolTip support • Border property • Size preferences • KeyStroke handling • Double-buffering • DebugGraphics
  • 15. 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
  • 16. 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 createToolTip method
  • 17. JTOOLTIP - AN EXAMPLE b1.setToolTipText("Click this button to disable the middle button.");
  • 18. 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
  • 19. THE “BORDER” INTERFACE • Interface describing an object capable of rendering a border • Some implemented border styles • EmptyBorder • BevelBorder • TitledBorder • MatteBorder • CompundBorder
  • 21. 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
  • 22. 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
  • 23. 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
  • 24. THE “KEYSTROKE” OBJECT • Can be used with modifiers like alt, shift etc • For virtual keys use the KeyEvent class • All KeyStroke objects are immutable and unique. • KeyStroke objects are cached and accessed using the getKeyStroke() method KeyStroke getKeyStroke(char); KeyStroke getKeyStroke(int, int);
  • 25. 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
  • 26. 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);
  • 27. ICONS AND IMAGEICONS • An icon is a small fixed size picture, typically used to decorate components • ImageIcon is an implementation of the Icon interface that paints Icons • The paintIcon methods paints the content on the specified graphics object ImageIcon bulb1 = loadImageIcon ("images/bulb2.gif","light bulb"); button.setSelectedIcon(bulb2);
  • 28. 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
  • 29. 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 }
  • 31. 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
  • 34. 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 • Views present the data • Controllers are used to interact with the model
  • 35. 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
  • 36. MODEL INTERFACES IN JFC • Some examples of model interfaces • ButtonModel • ComboBoxModel • ListModel • ListSelectionModel • SingleSelectionModel
  • 37. 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
  • 38. 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 ] ); } }
  • 40. RENDERERS • The “Renderer” interface defines the requirements for an object for rendering • Renderers available for component specific rendering • DefaultListRenderer • BasicComboBoxRenderer • TableCellRenderer
  • 41. A CUSTOM RENDERER class MyCellRenderer extends Jlabel implements ListCellRenderer { // Implement getListCellRendererComponent } Jlist list = new Jlist(); list.setCellRenderer(new MyCellRenderer());
  • 43. 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
  • 44. 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
  • 45. 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 ChangeEvent object can be queried for the source of the event
  • 46. 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());
  • 49. 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
  • 50. 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
  • 51. 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
  • 53. 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
  • 54. 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
  • 56. 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 );
  • 57. 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
  • 58. 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();
  • 59. MENUS • Created as first class Swing components • Menu components are: • JMenuBar • JMenu • JMenuItem • JCheckBoxMenuItem • JRadioButtonMenuItem • JPopupMenu
  • 60. 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);
  • 62. 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
  • 63. 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));
  • 65. 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
  • 66. 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);
  • 69. 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
  • 70. 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
  • 71. 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
  • 72. USING MODELS FOR JTABLE • The TableModel interface 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
  • 74. 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) { }
  • 76. 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
  • 77. 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
  • 78. 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
  • 79. 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));
  • 83. 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
  • 85. 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 );
  • 87. TEXTUAL COMPONENTS • Replacement for AWT text components • JTextField • JTextArea • A new generation of components • JPasswordField • JTextPane • JEditorPane
  • 88. 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
  • 89. 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
  • 90. 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
  • 91. 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
  • 92. 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; }
  • 94. 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);
  • 95. 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);
  • 97. MDI APPLICATIONS • Help in frame management • Represent an MDI-like application • JInternalFrame provides the frame • JDesktopPane provides the frame management pane to add frames • The DesktopManager is responsible for platform specific issues
  • 98. 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
  • 99. 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
  • 101. 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);
  • 102. 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();
  • 103. 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
  • 104. 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
  • 106. 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
  • 108. 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);
  • 109. 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
  • 110. 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