Professional Documents
Culture Documents
SL320 - GUI Construction With Java Foundation Classes - Oh - 1198
SL320 - GUI Construction With Java Foundation Classes - Oh - 1198
SL-320
Preface
Course Overview
• Java™ Foundation Classes (JFC) and Swing provide a
mature windowing toolkit.
Printing
Text in Swing
Text Editing
with Swing
Module-by-Module Overview
• Module 1 – Introduction
• Module 2 – Swing Foundations
• Module 3 – Basic Swing Components
• Module 4 – More Swing Foundations
• Module 5 – JDK 1.2 Printing
• Module 6 – Models, Views, and Controllers
• Module 7 – Swing MVC Components
• Module 8 – Using the JTable
Module-by-Module Overview
• Module 9 – Using the JTree
• Module 10 – Text Editing With Swing
• Module 11 – More Swing Features
• Module 12 – Utility Panes
• Module 13 – Program Localization
• Module 14 – Creating Custom Components
• Module 15 – GUI Data Transfer
• Module 16 – Using the GridBagLayout
Course Objectives
• Understand the features of AWT and Swing and make
appropriate design choices for a project
• Use AWT, Swing, and JFC features effectively
• Generate hard copy output under program control
• Understand and use correctly the Models Views and
Controllers design pattern
• Write programs that run appropriately under different
language/locales
• Program drag-and-drop and cut-and-paste operations
Introductions
• Name
• Company affiliation
• Title, function, and job responsibility
• AWT and Swing experience
• Localization experience
• Reasons for enrolling in this course
• Expectations for this course
Icons
• Demonstration
• Reference
• Discussion
• Exercise
Typographical Conventions
• Courier – Commands, files, and directories, on-screen
computer output
Module 1
Introduction
Overview
• Course map
• Relevance
• Objectives
Course Contents
• Most of JFC
• Including most of Swing
• Not – writing a look and feel
• Not – two-dimensional (2D)
• JDK™ 1.2 printing
• Some 2D supporting printing
What Is JFC?
• Blurred boundaries
• Swing
• 2D application programming interface (API) – "fancy"
graphics
• Accessibility
• Drag-and-drop
What Is Swing?
• Enhanced GUI component set
• Pluggable look and feel
• Do-it-yourself look and feel
Printing
• Two "levels"
• AWT – as JDK 1.1
• java.awt.print package
Think Beyond
• Given that Swing is largely backward compatible with
AWT and the delegation event model, do you think you
could write code to use some of these components
already? What changes do you think you might have to
make to an existing AWT 1.1 program to use Swing
components instead?
Module 2
Swing Foundations
Overview
• Course map
• Relevance
• Objectives
Using a RootPaneContainer
• Root pane
• Glass
• Layered
• Menu – optional
• Content
• Use the content pane
• f.getContentPane().add(...)
• f.getContentPane().setLayout(...)
JFrame Essentials
• Similar to java.awt.Frame
• It is a RootPaneContainer
• setDefaultCloseOperation(int operation)
DO_NOTHING_ON_CLOSE
HIDE_ON_CLOSE
DISPOSE_ON_CLOSE
Think Beyond
• Why do you suppose that the Swing top level containers
need a glass pane to catch events?
• Can you guess what consequence might arise if you add
an AWT (non-lightweight) component to a Swing
container that has non-Swing components in a stacking
order on the layered pane?
Module 3
Overview
• Course map
• Relevance
• Objectives
Creating an Icon
• Create an Icon from a graphic file
• new ImageIcon(Image i)
• new ImageIcon(String filename)
• new ImageIcon(URL u)
• Or implement the Icon interface
• paintIcon(Graphics) method
• getIconWidth method
• getIconHeight method
JLabel Example
1 import java.awt.*;
2 import javax.swing.*;
3
4 public class IconTest extends JPanel {
5
6 public IconTest() {
7 TargetIcon target = new TargetIcon();
8
9 setLayout(new GridLayout(4, 1));
10 add(new JLabel(“This is a normal label”));
11 add(new JLabel(“This label has an icon”, target,
12 SwingConstants.LEFT));
13 add(new JLabel(“The next label has only an icon:”));
14 add(new JLabel(target));
15 }
16
17 public static void main(String args[]) {
18 IconTest it = new IconTest();
19 JFrame jf = new JFrame(“Icon on a JLabel”);
20 jf.getContentPane().add(it, BorderLayout.CENTER);
21 jf.setVisible(true);
22 }
23 }
Tooltips
• Short text help message
• Shown when mouse cursor pauses over a component
• setToolTipText(String)
Buttons
• Several variations, like AWT
• Can display icons
• JButton is the basic push button
JButton Example
1 import java.awt.event.*;
2
3 public class CutCopyPaste implements ActionListener {
4 public static final String CUT = "CUT";
5 public static final String COPY = "COPY";
6 public static final String PASTE = "PASTE";
7 String testMode;
8
9 public CutCopyPaste(String name) {
10 testMode = name;
11 }
12
13 public void actionPerformed(ActionEvent ae) {
14 if (testMode != null) {
15 if (ae.getActionCommand() == CUT) {
16 System.out.println("Cut from " + testMode);
17 }
18 else if (ae.getActionCommand() == COPY) {
19 System.out.println("Copy from " + testMode);
20 }
21 else if (ae.getActionCommand() == PASTE) {
22 System.out.println("Paste from " + testMode);
23 }
24 }
25 }
26 }
JButton Example
1 Icon cutIcon = new ImageIcon("cut32x32.gif");
2 Icon copyIcon = new ImageIcon("copy32x32.gif");
3 Icon pasteIcon = new ImageIcon("paste32x32.gif");
4 add(cutButton = new JButton(cutIcon));
5 add(copyButton = new JButton(copyIcon));
6 add(pasteButton = new JButton(pasteIcon));
7 CutCopyPaste ccp = new CutCopyPaste("JButton Demo");
8
9 cutButton.setActionCommand(CutCopyPaste.CUT);
10 copyButton.setActionCommand(CutCopyPaste.COPY);
11 pasteButton.setActionCommand(CutCopyPaste.PASTE);
12
13 cutButton.addActionListener(ccp);
14 copyButton.addActionListener(ccp);
15 pasteButton.addActionListener(ccp);
JCheckBox Example
1 import javax.swing.*;
2 import java.awt.*;
3
4 public class CBox extends JPanel {
5 JCheckBox tb1, tb2, tb3;
6
7 public CBox() {
8 setLayout(new GridLayout(3,1));
9 add(tb1 = new JCheckBox("Left Channel"));
10 add(tb2 = new JCheckBox("Right Channel"));
11 add(tb3 = new JCheckBox("Bass Boost"));
12 }
13
14 public static void main(String args[]) {
15 JFrame jf = new JFrame("Checkbox Test");
16 jf.getContentPane().add(new CBox());
17 jf.pack();
18 jf.setVisible(true);
19 }
20 }
JRadioButton Example
1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4
5 public class RadioTest extends JPanel
6 implements ItemListener {
7
8 private JRadioButton tb1, tb2, tb3;
9 private ButtonGroup bg;
10
11 public RadioTest() {
12 setLayout(new GridLayout(4,1));
13 add(new JLabel("Select the audio output device:"));
14 add(tb1 = new JRadioButton("External Speakers"));
15 add(tb2 = new JRadioButton("Internal Speaker"));
16 add(tb3 = new JRadioButton("Headphones"));
17
18 tb1.addItemListener(this);
19 tb2.addItemListener(this);
20 tb3.addItemListener(this);
JRadioButton Example
21
22 // make it behave like a radio interface
23 bg = new ButtonGroup();
24 bg.add(tb1);
25 bg.add(tb2);
26 bg.add(tb3);
27 }
28
29 public void itemStateChanged(ItemEvent ie) {
30 JRadioButton jtb = (JRadioButton)ie.getItem();
31 // have to check, since "unselecting" also
32 // generates an event
33 if (ie.getStateChange() == ItemEvent.SELECTED) {
34 System.out.println("Current output device is: " +
35 jtb.getText());
36 }
37 }
JRadioButton Example
38
39 public static void main(String args[]) {
40 JFrame jf = new JFrame("RadioTest");
41 RadioTest it = new RadioTest();
42 jf.getContentPane().add(it, BorderLayout.CENTER);
43 jf.pack();
44 jf.setVisible(true);
45 }
46 }
47
JComboBox Example
1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4
5 public class ComboTest extends JPanel implements ItemListener {
6
7 private JComboBox jcb;
8 private String options[] = { "External Speakers",
9 "Internal Speaker", "Headphones" };
10
11 public ComboTest() {
12 TargetIcon target = new TargetIcon();
13
14 setLayout(new GridLayout(2,1));
15 add(new JLabel("Select the audio output device:"));
16 add(jcb = new JComboBox(options));
17 jcb.setEditable(true);
18 jcb.addItemListener(this);
19 }
20
21 public void itemStateChanged(ItemEvent ie) {
22 System.out.println("Item is: " + ie.getItem());
23 System.out.println("Selectable is: "
24 + ie.getItemSelectable());
25 }
26
JComboBox Example
27 public static void main(String args[]) {
28 JFrame jf = new JFrame("Combo Test");
29 ComboTest it = new ComboTest();
30 jf.getContentPane().add(it, BorderLayout.CENTER);
31 jf.pack();
32 jf.setVisible(true);
33 }
34 }
JMenu Example
1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4
5 public class MenuTest extends JPanel
6 implements ActionListener {
7
8 public MenuTest() {
9 setLayout(new BorderLayout());
10 Icon cutIcon = new ImageIcon("cut.gif");
11 Icon copyIcon = new ImageIcon("copy.gif");
12 Icon pasteIcon = new ImageIcon("paste.gif");
13
14 JMenuBar jmb = new JMenuBar();
15 JMenu editMenu = new JMenu("Edit");
16 JMenuItem cutItem = new JMenuItem("Cut", cutIcon);
17 editMenu.add(cutItem);
18 cutItem.addActionListener(this);
19
20 JMenuItem copyItem = new JMenuItem("Copy", copyIcon);
21 editMenu.add(copyItem);
22 copyItem.addActionListener(this);
23
JMenu Example
24 JMenuItem pasteItem = new JMenuItem("Paste", pasteIcon);
25 editMenu.add(pasteItem);
26 pasteItem.addActionListener(this);
27
28 jmb.add(editMenu);
29 add(jmb, BorderLayout.NORTH);
30
31 add(new JLabel("Look at the Edit menu above"),
32 BorderLayout.CENTER);
33 }
34
35 public void actionPerformed(ActionEvent ev) {
36 Object o = ev.getSource();
37 if (o instanceof AbstractButton) {
38 String command = ((AbstractButton)o).getActionCommand();
39 System.out.println("Action " + command + " occurred");
40 }
41 else {
42 System.out.println("Unrecognized action source");
43 }
44 }
45
JMenu Example
46 public static void main(String args[]) {
47 JFrame jf = new JFrame("Menu Test");
48 MenuTest mt = new MenuTest();
49 jf.getContentPane().add(mt, BorderLayout.CENTER);
50 jf.pack();
51 jf.setVisible(true);
52 }
53 }
cutItem.setAccelerator(
KeyStroke.getKeyStroke(88, 0, true)); // X
Think Beyond
• What other components in the Swing set do you think
you could use now?
Module 4
Overview
• Course map
• Relevance
• Objectives
JComponent Accessibility
• Easy
• Set component names
• Legal issues
Actions
• Define things your program can do
• javax.swing.Action
• Extends ActionListener
• Defines actionPerformed(ActionEvent)
• May have text and icon descriptions
• May be enabled or disabled
• Property change events can notify changes in
enabled state
• May be added directly to JMenu or JToolBar
Keystrokes
• Keystrokes describe keyboard input
• KeyStroke objects are shared
• Access them using static getKeystroke(...)
• Construct based on:
• Unicode character or key code
• Modifiers (shift, control, and so forth)
• Key press or release
• Conditions are
• WHEN_FOCUSED
• WHEN_IN_FOCUSED_WINDOW
• WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
Think Beyond
• What types of accessibility interface might your
programs be used with?
• How do actions and keystrokes facilitate reuse of
components?
Module 5
Overview
• Course map
• Relevance
• Objectives
Think Beyond
• What kinds of transformation might be possible using
the AffineTransform class?
• What effects might be achieved by applying this to
screen graphics?
Module 6
Overview
• Course map
• Relevance
• Objectives
MVC Overview
• Model – Abstract programmatic
• View – Visual representation of model
• Controller – Controls model
• Communicating between the parts
• Examples/analogies
MVC Overview
Controller
open
close
setOpenProportion Open
Close
MVC Overview
Interface methods to
physical valve
Controller
open
Physical valve close Open
setOpenProportion
Close
MVC Overview
Model New “openness” View/Controller
notification
open
close
setOpenProportion
Benefits of MVC
• Unrelated aspects are separated
• Better abstraction – easier design
• Simpler programming
• Easier maintenance – loose coupling
• Multiple views and or controllers
• Especially suits interfaces and events
• Combining View and Controller
Event Sourcing
• Choose an Event class
• Use or extend existing classes where possible to
increase interoperability
• Choose a listener type
• For the Event class or for the event’s parent class
Handling Listeners
• Create add/removeXXXListener methods
• Choose unicast or multicast
• Unicast cannot enforce program correctness
Vector listeners;
public void addMyEventListener(
MyEventListener l) {
listeners.addElement(l);
}
public void removeMyEventListener(
MyEventListener l) {
listeners.removeElement(l);
}
}
}
MVC in Swing
• View classes in Swing
• JLabel, JProgressBar
• Controller classes in Swing
• Various buttons, JMenu
• Many are View/Controllers
• Some buttons, JScrollBar, JSlider, text editors
• JList, JTextPane, JTable, and JTree are discussed in
later modules
Think Beyond
• What types of models would you need for components
like lists, trees, tables, and for text editors?
• Would you ever have needs for different models for any
of these components?
Module 7
Overview
• Course map
• Relevance
• Objectives
MVC in Swing
• JList, JComboBox, JTable, JTree, JEditorPane
• Several succeeding modules
• For JList and JTable:
• AbstractXXXModel implements XXXModel
• DefaultXXXModel extends AbstractXXXModel
• View/Controller may be partially modified via:
• ListCellRenderer
• TableCellRenderer, TableCellEditor
• TreeCellRenderer, TreeCellEditor
Using a JList
• View is not scrollable
• Put a JList into a JScrollPane
• Easy to use in simple circumstances
• DefaultListModel and constructors
• Use Object [] or Vector
• ListModel is accessible using the getModel method
Using a ListModel
• ListModel methods are:
add/removeListDataListener(ListDataListener l)
Object getElementAt(int index)
int getSize()
Defining an Action
• Action interface and AbstractAction abstract class
• getValue(String)/putValue(String, Object)
Action.LONG_DESCRIPTION
Action.NAME
Action.SHORT_DESCRIPTION
Action.SMALL_ICON
• setEnabled(boolean)/isEnabled()
• add/removePropertyChangeListener(
PropertyChangeListener)
• actionPerformed(ActionEvent)
Model
Actions
(Inner classes in
Actions, perhaps)
Think Beyond
• Consider how the Action/KeyStroke mechanism can
be used in a variety of situations. What types of control
is it less well suited to, and how could you adapt it to
those situations?
Module 8
Overview
• Course map
• Relevance
• Objectives
JTable Fundamentals
• JTable uses MVC model extensively
• Data model is TableModel
• Columns are modeled too, using TableColumnModel
• Present in a JScrollPane to view column headings
• Single value, single range, multiple range selection
specified by a TableSelectionModel
• Jtable uses TableCellEditor and
TableCellRenderer
JTable
TableModel TableColumnModel
(AbstractTableModel, (DefaultTableColumnModel)
DefaultTableModel)
TableColumn
TableCellRenderer TableCellEditor
(DefaultTableCellRenderer) (DefaultCellEditor)
Using a JTable
• Constructors using DefaultTableModel:
• No data
• Size but no data
• Vector of vectors for data, Vector for headings
• Array of arrays for data, array for headings
• Constructors using explicit TableModel and perhaps:
• Explicit TableColumnModel
• Explicit ListSelectionModel
Using an AbstractTableModel
• Implement:
• public int getRowCount();
• public int getColumnCount();
• public Object getValueAt(int r, int c);
• For an editable table:
• Implement setValueAt(...)
• Call fireTableCellUpdated(int r, int c)
Using a CellRenderer
• Applied column by column or default for whole JTable
• Shared by all cells in a column
• TableColumnModel -> TableColumn
• TableColumn has method setCellRenderer
Writing a CellRenderer
• Interface javax.swing.table.TableCellRenderer
defines:
public Component
getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column)
• Renderer is actually a factory for renderers
• Render value as appropriate to other arguments
• Component may be reused between cells
Using a CellEditor
• Set with parallel mechanism to CellRenderer
• TableColumn has setCellEditor
• TableCellEditor interface extends CellEditor
• DefaultCellEditor can use JTextField,
JCheckBox, JComboBox
Think Beyond
• In what other ways could you use a table? Might you be
able to use it as the basis of a spreadsheet? If so, how
might you go about this?
Module 9
Overview
• Course map
• Relevance
• Objectives
JTree Foundations
• JTree uses MVC model
• Data model is TreeModel
• Single value, contiguous range, multiple range selection
defined in TreeSelectionModel
• TreeCellEditor and TreeCellRenderer interfaces
are used
• Constructor takes a TreeModel to initialize data
Think Beyond
• Could you handle a tree that is of theoretically
unlimited depth? Can you conceive of such a situation
arising?
Module 10
Overview
• Course map
• Relevance
• Objectives
Constructing Styles
• Create a StyleContext
StyleContext sc = new StyleContext();
• Create a "root" style entry
Style plain = sc.addStyle("Plain", null);
• Create "derived" style entries
Style hd1 = sc.addStyle("Head1", plain);
• Define attributes for the styles:
StyleConstants.setFontSize(hd1, 18);
StyleConstants.setBold(hd1, true);
Applying Styles
• To a paragraph:
myJTP.setLogicalStyle(hd1);
• To the current selection or input:
myJTP.setCharacterAttributes(hd1, true);
• True argument specifies "replace" arguments; that is,
delete any preexisting ones
Images in JTextPane
Method 1:
• Create a style and an Icon
• ImageIcon
• Apply Icon to Style
• StyleConstants.setIcon(style, icon)
• jtp.setCharacterAttributes
• Do not setLogicalStyle
Method 2:
• Use insertIcon
Content type might reject icons or components
GUI Construction With Java Foundation Classes Module 10, slide 9 of 12
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services
Think Beyond
• What is the role of a model in the text editing
components you have just studied?
• What features do these models need?
• Is one model sufficient for all text documents?
Module 11
Overview
• Course map
• Relevance
• Objectives
Using Borders
• JComponent has method setBorder(Border)
• Border instances may be shared
• Use BorderFactory.getXXXBorder(...)
• CompoundBorder allows nesting
• EmptyBorder replaces setInsets
Border Appearance
Focus Handling
• Swing has its own focus manager
• Use AWT focus manager in mixed displays
(Raw AWT components do not support Swing focus)
• Call disableSwingFocusManager on
class javax.swing.FocusManager
• Install new FocusManager with
FocusManager.setCurrentManager(fm)
Focus Traversal
• By default, focus traversal follows X,Y location
• Can impose specific traverse order with
aJComponent.setNextFocusableComponent.
• Can subclass DefaultFocusManager, or a
JComponent can handle focus within itself.
• JComponent sends keys to FocusManager first:
public void processKeyEvent(
Component focusedComponent,
KeyEvent anEvent)
Think Beyond
• What circumstances might warrant creating your own
look and feel?
Module 12
Utility Panes
Overview
• Course map
• Relevance
• Objectives
Utility Panes
• JFileChooser
• JTabbedPane
• JScrollPane
• JSplitPane
The JFileChooser
The JTabbedPane
JTabbedPane Example
1 import java.awt.*;
2 import java.util.*;
3 import java.awt.event.*;
4 import javax.swing.*;
5
6 public class TabTest extends JPanel
7 implements ItemListener {
8
9 private JTabbedPane jtp;
10 private JCheckBox netCheckBox;
11 private JPanel systemPane = new JPanel();
12 private JPanel audioPane = new JPanel();
13 private JPanel internetPane = new JPanel();
14
15 public TabTest() {
16 setLayout(new BorderLayout());
17 jtp = new JTabbedPane();
18
19 netCheckBox = new JCheckBox(
20 "Internet Connection", true);
21 netCheckBox.addItemListener(this);
22 systemPane.add(netCheckBox);
23
24 audioPane.add(new JLabel("Audio configuration"));
25 internetPane.add(new JLabel("Internet configuration"));
26
JTabbedPane Example
27 jtp.addTab("System", systemPane);
28 jtp.addTab("Audio", audioPane);
29 jtp.addTab("Internet", internetPane);
30
31 add(jtp, BorderLayout.CENTER);
32 }
33
34 public static void main(String args[]) {
35 JFrame jf = new JFrame("Tabbed Pane Test");
36 TabTest tt = new TabTest();
37 jf.getContentPane().add(tt, BorderLayout.CENTER);
38 jf.pack();
39 jf.setVisible(true);
40 }
41
42 public void itemStateChanged(ItemEvent ie) {
43 int index = jtp.indexOfComponent(internetPane);
44 if (index != -1) {
45 jtp.setEnabledAt(index, netCheckBox.isSelected());
46 }
47 jtp.repaint();
48 }
49 }
JSplitPane Example
1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4
5 public class SplitTest extends JPanel {
6
7 public SplitTest() {
8 JSplitPane sp = new JSplitPane(
9 JSplitPane.HORIZONTAL_SPLIT,
10 new JTextArea("This is one text area"),
11 new JTextArea("This is another text area"));
12 setLayout(new BorderLayout());
13 add(sp, BorderLayout.CENTER);
14 }
15
16 public static void main(String args[]) {
17 JFrame jf = new JFrame("SplitPane Test");
18 SplitTest st = new SplitTest();
19 jf.getContentPane().add(st, BorderLayout.CENTER);
20 jf.pack();
21 jf.setVisible(true);
22 }
23 }
Column Header
Corners
Viewport
Row Header
Vertical Scrollbar
Horizontal Scrollbar
Controlling Scrolling
jsp.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jsp.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
The JOptionPane
Think Beyond
• How would you create displays that have more than
two split regions?
Module 13
Program Localization
Overview
• Course map
• Relevance
• Objectives
Localizing Code
• Customize for language, company standards, product
versions
• Properties can specify runtime configuration
• Command line
java -Dname=value Class
• Property file
Properties.load(inputStream)
• System properties
System.getProperties();
• Read properties with getProperty, and
getBoolean, getInteger, getFont,
getColor...
GUI Construction With Java Foundation Classes Module 13, slide 4 of 21
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services
Locale
• Language (ISO-639 codes: en, fr, es...)
• Country (ISO-3166 codes: US, CA, GB...)
• Variant (POSIX, MAC, WIN...)
• Locale.getDefault
ResourceBundle
• A container class that groups objects for a locale
Using a ResourceBundle
• getObject(key)
• getString(key)
• getStringArray(key)
String myText = theBundle.getString("myText");
Creating a ResourceBundle
• Subclass and implement two methods
• Object handleGetObject(String key)
• Enumeration getKeys()
• Use a Hashtable to store Object instances
• Or use ListResourceBundle directly
ListResourceBundle
• Extends ResourceBundle
• Implements handleGetObject
• Provide Object [][] getContents()
class MyResource_fr extends ListResourceBundle {
public Object[][] getContents() {
return contents;
}
static final Object[][] contents = {
{"count", "3"}, {"Yes", "Oui"},
{"No", "Non"}, {"Exit", "Quitter"}
};
}
Formatting Messages
• Substitute runtime values into a template
• Template should be localizable
• Use java.text.MessageFormat
String t = bundle.getString("formatstring");
Date Formatting
• Time/date takes modifiers which may be one of
• short
• medium
• long
• full
• Explicit pattern such as:
yyyy.MM.dd G 'at' hh:mm:ss z
• Documentation: java.text.SimpleDateFormat
Numeric Formatting
• Number modifiers are:
• currency
• percent
• integer
• Explicit pattern such as:
#,##0.00
• Documentation: java.text.DecimalFormat
Choice Formatting
• ChoiceFormat converts a double value to a String
• According to limits—specified as double
double [] staffIDs = { 0.0, 1.0, 2.0, 3.0, 4.0 };
String [] staffNames = {
"Fred", "Jim", "Sheila", "Andy", "Chris"
};
Nested Formatting
• Formats may be nested
• Create a MessageFormat
• Specify formats to use with setFormats
• Position of {} in format string determines which format
• Index in {} determines which argument
• A ChoiceFormat uses arguments from the outer format
• Other formats use nested arguments
Think Beyond
• What proportion of your programs relates to creating
text messages?
• How much of that can you now move outside of your
source code?
• Does this have any implications for maintenance?
Module 14
Overview
• Course map
• Relevance
• Objectives
Component Requirements
• Appearance (look)
• Via paint methods
• Response to UI actions (feel)
• Via events
• Source events to other listeners
Lightweight Components
• Rendering handled in Java programming language
code
• Events handled in Java code
• Hence entirely under control of Java code
• Subclassing/overriding works
• Components may be non-rectangular
• contains methods
• paint(Graphics) method
• setClip(Shape) method
Event Handling
• React to GUI activity by getting events
• Use processXXXEvent methods
• Do not listen to yourself
• Select appropriate events with enableEvents
Example
80 class XYEvent extends AWTEvent {
81 private Point p;
82
83 public XYEvent(Object source, Point p) {
84 super(source, 0);
85 this.p = p;
86 }
87
88 public Point getPoint() {
89 return p;
90 }
91 }
Example
80 interface XYListener {
81 public void pointSet(XYEvent e);
82 }
Example
10 public XYInput() {
11 enableEvents(AWTEvent.MOUSE_EVENT_MASK);
12 setPreferredSize(new Dimension(256, 256));
13 }
Think Beyond
• What sort of custom components can you think of that
you might be called upon to create?
Module 15
Overview
• Course map
• Relevance
• Objectives
Data Types
• Drag or copy can pick up many data types
• Text, Unicode text, file, URL, image, class...
• Transfers use java.awt.datatransfer.DataFlavor
• Uses MIME to describe data types
• text/plain; charset=unicode
• application/x-java-serialized-object
• Source of a copy might offer multiple types
• In preference order
• Destination of a copy might accept multiple types
Copy to Clipboard
• Get the system clipboard
• Encapsulate data to copy in a Transferable
• StringSelection is a Transferable for text
• Set the clipboard contents and claim ownership of it
• ClipboardOwner interface has callback method:
lostOwnership(Clipboard, Transferable)
Copy to Clipboard
1 import java.awt.datatransfer.*;
3 Clipboard c = getToolkit().getSystemClipboard();
4 // Create a Transferable to put into the clipboard
5 // StringSelection is simplest, and pre-defined
6 StringSelection ss = new StringSelection(text.getText());
7 c.setContents(ss, ss);
Implementing Transferable
• Object getTransferData(DataFlavor)
throws UnsupportedFlavorException
• DataFlavor [] getTransferDataFlavors()
• boolean isDataFlavorSupported(DataFlavor)
Drag-and-Drop
• Essentially similar to Cut/Paste – DataFlavor
• More "automatic"
• Drag-and-drop gestures predefined
• Special behavior during drag, such as cursor change
• Might need callbacks to monitor progress
• X Windows has multiple drag/drop schemes
• Multiple drop actions (copy/move/link)
• Source, destination, and user requested actions
DropTarget and
DropTargetListener
• DropTarget associates a Component and
DropTargetListener
• DropTargetListener gets progress calls particularly
void drop(DropTargetDropEvent)
• Call acceptDrop or rejectDrop
• DropTargetDragEvent and DropTargetDropEvent
• Carry the action type—getDropAction
• Carry the Transferable—getTransferable
• Call dropComplete when drop ends successfully
GUI Construction With Java Foundation Classes Module 15, slide 12 of 19
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services
DropTarget and
DropTargetListener
1 import java.awt.*;
2 import java.awt.dnd.*;
3 import java.awt.datatransfer.*;
4 import java.io.*;
5
6 public class DroppableList extends List
7 implements DropTargetListener{
8
9 public DroppableList() {
10 // this is both target component and listener
11 new DropTarget (this, this);
12 }
13
14 private void validateDrag(DropTargetDragEvent e) {
15 int action = e.getDropAction();
16 if (action == DnDConstants.ACTION_MOVE) {
17 e.acceptDrag(action);
18 }
19 else {
20 e.rejectDrag();
21 }
22 }
23
24 public void dragEnter(DropTargetDragEvent e) {
25 validateDrag(e);
26 }
27
28 public void dragOver(DropTargetDragEvent e) {
29 validateDrag(e);
30 }
31
32 public void dropActionChanged(DropTargetDragEvent e) {
33 validateDrag(e);
34 }
35
DragSource, DragSourceListener,
and DragGestureListener
• ds = DragSource.getDefaultDragSource()
• ds.getDefaultDragGestureRecognizer(
comp, act, gl)
• Callback method for recognizer is
dragGestureRecognized
• Call ds.startDrag(event, cursor,
transferable, dsl)
• Or other overloading method
• DragSourceListener callbacks track progress of drag
Think Beyond
• What reusable components can you create for use with
GUI data transfer?
Module 16
Overview
• Course map
• Relevance
• Objectives
Layout Managers
• Position and size components in a Container
• Lay out GUIs according to a policy
• Absolute coordinates can be used but are platform
dependent
• Basic layout managers:
• FlowLayout
• GridLayout
• BorderLayout
• Somewhat limited
The GridBagLayout
• Divides region into rows and columns
• Components may be sized to fit width, height, both, or
neither of their "region"
• "Region" is one or more contiguous rows and one or
more contiguous columns
The GridBagLayout
• Row/column count determined by cell usage
• Row/column basic size determined by contents
The GridBagLayout
• Use of "spare" space determined by weight
• Region is one or more contiguous rows and columns
• Components may fit width and/or height of the region
The GridBagLayout
• Components are located within region by "anchor"
• Fill can make anchor ineffective
Extra column
0 1 2 3 4
Loose component
2 3 4 5
9
6 7
10
11
12
1 0 0 5 1
2 0 1 1 1
3 1 1 1 1
4 2 1 1 1
5 3 1 2 1
6 0 2 1 4
7 1 2 3 4
8 4 2 1 1
9 4 3 1 1
10 4 4 1 1
11 4 5 1 1
12 0 6 5 1
0 1
1 2 3 4 5
2 8
3 9
7
6
4 10
5 11
6 12
Example
Example
38 static class GridBagAdder {
39 // OK to reuse this as we overwrite all elements every time
40 // Note that this is not threadsafe however!
41 static GridBagConstraints cons = new GridBagConstraints();
42 public static void add(Container cont, Component comp, int x, int y,
43 int width, int height, int weightx, int weighty, int fill, int anchor) {
44 cons.gridx = x;
45 cons.gridy = y;
46 cons.gridwidth = width;
47 cons.gridheight = height;
48 cons.weightx = weightx;
49 cons.weighty = weighty;
50 cons.fill = fill;
51 cons.anchor = anchor;
52 cont.add(comp, cons);
53 }
54 }
55 }
Think Beyond
• Are there any layout effects that you cannot handle
using the layout managers you now understand?
Appendix A
Overview
• Relevance
• Objectives
Event Classes
• java.awt.event.* lists many GUI events, such as:
• ActionEvent
• MouseEvent
• Subclasses of java.util.EventObject
• Utility methods, such as:
• getSource() - java.util.EventObject
• getActionCommand() - ActionEvent
• getKeyChar() - KeyEvent
• getModifiers() - InputEvent / MouseEvent
Appendix B
Printing
Overview
• Relevance
• Objectives
AWT Printing
• java.awt.Toolkit gives access to system facilities
• A java.awt.Component has a reference to the
Toolkit
• The Component must have been visible
• From the Toolkit, get a PrintJob
• From a PrintJob, get a Graphics
• Each Graphics represents a page
• dispose() the Graphics to spool the page
• end() the PrintJob to complete
Example
Component c;
Toolkit tk = c.getToolkit();
PrintJob pj = getPrintJob(f, title, props);
Graphics g = pj.getGraphics();
while (more_pages_to_print) {
g.drawLine(...);
g.drawString(...);
c.paint(g);
Appendix C
Overview
• Relevance
• Objectives
Fonts
• Multiple fonts can be installed
• Toolkit.getFontlist or
• GraphicsEnvironment.getAvailableFontFamilyNames
• Create font aliases
• Install new fonts
• Fonts might not cover all Unicode characters
• Fonts might not be in Unicode order
Font Configuration
• font.properties file
• In jre/lib directory under JDK or JRE installation
• font.properties.<locale>
• Adding an alias
• alias.timesroman=serif
• Installing a new font
• Platform specific
• Look at Solaris environment and Microsoft Windows
Appendix D
Undo/Redo Handling
Overview
• Relevance
• Objectives
Undo/Redo Features
• Document issues UndoableEditEvent objects.
• Payload is UndoableEdit.
• UndoableEdit has
• undo()
• redo()
• getPresentationName()
• and others - die(), canUndo(), canRedo()...
• javax.swing.undo.UndoManager collects and
groups UndoableEditEvent objects.
Introduction ............................................................................................................................1-1
Overview .................................................................................................................................................. 1-2
Course Contents ...................................................................................................................................... 1-3
What Is JFC? ............................................................................................................................................. 1-4
What Is Swing? ........................................................................................................................................ 1-5
Printing ..................................................................................................................................................... 1-6
Why Not Use AWT? ............................................................................................................................... 1-7
What Should a Replacement for AWT Offer? ..................................................................................... 1-8
Costs of Using JFC/Swing ................................................................................................................... 1-10
Exercise: Investigate Swing Component Set ..................................................................................... 1-11
Check Your Progress ............................................................................................................................ 1-12
Think Beyond ........................................................................................................................................ 1-13