Download as pdf or txt
Download as pdf or txt
You are on page 1of 307

Sun Educational Services

GUI Construction With Java


Foundation Classes

SL-320

Sun Educational Services

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Preface

About This Course

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Course Overview
• Java™ Foundation Classes (JFC) and Swing provide a
mature windowing toolkit.

• Java Development Kit (JDK™) fully supports


internationalization/localization.

• Course provides skills to:

• Develop graphical user interfaces (GUIs)


• Print and localize programs

GUI Construction With Java Foundation Classes Preface, slide 2 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services
Course Map
Swing Introduction
Introduction Swing Foundations

Basic Swing More Swing


Components Foundations

Printing

JDK 1.2 Printing

Models Views and Controllers


Models, Views, Swing MVC
and Controllers Components

Using the JTable Using the JTree

Text in Swing

Text Editing
with Swing

More About Swing

More Swing Utility Panes


Features

Further User Interface Issues


Program Creating Custom
Localization Components

GUI Data Using the


Transfer GridBagLayout

GUI Construction With Java Foundation Classes Preface, slide 3 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Preface, slide 4 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Preface, slide 5 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Preface, slide 6 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Topics Not Covered


• The Java programming language
• Object-oriented concepts
• Writing a look-and-feel implementation

GUI Construction With Java Foundation Classes Preface, slide 7 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

How Prepared Are You?


• Can you write Java technology programs?
• Can you make basic use of the Abstract Windowing
Toolkit (AWT)?

GUI Construction With Java Foundation Classes Preface, slide 8 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Preface, slide 9 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

How to Use the Course Materials


• Course map
• Relevance
• Overhead image
• Lecture
• Exercise
• Check your progress
• Think beyond

GUI Construction With Java Foundation Classes Preface, slide 10 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Icons
• Demonstration

• Reference

• Discussion

• Exercise

GUI Construction With Java Foundation Classes Preface, slide 11 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Typographical Conventions
• Courier – Commands, files, and directories, on-screen
computer output

• Courier bold – Input you type

• Courier italic – Variables and command-line


placeholders

• Palatino italics – Book titles, new words or terms, words


that are emphasized

GUI Construction With Java Foundation Classes Preface, slide 12 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Module 1

Introduction

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

GUI Construction With Java Foundation Classes Module 1, slide 2 of 13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 1, slide 3 of 13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

What Is JFC?
• Blurred boundaries
• Swing
• 2D application programming interface (API) – "fancy"
graphics
• Accessibility
• Drag-and-drop

GUI Construction With Java Foundation Classes Module 1, slide 4 of 13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

What Is Swing?
• Enhanced GUI component set
• Pluggable look and feel
• Do-it-yourself look and feel

GUI Construction With Java Foundation Classes Module 1, slide 5 of 13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Printing
• Two "levels"
• AWT – as JDK 1.1
• java.awt.print package

GUI Construction With Java Foundation Classes Module 1, slide 6 of 13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Why Not Use AWT?


• AWT is simple but limited
• Missing components
• Hard to customize appearance/behavior
• Hard to extend

GUI Construction With Java Foundation Classes Module 1, slide 7 of 13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

What Should a Replacement for AWT


Offer?
• Rich component set
• Ease of extension
• Ease of modification of behavior
• Control over appearance
• Backward compatibility
• Accessibility

GUI Construction With Java Foundation Classes Module 1, slide 8 of 13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

What Should a Replacement for AWT


Offer?
• Performance issues
• 1.1 event model
• Double buffering (lightweight components)
• Class downloading times
• Platform independence
• 100% Pure Java™
• JavaBeans™ component model compliance
• Drag-and-drop

GUI Construction With Java Foundation Classes Module 1, slide 9 of 13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Costs of Using JFC/Swing


• In 1.1, classes are not core to the JDK
• Need download time
• Double buffering is good
• But native components are fastest

GUI Construction With Java Foundation Classes Module 1, slide 10 of 13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise: Investigate Swing


Component Set
• Objective: View and manipulate all the GUI
components in the Swing set.
• Preparation: Locate the JDK installation directory on
your system.
• Tasks:
• Select directory jfc/SwingSet.
• Run java SwingSet
• Exercise summary

GUI Construction With Java Foundation Classes Module 1, slide 11 of 13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Check Your Progress


• Outline the features of the Java Foundation Classes

• Describe the key features of Swing


• Select appropriate components from the Swing set for
any given UI requirement
• Compare the facilities of Swing and the Java
Foundation Classes with other GUI kits

GUI Construction With Java Foundation Classes Module 1, slide 12 of 13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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?

GUI Construction With Java Foundation Classes Module 1, slide 13 of 13


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Module 2

Swing Foundations

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Course map

• Relevance

• Objectives

GUI Construction With Java Foundation Classes Module 2, slide 2 of 11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Comparing Swing and AWT


Components
• Swing components include: JButton, JCheckBox,
JFrame, JLabel, JList, JMenu, JPanel, JScrollBar,
JScrollPane, JTextArea, JTextField
• Use JDK 1.1 Delegation Event model
• Do not mix AWT and Swing

GUI Construction With Java Foundation Classes Module 2, slide 3 of 11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Converting From AWT to Swing


• Adding "J" is typically enough, except:
• Note JCheckBox versus Checkbox
• JRadioButton / ButtonGroup
• Use JScrollPane
• setJMenuBar

GUI Construction With Java Foundation Classes Module 2, slide 4 of 11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

New Components in Swing


• Simple components:
• JComboBox, JInternalFrame, JPasswordField,
JProgressBar, JRadioButton, JSeparator,
JSlider, JToggleButton, JToolBar, JToolTip
• Complex components covered later in this course

GUI Construction With Java Foundation Classes Module 2, slide 5 of 11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Top Level Swing Containers


• JFrame, JWindow, and JDialog
• JApplet
• RootPaneContainer

GUI Construction With Java Foundation Classes Module 2, slide 6 of 11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Using a RootPaneContainer
• Root pane
• Glass
• Layered
• Menu – optional
• Content
• Use the content pane
• f.getContentPane().add(...)
• f.getContentPane().setLayout(...)

GUI Construction With Java Foundation Classes Module 2, slide 7 of 11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

JFrame Essentials
• Similar to java.awt.Frame
• It is a RootPaneContainer
• setDefaultCloseOperation(int operation)
DO_NOTHING_ON_CLOSE
HIDE_ON_CLOSE
DISPOSE_ON_CLOSE

GUI Construction With Java Foundation Classes Module 2, slide 8 of 11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise: Converting an AWT GUI to


Swing
• Objective: Convert sample user interfaces from AWT to
Swing.
• Preparation: Run sample solutions in solutions
directory.
• Tasks:
• Read the file README in the labs directory
• Convert three files ConvertIF1.java,
ConvertIF2.java, and ConvertIF3.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 2, slide 9 of 11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Check Your Progress


• Name the Swing components that are direct substitutes
for the AWT components and modify an AWT user
interface to use these Swing components
• Recognize basic Swing components, and make use of
them in interfaces
• Understand the multiple panes of the JFrame, and write
code that correctly uses the content pane for holding
other components
• Understand that AWT and Swing components should
generally not be used together in the same user interface

GUI Construction With Java Foundation Classes Module 2, slide 10 of 11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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?

GUI Construction With Java Foundation Classes Module 2, slide 11 of 11


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Module 3

Basic Swing Components

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

GUI Construction With Java Foundation Classes Module 3, slide 2 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The Icon Interface


• Swing components support graphics
• Icon is used to describe the graphic
• Icon might be a graphic file or calculated image

GUI Construction With Java Foundation Classes Module 3, slide 3 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 3, slide 4 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Implementing the Icon Interface


1 import javax.swing.*;
2 import java.awt.*;
3
4 public class TargetIcon implements Icon {
5
6 public void paintIcon(Component c, Graphics g, int x, int y) {
7 Color old = g.getColor();
8 g.setColor(Color.red);
9 g.fillOval(0, 0, 16, 16);
10 g.setColor(Color.white);
11 g.fillOval(3, 3, 10, 10);
12 g.setColor(Color.red);
13 g.fillOval(6, 6, 4, 4);
14 g.setColor(old);
15 }
16
17 public int getIconWidth() { return 16; }
18 public int getIconHeight() { return 16; }
19 }

GUI Construction With Java Foundation Classes Module 3, slide 5 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The JLabel Class


• Specify text, Icon, or both
• Control alignment between the text and the icon
• SwingConstants defines tags for alignment
specification

GUI Construction With Java Foundation Classes Module 3, slide 6 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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 }

GUI Construction With Java Foundation Classes Module 3, slide 7 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Tooltips
• Short text help message
• Shown when mouse cursor pauses over a component
• setToolTipText(String)

GUI Construction With Java Foundation Classes Module 3, slide 8 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Buttons
• Several variations, like AWT
• Can display icons
• JButton is the basic push button

GUI Construction With Java Foundation Classes Module 3, slide 9 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The JButton Class


• Simple constructor for text label
• A graphic may be defined by an Icon
• new JButton(String, Icon)
• JButton generates an ActionEvent when clicked
• Specify the action command String with
setActionCommand

GUI Construction With Java Foundation Classes Module 3, slide 10 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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 }

GUI Construction With Java Foundation Classes Module 3, slide 11 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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);

GUI Construction With Java Foundation Classes Module 3, slide 12 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The JCheckBox Class


• Name differs from AWT Checkbox
• Accepts icons

GUI Construction With Java Foundation Classes Module 3, slide 13 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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 }

GUI Construction With Java Foundation Classes Module 3, slide 14 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The JRadioButton Class


• JRadioButton class has toggle behavior
• ButtonGroup applies mutual exclusion behavior
• ButtonGroup can manage any Swing button

GUI Construction With Java Foundation Classes Module 3, slide 15 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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);

GUI Construction With Java Foundation Classes Module 3, slide 16 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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 }

GUI Construction With Java Foundation Classes Module 3, slide 17 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 3, slide 18 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The JComboBox Class


• AWT only offered Choice
• Non-editable JComboBox is similar to Choice
• Editable JComboBox allows typing of new entries
• addItem and removeItem methods control list contents
programmatically

GUI Construction With Java Foundation Classes Module 3, slide 19 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 3, slide 20 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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 }

GUI Construction With Java Foundation Classes Module 3, slide 21 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The JMenu Class


• Supports icons
• Issues events like buttons
• JButton and JMenuItem both extend AbstractButton

GUI Construction With Java Foundation Classes Module 3, slide 22 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 3, slide 23 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 3, slide 24 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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 }

GUI Construction With Java Foundation Classes Module 3, slide 25 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Additional Features of JMenu


• Keyboard accelerators
JMenuItem cutItem = new JMenuItem("Cut",cutIcon);

cutItem.setAccelerator(
KeyStroke.getKeyStroke(88, 0, true)); // X

• JMenu is a Component, so may be positioned under


layout manager control
• The top of a window is the normal location

GUI Construction With Java Foundation Classes Module 3, slide 26 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise: Using Basic Swing


Components
• Objective: Experiment with JComboBox, ToolTip,
JLabel, JRadioButton, and ButtonGroup
• Preparation: Run the program Translate in the
solutions directory
• Tasks:
• Read the file README in the labs directory
• Edit the file Tranlsate.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 3, slide 27 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Check Your Progress


• Write code to use icons in Swing components
• Implement the Icon interface
• Write code to use the following classes:
• JLabel
• JButton
• JCheckBox
• JRadioButton
• ToolTips
• JComboBox
• JMenu

GUI Construction With Java Foundation Classes Module 3, slide 28 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Think Beyond
• What other components in the Swing set do you think
you could use now?

GUI Construction With Java Foundation Classes Module 3, slide 29 of 29


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Module 4

More Swing Foundations

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

GUI Construction With Java Foundation Classes Module 4, slide 2 of 10


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

JComponent Accessibility
• Easy
• Set component names
• Legal issues

GUI Construction With Java Foundation Classes Module 4, slide 3 of 10


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 4, slide 4 of 10


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 4, slide 5 of 10


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Attaching an Action to a KeyStroke


• JComponent has:
public void registerKeyboardAction(
ActionListener anAction,
String aCommand,
KeyStroke aKeyStroke,
int aCondition)

• Conditions are
• WHEN_FOCUSED
• WHEN_IN_FOCUSED_WINDOW
• WHEN_ANCESTOR_OF_FOCUSED_COMPONENT

GUI Construction With Java Foundation Classes Module 4, slide 6 of 10


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise 1: Investigate Action Objects


• Objective: Use predefined Action objects
• Preparation: Run the program Actions in the
solutions directory
• Tasks
• Read the file README.1 in the labs directory
• Edit the file Actions.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 4, slide 7 of 10


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise 2: Investigate Keystroke


Handling
• Objective: Attach Action objects to keystrokes
• Preparation: Run the program Keystroke in the
solutions directory
• Tasks
• Read the file README in the labs directory
• Edit the file Keystroke.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 4, slide 8 of 10


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Check Your Progress


• Appreciate the need for accessibility technologies, and
create accessible user interfaces using Swing
components
• Write code to implement keystroke handling so that a
Swing component reacts to keyboard control in a
required way
• Understand Action objects, and write code to use pre-
defined Action objects in Swing components

GUI Construction With Java Foundation Classes Module 4, slide 9 of 10


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Think Beyond
• What types of accessibility interface might your
programs be used with?
• How do actions and keystrokes facilitate reuse of
components?

GUI Construction With Java Foundation Classes Module 4, slide 10 of 10


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Module 5

JDK 1.2 Printing

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

GUI Construction With Java Foundation Classes Module 5, slide 2 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Two Modes of Printing


• AWT printing (JDK 1.1)
• Low resolution
• 2D Printing (JFC/JDK1.2)
• High-precision (2D) printing
• Print "books"
• Control paper size, orientation, and so forth

GUI Construction With Java Foundation Classes Module 5, slide 3 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

JDK 1.2 Printing


• Graphics2D
• High resolution, floating point coordinates
• Transformations
• Package java.awt.print
• PrinterJob class
• PrinterJob.getPrinterJob
• Prints Printable or Pageable

GUI Construction With Java Foundation Classes Module 5, slide 4 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Implementing the Printable


Interface
1 public class PrintableTextPane extends JTextPane
2 implements Printable {
3
4 public int print(Graphics g, PageFormat form, int page) {
5 if (page == 0) {
6 if (g instanceof Graphics2D) {
7 AffineTransform tr = new AffineTransform(form.getMatrix());
8 tr.translate(form.getImageableX(), form.getImageableY());
9 ((Graphics2D)g).transform(tr);
10 }
11 super.paint(g);
12 return PAGE_EXISTS;
13 }
14 else {
15 return NO_SUCH_PAGE;
16 }
17 }
18 }

GUI Construction With Java Foundation Classes Module 5, slide 5 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Using the PrinterJob


1 PrinterJob pj = PrinterJob.getPrinterJob();
2 if (pj.printDialog()) {
3 PageFormat pf = pj.defaultPage();
4 pf = pj.pageDialog(pf);
5
6 pj.setPrintable(ta);
7
8 try {
9 pj.print();
10 System.out.println("Print completed");
11 }
12 catch (PrinterException e) {
13 e.printStackTrace(System.err);
14 System.out.println("Print failed");
15 }
16 }
17 else {
18 System.out.println("Print cancelled");
19 }

GUI Construction With Java Foundation Classes Module 5, slide 6 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The Printable and Pageable


Interfaces
• Printable interface
• One or more pages, all the same format
• print returns NO_SUCH_PAGE or PAGE_EXISTS
• Pageable interface
• Collection of pages (Printable), with own formats
• Book class

GUI Construction With Java Foundation Classes Module 5, slide 7 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Example of Using Pageable and Book


1 PrinterJob pj = PrinterJob.getPrinterJob();
2 if (pj.printDialog()) {
3 PageFormat pf = pj.defaultPage();
4 pf = pj.pageDialog(pf);
5
6 Book b = new Book();
7 b.append(ta, pf);
8 pj.setPageable(b);
9
10 try {
11 pj.print();
12 System.out.println("Print completed");
13 }
14 catch (PrinterException e) {
15 e.printStackTrace(System.err);
16 System.out.println("Print failed");
17 }
18 }
19 else {
20 System.out.println("Print cancelled");
21 }
22 }

GUI Construction With Java Foundation Classes Module 5, slide 8 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The PageFormat Class


• A PageFormat object defines:
• Page size
• Margins
• Orientation
• Paper
• The pageDialog method of PrinterJob allows user
configuration of a PageFormat.

GUI Construction With Java Foundation Classes Module 5, slide 9 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise: Using JDK 1.2 Printing


• Objective: Experiment with the JDK 1.2 printing
features
• Preparation: Run the program PrintOut in the
solutions directory
• Tasks
• Read the file README in the labs directory
• Edit the file PrintOut.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 5, slide 10 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Check Your Progress


• Write code to obtain a PrinterJob, present the user
with a configuration dialog, and recognize cancellation
• Implement the Printable interface to support printing
• Use the Book class with Printable objects to support
printing
• Use the pageDialog method to enable the user to
configure a PageFormat for a PrinterJob
• Use the methods of the PageFormat class to obtain size
and orientation information about a page
• Use AffineTransform objects to position printed
output correctly on a page
GUI Construction With Java Foundation Classes Module 5, slide 11 of 12
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Think Beyond
• What kinds of transformation might be possible using
the AffineTransform class?
• What effects might be achieved by applying this to
screen graphics?

GUI Construction With Java Foundation Classes Module 5, slide 12 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Module 6

Models, Views, and Controllers

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

GUI Construction With Java Foundation Classes Module 6, slide 2 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

MVC Overview
• Model – Abstract programmatic
• View – Visual representation of model
• Controller – Controls model
• Communicating between the parts
• Examples/analogies

GUI Construction With Java Foundation Classes Module 6, slide 3 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

MVC Overview

Model New “openness” View


notification

float openness = 0.6

Controller
open
close
setOpenProportion Open

Close

GUI Construction With Java Foundation Classes Module 6, slide 4 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

MVC Overview

Model New “openness” View


notification

Interface methods to
physical valve

Controller

open
Physical valve close Open
setOpenProportion

Close

GUI Construction With Java Foundation Classes Module 6, slide 5 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

MVC Overview
Model New “openness” View/Controller
notification

float openness = 0.6

open
close
setOpenProportion

GUI Construction With Java Foundation Classes Module 6, slide 6 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 6, slide 7 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Implementing MVC in JDK 1.1


• Events
• Observer /Observable
• Custom notification
• Controller interface

GUI Construction With Java Foundation Classes Module 6, slide 8 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 6, slide 9 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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);
}

GUI Construction With Java Foundation Classes Module 6, slide 10 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Dispatching the Event


• Create the Event object
• With a reference to the originating component (this)
• Call the handler method of each registered listener
private void issueEvent(Info i) {
Event ev = new MyEvent(this, i);
Vector cl = (Vector)(listeners.clone());
Enumeration e = cl.elements();
while (e.hasMoreElements()) {
((MyEventListener)e.nextElement()).
doMyEvent(ev);

}
}

GUI Construction With Java Foundation Classes Module 6, slide 11 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 6, slide 12 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise: MVC Demonstration Using


the 1.1 Event Model
• Objective: Implement the MVC model using interfaces
and the 1.1 Event Delegation model.
• Preparation: Run the programs SimpleMVC and
MultiMVC in the solutions directory.
• Tasks:
• Read the file README in the labs directory
• Edit the files ButtonController.java,
MultiMVC.java, ProgressView.java,
TextView.java, ValveModelImpl.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 6, slide 13 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Check Your Progress


• Describe the separation of appropriate parts of
applications into models, views, and controllers
• Select suitable classes for implementing models, views,
and controllers in either 1.1 AWT or Swing
• Write code to implement each part of an MVC system,
using either 1.1 AWT or Swing
• Write code to implement the necessary communications
between the model, view, and controller elements of an
MVC system

GUI Construction With Java Foundation Classes Module 6, slide 14 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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?

GUI Construction With Java Foundation Classes Module 6, slide 15 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Module 7

Swing MVC Components

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

GUI Construction With Java Foundation Classes Module 7, slide 2 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 7, slide 3 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 7, slide 4 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Using a ListModel
• ListModel methods are:
add/removeListDataListener(ListDataListener l)
Object getElementAt(int index)
int getSize()

• AbstractListModel adds fireXXX convenience


methods
• DefaultListModel implements methods of
java.util.Vector
• Thereby providing a controller interface

GUI Construction With Java Foundation Classes Module 7, slide 5 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise 1: Sharing a Model With MVC


• Objective: Demonstrate the MVC model in Swing by
creating two JLists that share a data model
• Preparation: Run the program TwoLists in the
solutions directory
• Tasks:
• Read the file README.1 in the labs directory
• Edit the files TwoLists.java and
ListController.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 7, slide 6 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Actions, KeyStrokes and Models


• Models can have ad hoc controller interface
• DefaultListModel (same methods as Vector)
• Consistent approach would be better
• Could use a well-known interface, such as
java.util.List
• Actions are a valuable controller interface pattern
• KeyStrokes provide a compatible keyboard controller

GUI Construction With Java Foundation Classes Module 7, slide 7 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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)

GUI Construction With Java Foundation Classes Module 7, slide 8 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services
Action and Model
Interactions
Controller

Model

Actions
(Inner classes in
Actions, perhaps)

1) getActions Model data


method returns an (private)
array of Action
int x
objects. void actionPerformed float y
2) The Action Object z
objects are added
to the controller.

3) Each Action has


access to the data in
the model and Action [ ] getActions()
implements a useful
actionPerformed
method operating
on that data.

GUI Construction With Java Foundation Classes Module 7, slide 9 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise 2: Defining Action Classes


• Objective: Implement the Action interface to create a
ListModel that provides Action objects
• Preparation: Run the program ListActions in the
solutions directory
• Tasks
• Read the file README.2 in the labs directory
• Edit the files ActionListController.java,
ActionListModel.java, and ListActions.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 7, slide 10 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Check Your Progress


• Describe the use of MVC in the Swing classes
• Write code to use the JList class initialized with data in
either a Vector or an Object array
• Write code to use the ListModel interface,
AbstractListModel, or DefaultListModel classes
• Write code to obtain the ListModel in use by a JList
• Write code to extend AbstractListModel,
implementing the list model itself and providing a
controller interface
• Describe the significance of Action and KeyStroke
classes to the model and controller roles of MVC
• Implement the Action interface as a means of creating
a controller interface on a model

GUI Construction With Java Foundation Classes Module 7, slide 11 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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?

GUI Construction With Java Foundation Classes Module 7, slide 12 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Module 8

Using the JTable

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

GUI Construction With Java Foundation Classes Module 8, slide 2 of 18


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 8, slide 3 of 18


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Essential JTable Support Classes

JTable

TableModel TableColumnModel
(AbstractTableModel, (DefaultTableColumnModel)
DefaultTableModel)

TableColumn

TableCellRenderer TableCellEditor
(DefaultTableCellRenderer) (DefaultCellEditor)

GUI Construction With Java Foundation Classes Module 8, slide 4 of 18


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The TableModel interface


• getColumnClass(int columnIndex)
• getRowCount(), getColumnCount()
• getColumnName(int columnIndex)
• getValueAt(int rowIndex, int columnIndex)
• setValueAt(Object v, int row, int column)
• isCellEditable(int row, int column)
• add/removeTableModelListener

GUI Construction With Java Foundation Classes Module 8, slide 5 of 18


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The TableColumnModel Interface and


TableColumn Class
• DefaultTableColumnModel used normally
• Supports changing displayed order of columns
• Maintains information about columns
• TableColumn objects define:
• TableCellRenderer for cells and header
• TableCellEditor
• Size information

GUI Construction With Java Foundation Classes Module 8, slide 6 of 18


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 8, slide 7 of 18


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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)

GUI Construction With Java Foundation Classes Module 8, slide 8 of 18


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Controlling Table Appearance


• If getColumnType returns Boolean the column uses a
JCheckBox
• Control display using a CellRenderer
• Control editing using a CellEditor

GUI Construction With Java Foundation Classes Module 8, slide 9 of 18


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 8, slide 10 of 18


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 8, slide 11 of 18


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Using a CellEditor
• Set with parallel mechanism to CellRenderer
• TableColumn has setCellEditor
• TableCellEditor interface extends CellEditor
• DefaultCellEditor can use JTextField,
JCheckBox, JComboBox

GUI Construction With Java Foundation Classes Module 8, slide 12 of 18


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise 1: Using JTable and


TableModel
• Objective: Become familiar with the use of JTable, and
the use of the TableModel getColumnClass method
• Preparation: Run the program MyTable in the
solutions.1 directory
• Tasks:
• Read the file README in the labs.1 directory
• Edit the files MyTable.java and
MyTableModel.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 8, slide 13 of 18


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise 2: Controlling Editability


With the TableModel
• Objective: Become familiar with the use of the table
model to make particular cells of a table non-editable
• Preparation: Run the program MyTable in the
solutions.2 directory
• Tasks:
• Read the file README in the labs.2 directory
• Edit the files MyTable.java and
MyTableModel.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 8, slide 14 of 18


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise 3: Using a Cell Renderer


• Objective: Become familiar with the use of a
CellRenderer in a table
• Preparation: Run the program MyTable in the
solutions.3 directory
• Tasks:
• Read the file README in the labs.3 directory
• Edit the files MyTable.java, MyTableModel.java
and ColorRenderer.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 8, slide 15 of 18


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise 4: Using a Cell Editor


• Objective: Become familiar with the use of a cell editor
in a table
• Preparation: Run the program MyTable in the
solutions.4 directory
• Tasks:
• Read the file README in the labs.4 directory
• Edit the files MyTable.java, MyTableModel.java
and ColorRenderer.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 8, slide 16 of 18


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Check Your Progress


• Write code to present a simple JTable based on
constant initialization data
• Write an implementation of TableModel to control Cell
editability, column data types and headings
• Write code to use non-default editor and renderer
classes in a JTable, or specific column of a JTable

GUI Construction With Java Foundation Classes Module 8, slide 17 of 18


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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?

GUI Construction With Java Foundation Classes Module 8, slide 18 of 18


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Module 9

Using the JTree

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

GUI Construction With Java Foundation Classes Module 9, slide 2 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 9, slide 3 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The DefaultTreeModel and


DefaultMutableTreeNode
• Construct DefaultMutableTreeNode objects with:
• Node user object (defines display name)
• boolean allowsChildren
• Use add method to build the tree of nodes
• Then construct DefaultTreeModel with root node as
argument

GUI Construction With Java Foundation Classes Module 9, slide 4 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Using DefaultTreeModel and


DefaultMutableTreeNode
1 import java.awt.*;
2 import javax.swing.*;
3 import javax.swing.tree.*;
4
5 public class TreeTest {
6 private static Object [] nodeNames = { "one", "two", "three",
7 "four", "five", "six", "seven", new Integer(8),
8 new Integer(9), new Float(10) };
9 private static boolean [] leaf = { false, true, true, false,
10 true, true, false, true, true, true };
11
12 public static void main(String args[]) {
13 JFrame jf = new JFrame("Tree Test");
14 DefaultMutableTreeNode [] nodes = new DefaultMutableTreeNode[10];
15 for (int i = 0; i < nodes.length; i++) {
16 nodes[i] = new DefaultMutableTreeNode(nodeNames[i], !leaf[i]);
17 }

GUI Construction With Java Foundation Classes Module 9, slide 5 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Using DefaultTreeModel and


DefaultMutableTreeNode
18 nodes[0].add(nodes[1]);
19 nodes[0].add(nodes[2]);
20 nodes[0].add(nodes[3]);
21 nodes[0].add(nodes[6]);
22 nodes[0].add(nodes[9]);
23 nodes[3].add(nodes[4]);
24 nodes[3].add(nodes[5]);
25 nodes[6].add(nodes[7]);
26 nodes[6].add(nodes[8]);
27
28 JTree jt = new JTree(nodes[0]);
29 jf.getContentPane().add(jt, BorderLayout.CENTER);
30 jf.pack();
31 jf.setVisible(true);
32 }
33 }

GUI Construction With Java Foundation Classes Module 9, slide 6 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Using DefaultTreeModel and


DefaultMutableTreeNode

GUI Construction With Java Foundation Classes Module 9, slide 7 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The TreeModel Interface


• add/remove TreeModelListener(...)
• Object getChild(Object parent, int index)
• int getChildCount(Object parent)
• int getIndexOfChild(Object parent, Object
child)
• Object getRoot()
• boolean isLeaf(Object node)
• valueForPathChanged(TreePath path, Object
newValue)

GUI Construction With Java Foundation Classes Module 9, slide 8 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

More About JTree


• DefaultTreeModel
• asksAllowsChildren
• Editors and renderers function as in JTable
• Apply to whole tree
• Hence JTree has methods setCellRenderer and
setCellEditor
• getTreeCellEditorComponent and
getTreeCellRendererComponent are similar to
table equivalents, but arguments to suit a tree

GUI Construction With Java Foundation Classes Module 9, slide 9 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise: Using JTree and


DefaultTreeModel
• Objective: Use DefaultMutableTreeNode to construct
a DefaultTreeModel, then use that tree model to
construct a JTree
• Preparation: Run the program CompTree in the
solutions directory
• Tasks:
• Read the file README in the labs directory
• Edit the file CompTree.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 9, slide 10 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Check Your Progress


• Write code to present a JTree based on simple constant
initialization data
• Write code to use a non-default editor or renderer with
a JTree

GUI Construction With Java Foundation Classes Module 9, slide 11 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Think Beyond
• Could you handle a tree that is of theoretically
unlimited depth? Can you conceive of such a situation
arising?

GUI Construction With Java Foundation Classes Module 9, slide 12 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Module 10

Text Editing With Swing

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

GUI Construction With Java Foundation Classes Module 10, slide 2 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Basic Text Editing


Migration support:
• JTextComponent
• JTextField
• JPasswordField (instead of JTextField)
• JTextArea
• JScrollPane

GUI Construction With Java Foundation Classes Module 10, slide 3 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Using the JTextPane


• Text with
• Attributes
• Styles
• Pictures
• Components
• Content awareness inherited from JEditorPane
• Hypertext markup language (HTML) and rich text
format (RTF) built in
• Extensible – see next module

GUI Construction With Java Foundation Classes Module 10, slide 4 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Styles and JTextPane


• JTextPane uses a DefaultStyledDocument by default
• StyleContext
• Hierarchical collection of styles
• Style objects are named MutableAttributeSets
• StyleConstants is a convenience class:
• Static setXxxx(mutableAttribSet, value)
methods
• For Bold, Italic, Underline, and so forth
• Styles may be applied to paragraphs or character
runs
GUI Construction With Java Foundation Classes Module 10, slide 5 of 12
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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);

GUI Construction With Java Foundation Classes Module 10, slide 6 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 10, slide 7 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Placing Components in JTextPane


Method 1:
• Create a Style and a JComponent
• Apply Component to Style with
StyleConstants.setComponent(style, jcomp)
• Apply Style to Character with
jtp.setCharacterAttributes
• Do not setLogicalStyle
Method 2:
• Use insertComponent
Use a Component only once
GUI Construction With Java Foundation Classes Module 10, slide 8 of 12
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

Exercise: Using JTextPane and Styles


• Objective: Become familiar with the use of JTextPane
and Styles
• Preparation: Run the program Editor in the solutions
directory
• Tasks:
• Read the file README in the labs directory
• Edit the files Editor.java, FontPane.java,
StylePane.java, and StyleView.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 10, slide 10 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Check Your Progress


• Use the JTextField, JPasswordField, and JTextArea
in place of the text components of AWT
• Write code to implement styles in the JTextPane/
DefaultStyledDocument combination and apply
styles to both character runs and paragraphs
• Write code to incorporate components and images into
a document with the JTextPane

GUI Construction With Java Foundation Classes Module 10, slide 11 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?

GUI Construction With Java Foundation Classes Module 10, slide 12 of 12


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Module 11

More Swing Features

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

GUI Construction With Java Foundation Classes Module 11, slide 2 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Swing Is Not Thread Safe


• Difficult to implement efficiently
• Custom components would also need thread safety
• Few developers are skilled with threads
• Prone to deadlock
• Easy to do without

GUI Construction With Java Foundation Classes Module 11, slide 3 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Swing Is Not Thread Safe


• GUI processing should be done in AWT thread
• There are some exceptions:
• Can (usually) construct GUI in main or init
• Some methods are documented as thread safe
• repaint, revalidate, invalidate
• add/removeXXXListener

GUI Construction With Java Foundation Classes Module 11, slide 4 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Calling Methods From Other Threads


• Why would you use another thread?
• Time-consuming processing in AWT thread is bad
• Repetitive/timing operations
• Input/output (I/O) handling

GUI Construction With Java Foundation Classes Module 11, slide 5 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Communicating Between Threads


• Two ways to request AWT thread to perform work
• SwingUtilities.invokeLater(Runnable)
• SwingUtilities.invokeAndWait(Runnable)
• javax.swing.Timer class
• Can add ActionListener objects
• actionPerformed called in the AWT thread
• Can abandon overrun ticks

GUI Construction With Java Foundation Classes Module 11, slide 6 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Swing Component Appearance


• Simple control
• Colors
• Fonts
• Borders
• Full control
• Pluggable look and feel
• Custom look and feel

GUI Construction With Java Foundation Classes Module 11, slide 7 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Using Borders
• JComponent has method setBorder(Border)
• Border instances may be shared
• Use BorderFactory.getXXXBorder(...)
• CompoundBorder allows nesting
• EmptyBorder replaces setInsets

GUI Construction With Java Foundation Classes Module 11, slide 8 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Border Appearance

GUI Construction With Java Foundation Classes Module 11, slide 9 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Controlling Look and Feel


• Default look and feel is "Metal"
• Platform’s own look and feel may also be supported
• Microsoft Windows
• Motif
• Macintosh
• Copyright might restrict look and feel availability

GUI Construction With Java Foundation Classes Module 11, slide 10 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Controlling Look and Feel


• Install an explicit look and feel with:
UIManager.setLookAndFeel(
"javax.swing.plaf.metal.MetalLookAndFeel");

• May change look and feel of running program


• May even create own look and feel (not covered in this
class)

GUI Construction With Java Foundation Classes Module 11, slide 11 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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)

GUI Construction With Java Foundation Classes Module 11, slide 12 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Controlling Default Focus


• To make a component default focus target:
• Add first to Container
• Or subclass DefaultFocusManager, overriding
getFirstComponent(Container)
• Or subclass JComponent, overriding
getComponents

GUI Construction With Java Foundation Classes Module 11, slide 13 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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)

GUI Construction With Java Foundation Classes Module 11, slide 14 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise 1: Observe Default Focus


Traversal
• Objective: Observe the default focus behavior in Swing
layouts
• Task:
• Run the program Focus1 in the solutions directory
and notice how the focus is transferred
• Exercise summary

GUI Construction With Java Foundation Classes Module 11, slide 15 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise 2: Control Focus Traversal


• Objective: Investigate the use of
setNextFocusableComponent to control tab focus
order
• Preparation: Run the program Focus2 in the solutions
directory
• Tasks:
• Read the file README.2 in the labs directory
• Edit the file Focus2.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 11, slide 16 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise 3: Control Default Focus


Position
• Objective: Investigate the significance of component-
adding order to the default focus position
• Preparation: Run the program Focus3 in the solutions
directory
• Tasks:
• Read the file README.3 in the labs directory
• Edit the file Focus3.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 11, slide 17 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise 4: Install a Look and Feel


• Objective: Control the look and feel of a running
program
• Preparation: Run the program LnF in the solutions
directory
• Tasks:
• Read the file README.4 in the labs directory
• Edit the file LnF.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 11, slide 18 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Check Your Progress


• Write code that adheres to the single-threading rule of
Swing
• Describe the reasons for Swing’s single-threading rule
• List the exceptions to Swing’s single-threading rule
• Write code that uses Border objects to modify the
appearance of Swing components, including using
nested borders

GUI Construction With Java Foundation Classes Module 11, slide 19 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Check Your Progress


• Write programs that allow the users or system
administrators to install a look and feel according to
their preference
• Write code to control the default focus, and keyboard
focus traversal order, of a GUI

GUI Construction With Java Foundation Classes Module 11, slide 20 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Think Beyond
• What circumstances might warrant creating your own
look and feel?

GUI Construction With Java Foundation Classes Module 11, slide 21 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Module 12

Utility Panes

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

GUI Construction With Java Foundation Classes Module 12, slide 2 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Utility Panes
• JFileChooser
• JTabbedPane
• JScrollPane
• JSplitPane

GUI Construction With Java Foundation Classes Module 12, slide 3 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The JFileChooser

GUI Construction With Java Foundation Classes Module 12, slide 4 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services
JFileChooser Example
1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4
5 public class ChooserTest extends JPanel
6 implements ActionListener {
7
8 private JButton goButton;
9 private JLabel display;
10 private JFileChooser jfc = new JFileChooser();
11
12 public ChooserTest() {
13 goButton = new JButton(“Pick File”);
14 add(goButton);
15 display = new JLabel(“Chosen file will be shown here”);
16 add(display);
17
18 goButton.addActionListener(this);
19 }
20
21 public void actionPerformed(ActionEvent ae) {
22 int status = jfc.showOpenDialog(this);
23 if (status == 0) {
24 display.setText(“You chose: “
25 + jfc.getSelectedFile().getName());
26 }
27 else {
28 display.setText(“File chooser was cancelled”);
29 }
30 }
31
32 public static void main(String args[]) {
33 JFrame jf = new JFrame(“FileChooser test”);
34 ChooserTest it = new ChooserTest();
35 jf.getContentPane().add(it, BorderLayout.CENTER);
36 jf.pack();
37 jf.setVisible(true);
38 }
39 }

GUI Construction With Java Foundation Classes Module 12, slide 5 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Using the JFileChooser


• Controlling messages
• showOpenDialog
• showSaveDialog
• showDialog(parent, approveText)
• Filtering
• FileFilter class
• boolean accept(File) method
• String getDescription method

GUI Construction With Java Foundation Classes Module 12, slide 6 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The JTabbedPane

GUI Construction With Java Foundation Classes Module 12, slide 7 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Using the JTabbedPane


• Construct with optional orientation for tabs
• addTab(String label, Component pane)
• indexOfComponent(Component)
• indexOfTab(Icon)
• indexOfTab(String)
• insertTab(String, Icon, Component, String,
int)
• getComponentAt(int)

GUI Construction With Java Foundation Classes Module 12, slide 8 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 12, slide 9 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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 }

GUI Construction With Java Foundation Classes Module 12, slide 10 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Using the JSplitPane

GUI Construction With Java Foundation Classes Module 12, slide 11 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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 }

GUI Construction With Java Foundation Classes Module 12, slide 12 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Controlling the Divider


• JComponent.setMinimumSize

Property Name get() set() Description


dividerLocation ✔ ✔ The current position (in pixels relative to the
upper-left corner of the pane) of the divider
dividerSize ✔ ✔ The size of the divider in pixels (width or height
depending on the orientation of the split)
lastDividerLocation ✔ The last position of the divider after a resize
occurred
continuousLayout ✔ (is) ✔ boolean value that determines whether or not
the pane tries to repaint both components continu-
ously as the user slides the divider
minimumDividerLocation ✔ The minimum size of the “left” component
maximumDividerLocation ✔ The maximum size of the “left” component (usu-
ally dictated by the minimum size of the “right”
component)
orientation ✔ ✔ The vertical or horizontal orientation of the split
pane (use the SwingConstants values to change or
compare)

GUI Construction With Java Foundation Classes Module 12, slide 13 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Using the JScrollPane

Column Header

Corners

Viewport

Row Header
Vertical Scrollbar

Horizontal Scrollbar

GUI Construction With Java Foundation Classes Module 12, slide 14 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Assigning Components to Regions of a


JScrollPane
1 JTextArea jta = new JTextArea();
2 jta.setMinimumSize(new Dimension(200,150));
3 JScrollPane jsp = new JScrollPane(jta);
4 JLabel fileNameLabel = new JLabel("", JLabel.CENTER);
5 jsp.setColumnHeaderView(fileNameLabel);
6 jsp.setCorner(JScrollPane.UPPER_RIGHT_CORNER, upButton);
7 jsp.setCorner(JScrollPane.LOWER_RIGHT_CORNER, downButton);

GUI Construction With Java Foundation Classes Module 12, slide 15 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Controlling Scrolling
jsp.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

jsp.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

GUI Construction With Java Foundation Classes Module 12, slide 16 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The JOptionPane

GUI Construction With Java Foundation Classes Module 12, slide 17 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Using the JOptionPane


• Option pane provides dialog utility methods
JOptionPane.showMessageDialog(null, "Alert",
"Warning", JOptionPane.WARNING_MESSAGE)

• Message type is one of


• ERROR_MESSAGE
• INFORMATION_MESSAGE
• WARNING_MESSAGE
• QUESTION_MESSAGE
• PLAIN_MESSAGE

GUI Construction With Java Foundation Classes Module 12, slide 18 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Using the JOptionPane


• Additional methods support questions
int response = JOptionPane.showConfirmDialog(
null,
"What next?",
"Choose your destiny",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE
);

• Return indicates chosen option


• Can specify option buttons explicitly

GUI Construction With Java Foundation Classes Module 12, slide 19 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise: Using the Utility Panes


• Objective: Use the JTabbedPane, JScrollPane,
JSplitPane, and JOptionPane classes
• Preparation: Run the program MultiEx in the
solutions directory
• Tasks:
• Read the file README in the labs directory
• Edit the file MultiEx.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 12, slide 20 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Check Your Progress


• Create programs that utilize the new Swing containers
JTabbedPane, JSplitPane, and JScrollPane
• Create a program that can build a JDirectoryPane to
display the files in a directory
• Create programs that use the JOptionPane to display
dialog boxes

GUI Construction With Java Foundation Classes Module 12, slide 21 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Think Beyond
• How would you create displays that have more than
two split regions?

GUI Construction With Java Foundation Classes Module 12, slide 22 of 22


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Module 13

Program Localization

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

GUI Construction With Java Foundation Classes Module 13, slide 2 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Unicode and Other Character Sets


• JDK and JVM use Unicode
• Source
• Runtime
• Conversion is needed between platform conventions
• Reading/writing to local host
new InputStreamReader(inStream)
new OutputStreamWriter(outStream)
• Over network to remote hosts
new InputStreamReader(inStream, "8859_1")
new OutputStreamWriter(outStream, "8859_1")

GUI Construction With Java Foundation Classes Module 13, slide 3 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 13, slide 5 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

ResourceBundle
• A container class that groups objects for a locale

• Access an Object by key (String)

• To get a bundle for the current locale:


• Use ResourceBundle.getBundle(rootName)
• Give fully qualified root classname
• Target classnames should have locale extensions—
example: Support_en_GB.class
• Provide option to request specific locale

GUI Construction With Java Foundation Classes Module 13, slide 6 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Using a ResourceBundle
• getObject(key)
• getString(key)
• getStringArray(key)
String myText = theBundle.getString("myText");

GUI Construction With Java Foundation Classes Module 13, slide 7 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 13, slide 8 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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"}
};
}

GUI Construction With Java Foundation Classes Module 13, slide 9 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Formatting Messages
• Substitute runtime values into a template
• Template should be localizable
• Use java.text.MessageFormat

GUI Construction With Java Foundation Classes Module 13, slide 10 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Basic Use of MessageFormat


• Build array of argument values (as Object instances)
• Use {...} as substitution placeholder in template
Object[] values = {
"red", new Integer(99), new Date()
};

String t ="At {2,time} on {2,date}, " +


"there were {1,number,integer} {0} ballons";

String output = MessageFormat.format(t, values);

GUI Construction With Java Foundation Classes Module 13, slide 11 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Localizing Formatted Messages


• Use ResourceBundles
• For argument strings
• For format strings
Object[] values = {
bundle.getString("colorname"),
new Integer(99), new Date()
};

String t = bundle.getString("formatstring");

• Order of use of arguments is not important


• Arguments may even be unused

GUI Construction With Java Foundation Classes Module 13, slide 12 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

More Control of Message Formatting


• Braces specify one of:
• time
• date
• number
• choice

GUI Construction With Java Foundation Classes Module 13, slide 13 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 13, slide 14 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Numeric Formatting
• Number modifiers are:
• currency
• percent
• integer
• Explicit pattern such as:
#,##0.00
• Documentation: java.text.DecimalFormat

GUI Construction With Java Foundation Classes Module 13, slide 15 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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"
};

ChoiceFormat staffFormat = new


ChoiceFormat(staffIDs, staffNames);

String output = staffFormat.format(2);

GUI Construction With Java Foundation Classes Module 13, slide 16 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 13, slide 17 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services
Nested Formatting
1 import java.text.*;
2
3 public class NestedForms {
4 public static void main(String args[]) {
5
6 double [] plurals = { 0.0, 1.0, 2.0 };
7 String [] pluralStrings = {"there are no files",
8 "there is one file",
9 "there are {1} files"};
10 ChoiceFormat plural =
11 new ChoiceFormat(plurals, pluralStrings);
12
13 MessageFormat dirMsg =
14 new MessageFormat("In directory {0} {1}");
15 Format [] dirForms = { null, plural };
16 dirMsg.setFormats(dirForms);
17 Object [] dirArgs = { "tools", null };
18 for (int fileCount = 0; fileCount < 4; fileCount++) {
19 dirArgs[1] = new Integer(fileCount);
20 System.out.println(dirMsg.format(dirArgs));
21 }
22
23 MessageFormat collected =
24 new MessageFormat("My friend {0} tells me {1}");
25 Format [] collectedForms = { null, dirMsg };
26 collected.setFormats(collectedForms);
27 Object [] collectedArgs = { "Ruth", dirArgs };
28 System.out.println(collected.format(collectedArgs));
29 }
30 }

GUI Construction With Java Foundation Classes Module 13, slide 18 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise: Program Localization


• Objective: Become familiar with resource bundle usage
and message formatting
• Preparation: Run the program Messages in the
solutions directory
• Tasks:
• Read the file README in the labs directory.
• Edit the file Messages.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 13, slide 19 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Check Your Progress


• Write code to convert between a platform character
encoding standard and Unicode
• Write code that reads properties from the invoking
command line
• Write programs that use the ResourceBundle and
Locale mechanisms to implement behavior that is
appropriate to the language and customs where the
program is being run
• Write code that uses the features of the java.text
package to format output messages appropriately for
where the program is being run

GUI Construction With Java Foundation Classes Module 13, slide 20 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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?

GUI Construction With Java Foundation Classes Module 13, slide 21 of 21


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Module 14

Creating Custom Components

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

GUI Construction With Java Foundation Classes Module 14, slide 2 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Component Requirements
• Appearance (look)
• Via paint methods
• Response to UI actions (feel)
• Via events
• Source events to other listeners

GUI Construction With Java Foundation Classes Module 14, slide 3 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Creating a New Component


• Any or all of look and feel may be inherited from parent
• AWT components, heavyweight or "with-peers" are
hard to modify
• Lightweight components can be created in JDK 1.1 and
Swing
• Pluggable look and feel difficult in "from-scratch"
component

GUI Construction With Java Foundation Classes Module 14, slide 4 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 14, slide 5 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Event Handling
• React to GUI activity by getting events
• Use processXXXEvent methods
• Do not listen to yourself
• Select appropriate events with enableEvents

GUI Construction With Java Foundation Classes Module 14, slide 6 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Event Sourcing Choices


• Unicast or multicast?
• New or existing Event type?
• Event listener type?
• Provide addXXXListener /removeXXXListener

GUI Construction With Java Foundation Classes Module 14, slide 7 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Add/Remove Listener Methods


Vector list; // registered event listeners

public void addMyEventListener(


MyEventListener l) {
listeners.addElement(l);
}
public void removeMyEventListener(
MyEventListener l) {
listeners.removeElement(l);
}

GUI Construction With Java Foundation Classes Module 14, slide 8 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Event Firing Convenience Method


private void issueEvent(Info i) {
MyEvent ev = new MyEvent(this, i);
Vector v = (Vector)(list.clone());
Enumeration e = v.elements();
while (e.hasMoreElements()) {
((MyEventListener)(e.nextElement())).
doMyEvent(ev);
}
}

GUI Construction With Java Foundation Classes Module 14, slide 9 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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 }

• Define an Event class

GUI Construction With Java Foundation Classes Module 14, slide 10 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Example
80 interface XYListener {
81 public void pointSet(XYEvent e);
82 }

50 public void addXYListener(XYListener l) {


51 listeners.addElement(l);
52 }
53
54 public void removeXYListener(XYListener l) {
55 listeners.removeElement(l);
56 }

• Prepare for listeners

GUI Construction With Java Foundation Classes Module 14, slide 11 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Example
10 public XYInput() {
11 enableEvents(AWTEvent.MOUSE_EVENT_MASK);
12 setPreferredSize(new Dimension(256, 256));
13 }

24 protected void processMouseEvent(MouseEvent ev) {


25 if (ev.getID() == MouseEvent.MOUSE_CLICKED) {
26 clickedAt = ev.getPoint();
27 XYEvent e = new XYEvent(this, clickedAt);
28 sendEvent(e);
29 repaint();
30 }
31 super.processMouseEvent(ev);
32 }

• Handle mouse input

GUI Construction With Java Foundation Classes Module 14, slide 12 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise: Create a New Component


• Objective: Create a non-rectangular component that
responds to both keyboard and mouse input
• Preparation: Run the program XYKeyInput in the
solutions directory
• Tasks:
• Read the file README in the solutions directory
• Edit the file XYKeyInput.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 14, slide 13 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Check Your Progress


• Create new lightweight components by subclassing
java.awt.Component or Swing components
• Write code to handle GUI events so that a specified
“feel” is achieved
• Write code to define appropriate events and event
listeners to notify other objects of behavior in a new
component
• Write code to register and deregister event listeners,
and to notify listeners when behavior occurs in a new
component

GUI Construction With Java Foundation Classes Module 14, slide 14 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Think Beyond
• What sort of custom components can you think of that
you might be called upon to create?

GUI Construction With Java Foundation Classes Module 14, slide 15 of 15


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Module 15

GUI Data Transfer

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

GUI Construction With Java Foundation Classes Module 15, slide 2 of 19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 15, slide 3 of 19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The System Clipboard


• Supports cut-and-paste
• Concept shared by most platforms
• JDK hides variations
• Program your own cut/copy/paste initiators

GUI Construction With Java Foundation Classes Module 15, slide 4 of 19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Paste From Clipboard


• Get the Toolkit (from a realized Component instance)
• Get the system Clipboard from the Toolkit
• Get the current clipboard contents as a Transferable
• Check data flavors supported by this Transferable
• If one is suitable, extract the data in that form and use it

GUI Construction With Java Foundation Classes Module 15, slide 5 of 19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Paste From Clipboard


1 import java.awt.datatransfer.*;
2 // "this" is a Component instance
3 Clipboard c = getToolkit().getSystemClipboard();
4 Transferable t = c.getContents(this);
5 DataFlavor [] flavors =
t.getTransferDataFlavors();
6 for (int i = 0; i < flavors.length; i++) {
7 try {
8 Object o = t.getTransferData(flavors[i]);
9 System.out.println("Flavor " + i + " gives " + o.getClass().getName());
10 if (o instanceof Something_I_Can_Handle) {
11 // then handle it... for example:
12 // if (o instanceof String) { setText((String)o); }
13 break; // once handled, lower preference flavors may be ignored
14 }
15 }
16 catch (UnsupportedFlavorException ex) {
17 ex.printStackTrace();
18 }
19 }

GUI Construction With Java Foundation Classes Module 15, slide 6 of 19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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)

GUI Construction With Java Foundation Classes Module 15, slide 7 of 19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Copy to Clipboard
1 import java.awt.datatransfer.*;

2 class... implements ClipboardOwner {

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);

8 public void lostOwnership(Clipboard c, Transferable t) {


9 System.out.println("Lost clipboard");
10 }

GUI Construction With Java Foundation Classes Module 15, slide 8 of 19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Implementing Transferable
• Object getTransferData(DataFlavor)
throws UnsupportedFlavorException
• DataFlavor [] getTransferDataFlavors()
• boolean isDataFlavorSupported(DataFlavor)

GUI Construction With Java Foundation Classes Module 15, slide 9 of 19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise 1: Implementing Cut-and-


Paste
• Objective: Implement cut-and-paste with text data
• Preparation: Run the program CutPaste in the
solutions directory
• Tasks:
• Read the file README.1 in the labs directory
• Edit the file CutPaste.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 15, slide 10 of 19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 15, slide 11 of 19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 15, slide 13 of 19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services
DropTarget and
DropTargetListener
36 public void dragExit(DropTargetEvent e) { }
37
38 public void drop(DropTargetDropEvent e) {
39 int action = e.getDropAction();
40 Transferable tr = e.getTransferable();
41 if ((action == DnDConstants.ACTION_MOVE) ||
42 tr.isDataFlavorSupported(DataFlavor.stringFlavor)) {
43 e.acceptDrop(action);
44 try {
45 String s = (String)tr.getTransferData (
46 DataFlavor.stringFlavor);
47 add (s);
48 e.dropComplete(true);
49 }
50 catch (Exception ex) {
51 e.rejectDrop();
52 }
53 }
54 else {
55 e.rejectDrop();
56 }
57 }
58 }

GUI Construction With Java Foundation Classes Module 15, slide 14 of 19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 15, slide 15 of 19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services
DragSource,
DragSourceListener, and
DragGestureListener
1 import java.awt.*;
2 import java.awt.dnd.*;
3 import java.awt.datatransfer.*;
4
5 public class DraggableLabel extends Label
6 implements DragSourceListener, DragGestureListener {
7
8 DragSource dragSource;
9 public DraggableLabel(String s) {
10 super(s);
11 dragSource = new DragSource();
12 dragSource.createDefaultDragGestureRecognizer(
13 this, DnDConstants.ACTION_MOVE, this);
14 }
15
16 public void dragGestureRecognized(DragGestureEvent e) {
17 StringSelection text = new StringSelection(getText());
18 // specify null for the DragSourceListener if you are
19 // not interested in the callbacks.
20 dragSource.startDrag(
21 e, DragSource.DefaultCopyDrop, text, this);
22 }
23
24 // if no callbacks needed, you do not have to implement
25 // DragSourceListener at all.
26 public void dragDropEnd(DragSourceDropEvent e) { }
27 public void dragEnter(DragSourceDragEvent e) { }
28 public void dragExit(DragSourceEvent e) { }
29 public void dragOver(DragSourceDragEvent e) { }
30 public void dropActionChanged(DragSourceDragEvent e) { }
31 }

GUI Construction With Java Foundation Classes Module 15, slide 16 of 19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise 2: Implementing Drag-and-


Drop
• Objective: Implement drag-and-drop with text data
• Preparation: Run the program DragDrop in the
solutions directory
• Tasks:
• Read the file README.2 in the labs directory
• Edit the file DragDrop.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 15, slide 17 of 19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Check Your Progress


• Write programs that support cut-and-paste operations
• Write programs that support drag-and-drop operations

GUI Construction With Java Foundation Classes Module 15, slide 18 of 19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Think Beyond
• What reusable components can you create for use with
GUI data transfer?

GUI Construction With Java Foundation Classes Module 15, slide 19 of 19


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Module 16

Using the GridBagLayout

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Course map
• Relevance
• Objectives

GUI Construction With Java Foundation Classes Module 16, slide 2 of 20


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 16, slide 3 of 20


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 16, slide 4 of 20


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The GridBagLayout
• Row/column count determined by cell usage
• Row/column basic size determined by contents

GUI Construction With Java Foundation Classes Module 16, slide 5 of 20


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Module 16, slide 6 of 20


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The GridBagLayout
• Components are located within region by "anchor"
• Fill can make anchor ineffective

GUI Construction With Java Foundation Classes Module 16, slide 7 of 20


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The GridBagConstraints Class


• For each component, specify:
• Top left corner of cell with gridx, gridy
• Cell size with gridwidth, gridheight
• "Stretchiness" with fill
• anchor
• Specify row and column stretchiness with weightx,
weighty

GUI Construction With Java Foundation Classes Module 16, slide 8 of 20


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Designing with GridBagLayout


1. Sketch all components
2. Sketch all components on resized container
3. Identify all gridlines and hence row/column count
4. Identify stretchy rows/columns and allocate weights
5. Identify starting row/column for each component
6. Identify width/height for each component
7. Identify fill for each component
8. Identify anchor for each component
9. Assert row/column weights on one component each
GUI Construction With Java Foundation Classes Module 16, slide 9 of 20
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services
Example

Basic, unexpanded layout proposal

Basic, expanded layout proposal

GUI Construction With Java Foundation Classes Module 16, slide 10 of 20


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services
Example
0 1 2 3 4

Extra column
0 1 2 3 4

Loose component

GUI Construction With Java Foundation Classes Module 16, slide 11 of 20


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services
Example
1

2 3 4 5

9
6 7
10

11

12

Component gridx gridy gridwidth gridheight

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

GUI Construction With Java Foundation Classes Module 16, slide 12 of 20


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services
Example
0 1 1 2 3 4

0 1

1 2 3 4 5

2 8

3 9
7
6

4 10

5 11

6 12

GUI Construction With Java Foundation Classes Module 16, slide 13 of 20


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Example

GUI Construction With Java Foundation Classes Module 16, slide 14 of 20


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services
Example
1 import java.awt.*;
2 import javax.swing.*;
3
4 public class ExampleGB {
5 public static void main(String args[]) {
6 JFrame f = new JFrame(“GridBag Example”);
7 Container c = f.getContentPane();
8 c.setLayout(new GridBagLayout());
9 GridBagAdder.add(c, new Canvas(), 3, 2, 1, 1, 1, 0,
10 GridBagConstraints.NONE, GridBagConstraints.CENTER);
11 GridBagAdder.add(c, new JButton(“1”), 0, 0, 5, 1, 0, 0,
12 GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER);
13 GridBagAdder.add(c, new JButton(“2”), 0, 1, 1, 1, 0, 0,
14 GridBagConstraints.BOTH, GridBagConstraints.CENTER);
15 GridBagAdder.add(c, new JButton(“3”), 1, 1, 1, 1, 1, 0,
16 GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER);
17 GridBagAdder.add(c, new JButton(“4”), 2, 1, 1, 1, 0, 0,
18 GridBagConstraints.BOTH, GridBagConstraints.CENTER);
19 GridBagAdder.add(c, new JButton(“5”), 3, 1, 2, 1, 0, 0,
20 GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER);
21 GridBagAdder.add(c, new JButton(“6”), 0, 2, 1, 4, 0, 0,
22 GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER);
23 GridBagAdder.add(c, new JButton(“7”), 1, 2, 3, 4, 0, 0,
24 GridBagConstraints.BOTH, GridBagConstraints.CENTER);
25 GridBagAdder.add(c, new JButton(“8”), 4, 2, 1, 1, 0, 1,
26 GridBagConstraints.BOTH, GridBagConstraints.CENTER);
27 GridBagAdder.add(c, new JButton(“9”), 4, 3, 1, 1, 0, 1,
28 GridBagConstraints.BOTH, GridBagConstraints.CENTER);
29 GridBagAdder.add(c, new JButton(“10”), 4, 4, 1, 1, 0, 1,
30 GridBagConstraints.BOTH, GridBagConstraints.CENTER);
31 GridBagAdder.add(c, new JButton(“11”), 4, 5, 1, 1, 0, 1,
32 GridBagConstraints.BOTH, GridBagConstraints.CENTER);
33 GridBagAdder.add(c, new JButton(“12”), 0, 6, 5, 1, 0, 0,
34 GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER);
35 f.pack();
36 f.setVisible(true);
37 }

GUI Construction With Java Foundation Classes Module 16, slide 15 of 20


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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 }

GUI Construction With Java Foundation Classes Module 16, slide 16 of 20


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

RELATIVE and REMAINDER


• Shorthand for position/size
• For gridx/gridy
RELATIVE => Next position
• For gridwidth/gridheight
RELATIVE => Extends to last but one
• For gridwidth/gridheight
REMAINDER => Extends to last one
• Careful use of these aids maintenance but:
• Makes adding order significant
• Might cloud readability of code

GUI Construction With Java Foundation Classes Module 16, slide 17 of 20


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Exercise: Using GridBagLayout


• Objective: Implement a GUI layout using
GridBagLayout
• Preparation: Run the program Layout in the solutions
directory
• Tasks:
• Read the file README in the labs directory
• Edit the file Layout.java
• Exercise summary

GUI Construction With Java Foundation Classes Module 16, slide 18 of 20


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Check Your Progress


• Write code to implement a specified layout using
GridBagLayout

GUI Construction With Java Foundation Classes Module 16, slide 19 of 20


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Think Beyond
• Are there any layout effects that you cannot handle
using the layout managers you now understand?

GUI Construction With Java Foundation Classes Module 16, slide 20 of 20


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Appendix A

Delegation Event Handling

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Relevance

• Objectives

GUI Construction With Java Foundation Classes Appendix A, slide 2 of 6


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

JDK 1.1 Event Model


• JDK 1.1 introduces delegation model
• AWT, the JavaBeans component model, and Swing all
use it
• Swing requires it

GUI Construction With Java Foundation Classes Appendix A, slide 3 of 6


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

What Is Event Handling?


• An event is an information object.
• When something happens:
• A descriptive event object is created
• The event is passed as argument to listener methods
• To be called, a listener must register first.
• Events are only processed by interested parties.

GUI Construction With Java Foundation Classes Appendix A, slide 4 of 6


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Coding With Events


• To receive events, call an addXXXListener method
JButton b = new JButton("Press Me");
b.addActionListener(this); // inform me...

• Implement the appropriate XXXListener interface


public class MyButtonHandler implements
ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Got event " + e +
" from object " + e.getSource());
}
}

GUI Construction With Java Foundation Classes Appendix A, slide 5 of 6


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Appendix A, slide 6 of 6


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Appendix B

Printing

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Relevance

• Objectives

GUI Construction With Java Foundation Classes Appendix B, slide 2 of 5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Appendix B, slide 3 of 5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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);

g.dispose(); // output this page


}
pj.end();

GUI Construction With Java Foundation Classes Appendix B, slide 4 of 5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

AWT Printing Limitations


• With AWT, printing is 72 dpi.
• JComponent paintAll or paint methods need a non-
null clip in their Graphics.
• Non-lightweight components might not render on a
printer using the paint method.

GUI Construction With Java Foundation Classes Appendix B, slide 5 of 5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Appendix C

Adding Fonts to the Java Runtime

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Relevance

• Objectives

GUI Construction With Java Foundation Classes Appendix C, slide 2 of 6


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Appendix C, slide 3 of 6


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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

GUI Construction With Java Foundation Classes Appendix C, slide 4 of 6


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Adding a Font to Microsoft Windows


• Font specification references like:
serif.0=Times New Roman,ANSI_CHARSET
• Digit allows multiple font files for Unicode
• Win32 Charset entry:
ANSI_CHARSET, SYMBOL_CHARSET, and others
• Non-Unicode conversions
• NEED_CONVERTED
• Provide corresponding index converter class:
fontcharset.serif.1=\
sun.awt.windows.CharToByteWingDings

GUI Construction With Java Foundation Classes Appendix C, slide 5 of 6


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Adding a Font to a Solaris System


• Similar font specification
serif.plain.0=
-linotype-times-medium-r-normal--*-%d-*-*-p-*-
iso8859-1

• Attributes are part of the name


• X11 font names, with %d for scale
• All X11 fonts need conversion for Unicode indices
• NEED_CONVERTED is assumed
• fontcharset entry required

GUI Construction With Java Foundation Classes Appendix C, slide 6 of 6


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Appendix D

Undo/Redo Handling

GUI Construction With Java Foundation Classes November 1998


Sun Educational Services

Overview
• Relevance

• Objectives

GUI Construction With Java Foundation Classes Appendix D, slide 2 of 5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

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.

GUI Construction With Java Foundation Classes Appendix D, slide 3 of 5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services
Undo Example
1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4 import javax.swing.event.*;
5 import javax.swing.text.*;
6 import javax.swing.undo.*;
7
8 public class Undoer {
9 public static void main(String args[]) {
10 JFrame frame = new JFrame("Undoable Edits");
11 JTextPane pane = new JTextPane();
12 frame.getContentPane().add(pane, BorderLayout.CENTER);
13 DisplayableUndoManager undoer =
new DisplayableUndoManager(pane);
14 frame.getContentPane().add(undoer, BorderLayout.SOUTH);
15 frame.pack();
16 frame.setVisible(true);
17 }
18 }
19
20 class DisplayableUndoManager extends JPanel
implements UndoableEditListener {
21 private UndoManager undoManager = new UndoManager();
22 private JTextField nextUndo = new JTextField("", 30);
23 private JTextField nextRedo = new JTextField("", 30);
24 private JButton undoButton = new JButton("Undo");
25 private JButton redoButton = new JButton("Redo");
26 private JPanel leftPanel = new JPanel();
27 private JPanel rightPanel = new JPanel();
28
29 public DisplayableUndoManager(JTextComponent editSource) {
30 leftPanel.setLayout(new GridLayout(2, 1));
31 leftPanel.add(undoButton);
32 leftPanel.add(redoButton);
33
34 rightPanel.setLayout(new GridLayout(2, 1));
35 rightPanel.add(nextUndo);
36 rightPanel.add(nextRedo);
37

GUI Construction With Java Foundation Classes Appendix D, slide 4 of 5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services
Undo Example
38 setLayout(new BorderLayout());
39 add(leftPanel, BorderLayout.WEST);
40 add(rightPanel, BorderLayout.CENTER);
41
42 nextUndo.setEnabled(false); // just for viewing.
43 nextRedo.setEnabled(false); // ditto
44
45 editSource.getDocument().addUndoableEditListener(this);
46 undoButton.addActionListener(
47 new ActionListener() {
48 public void actionPerformed(ActionEvent ev) {
49 undoManager.undo();
50 refresh();
51 }
52 }
53 );
54
55 redoButton.addActionListener(
56 new ActionListener() {
57 public void actionPerformed(ActionEvent ev) {
58 undoManager.redo();
59 refresh();
60 }
61 }
62 );
63 }
64
65 public void undoableEditHappened(UndoableEditEvent ev) {
66 undoManager.undoableEditHappened(ev);
67 refresh();
68 }
69
70 private void refresh() {
71 nextUndo.setText(undoManager.getUndoPresentationName());
72 nextRedo.setText(undoManager.getRedoPresentationName());
73 undoButton.setEnabled(undoManager.canUndo());
74 redoButton.setEnabled(undoManager.canRedo());
75 }
76 }

GUI Construction With Java Foundation Classes Appendix D, slide 5 of 5


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Course Contents

About This Course .......................................................................................................Preface-1


Course Overview ......................................................................................................................... Preface-2
Course Map ................................................................................................................................... Preface-3
Module-by-Module Overview ................................................................................................... Preface-4
Course Objectives ......................................................................................................................... Preface-6
Topics Not Covered ..................................................................................................................... Preface-7
How Prepared Are You? ............................................................................................................. Preface-8
Introductions ................................................................................................................................ Preface-9
How to Use the Course Materials ............................................................................................ Preface-10
Icons ............................................................................................................................................. Preface-11
Typographical Conventions ..................................................................................................... Preface-12

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

GUI Construction With Java Foundation Classes i


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Swing Foundations .................................................................................................................2-1


Overview .................................................................................................................................................. 2-2
Comparing Swing and AWT Components ......................................................................................... 2-3
Converting From AWT to Swing .......................................................................................................... 2-4
New Components in Swing ................................................................................................................... 2-5
Top Level Swing Containers ................................................................................................................. 2-6
Using a RootPaneContainer ..................................................2-7
JFrame Essentials .................................................................................................................................... 2-8
Exercise: Converting an AWT GUI to Swing ...................................................................................... 2-9
Check Your Progress ............................................................................................................................ 2-10
Think Beyond ........................................................................................................................................ 2-11

Basic Swing Components ......................................................................................................3-1


Overview .................................................................................................................................................. 3-2
The Icon Interface ................................................................................................................................... 3-3
Creating an Icon ...........................................................3-4
Implementing the Icon Interface ......................................................................................................... 3-5
The JLabel Class .................................................................................................................................... 3-6
JLabel Example ...................................................................................................................................... 3-7
Tooltips ..................................................................................................................................................... 3-8
Buttons ...................................................................................................................................................... 3-9
The JButton Class ................................................................................................................................ 3-10
JButton Example .................................................................................................................................. 3-11
The JCheckBox Class ............................................................................................................................ 3-13
JCheckBox Example ............................................................................................................................. 3-14
The JRadioButton Class ..................................................................................................................... 3-15
JRadioButton Example ....................................................................................................................... 3-16
The JComboBox Class ............................................................................................................................ 3-19
JComboBox Example ............................................................................................................................. 3-20
The JMenu Class .................................................................................................................................... 3-22

GUI Construction With Java Foundation Classes ii


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

JMenu Example ...................................................................................................................................... 3-23


Additional Features of JMenu .................................................3-26
Exercise: Using Basic Swing Components ........................................................................................ 3-27
Check Your Progress ............................................................................................................................ 3-28
Think Beyond ........................................................................................................................................ 3-29

More Swing Foundations ......................................................................................................4-1


Overview .................................................................................................................................................. 4-2
JComponent Accessibility ...................................................................................................................... 4-3
Actions ...................................................................................................................................................... 4-4
Keystrokes ................................................................................................................................................ 4-5
Attaching an Action to a KeyStroke ...........................................4-6
Exercise 1: Investigate Action Objects .................................................................................................. 4-7
Exercise 2: Investigate Keystroke Handling ........................................................................................ 4-8
Check Your Progress .............................................................................................................................. 4-9
Think Beyond ........................................................................................................................................ 4-10

JDK 1.2 Printing ......................................................................................................................5-1


Overview .................................................................................................................................................. 5-2
Two Modes of Printing .......................................................................................................................... 5-3
JDK 1.2 Printing ....................................................................................................................................... 5-4
Implementing the Printable Interface .............................................................................................. 5-5
Using the PrinterJob .......................................................5-6
The Printable and Pageable Interfaces ........................................................................................... 5-7
Example of Using Pageable and Book ..........................................5-8
The PageFormat Class ........................................................................................................................... 5-9
Exercise: Using JDK 1.2 Printing ......................................................................................................... 5-10
Check Your Progress ............................................................................................................................ 5-11
Think Beyond ........................................................................................................................................ 5-12

GUI Construction With Java Foundation Classes iii


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Models, Views, and Controllers ...........................................................................................6-1


Overview .................................................................................................................................................. 6-2
MVC Overview ....................................................................................................................................... 6-3
Benefits of MVC ...................................................................................................................................... 6-7
Implementing MVC in JDK 1.1 ............................................................................................................. 6-8
Event Sourcing ........................................................................................................................................ 6-9
Handling Listeners ............................................................................................................................... 6-10
Dispatching the Event .......................................................................................................................... 6-11
MVC in Swing ....................................................................................................................................... 6-12
Exercise: MVC Demonstration Using the 1.1 Event Model ............................................................ 6-13
Check Your Progress ............................................................................................................................ 6-14
Think Beyond ........................................................................................................................................ 6-15

Swing MVC Components ......................................................................................................7-1


Overview .................................................................................................................................................. 7-2
MVC in Swing ......................................................................................................................................... 7-3
Using a JList ..............................................................7-4
Using a ListModel ..........................................................7-5
Exercise 1: Sharing a Model With MVC .............................................................................................. 7-6
Actions, KeyStrokes and Models .......................................................................................................... 7-7
Defining an Action .........................................................7-8
Action and Model Interactions ............................................................................................................. 7-9
Exercise 2: Defining Action Classes .................................................................................................. 7-10
Check Your Progress ............................................................................................................................ 7-11
Think Beyond ........................................................................................................................................ 7-12

Using the JTable ....................................................................................................................8-1


Overview .................................................................................................................................................. 8-2
JTable Fundamentals ............................................................................................................................ 8-3
Essential JTable Support Classes ........................................................................................................ 8-4

GUI Construction With Java Foundation Classes iv


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

The TableModel interface ..................................................................................................................... 8-5


The TableColumnModel Interface and TableColumn Class ............................................................. 8-6
Using a JTable .............................................................8-7
Using an AbstractTableModel ...............................................8-8
Controlling Table Appearance .............................................................................................................. 8-9
Using a CellRenderer ......................................................8-10
Writing a CellRenderer ....................................................8-11
Using a CellEditor ........................................................8-12
Exercise 1: Using JTable and TableModel ......................................8-13
Exercise 2: Controlling Editability With the TableModel ...........................8-14
Exercise 3: Using a Cell Renderer ....................................................................................................... 8-15
Exercise 4: Using a Cell Editor ............................................................................................................ 8-16
Check Your Progress ............................................................................................................................ 8-17
Think Beyond ........................................................................................................................................ 8-18

Using the JTree ......................................................................................................................9-1


Overview .................................................................................................................................................. 9-2
JTree Foundations ................................................................................................................................. 9-3
The DefaultTreeModel and DefaultMutableTreeNode ............................9-4
Using DefaultTreeModel and DefaultMutableTreeNode ..........................9-5
The TreeModel Interface ........................................................................................................................ 9-8
More About JTree ..........................................................9-9
Exercise: Using JTree and DefaultTreeModel ..................................9-10
Check Your Progress ............................................................................................................................ 9-11
Think Beyond ........................................................................................................................................ 9-12

Text Editing With Swing .....................................................................................................10-1


Overview ................................................................................................................................................ 10-2
Basic Text Editing .................................................................................................................................. 10-3
Using the JTextPane .......................................................10-4

GUI Construction With Java Foundation Classes v


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Styles and JTextPane ......................................................10-5


Constructing Styles ............................................................................................................................... 10-6
Applying Styles ..................................................................................................................................... 10-7
Placing Components in JTextPane ............................................10-8
Images in JTextPane .......................................................10-9
Exercise: Using JTextPane and Styles ............................................................................................ 10-10
Check Your Progress .......................................................................................................................... 10-11
Think Beyond ...................................................................................................................................... 10-12

More Swing Features ............................................................................................................11-1


Overview ................................................................................................................................................ 11-2
Swing Is Not Thread Safe .................................................................................................................... 11-3
Calling Methods From Other Threads ............................................................................................... 11-5
Communicating Between Threads ..................................................................................................... 11-6
Swing Component Appearance .......................................................................................................... 11-7
Using Borders ........................................................................................................................................ 11-8
Border Appearance ............................................................................................................................... 11-9
Controlling Look and Feel ................................................................................................................. 11-10
Focus Handling ................................................................................................................................... 11-12
Controlling Default Focus .................................................................................................................. 11-13
Focus Traversal .................................................................................................................................... 11-14
Exercise 1: Observe Default Focus Traversal .................................................................................. 11-15
Exercise 2: Control Focus Traversal ................................................................................................. 11-16
Exercise 3: Control Default Focus Position ..................................................................................... 11-17
Exercise 4: Install a Look and Feel .................................................................................................... 11-18
Check Your Progress .......................................................................................................................... 11-19
Think Beyond ...................................................................................................................................... 11-21

Utility Panes .........................................................................................................................12-1


Overview ................................................................................................................................................ 12-2

GUI Construction With Java Foundation Classes vi


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Utility Panes ........................................................................................................................................... 12-3


The JFileChooser .........................................................12-4
JFileChooser Example ....................................................................................................................... 12-5
Using the JFileChooser ....................................................12-6
The JTabbedPane ..........................................................12-7
Using the JTabbedPane .....................................................12-8
JTabbedPane Example ......................................................................................................................... 12-9
Using the JSplitPane .....................................................12-11
JSplitPane Example ......................................................................................................................... 12-12
Controlling the Divider ...................................................................................................................... 12-13
Using the JScrollPane ....................................................12-14
Assigning Components to Regions of a JScrollPane ............................12-15
Controlling Scrolling .......................................................................................................................... 12-16
The JOptionPane .........................................................12-17
Exercise: Using the Utility Panes ...................................................................................................... 12-20
Check Your Progress .......................................................................................................................... 12-21
Think Beyond ...................................................................................................................................... 12-22

Program Localization ..........................................................................................................13-1


Overview ................................................................................................................................................ 13-2
Unicode and Other Character Sets ..................................................................................................... 13-3
Localizing Code ..................................................................................................................................... 13-4
Locale ...................................................................................................................................................... 13-5
ResourceBundle ..........................................................13-6
Using a ResourceBundle ....................................................13-7
Creating a ResourceBundle .................................................13-8
ListResourceBundle ......................................................13-9
Formatting Messages .......................................................................................................................... 13-10
Basic Use of MessageFormat ................................................13-11
Localizing Formatted Messages ........................................................................................................ 13-12

GUI Construction With Java Foundation Classes vii


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

More Control of Message Formatting .............................................................................................. 13-13


Date Formatting .................................................................................................................................. 13-14
Numeric Formatting ........................................................................................................................... 13-15
Choice Formatting .............................................................................................................................. 13-16
Nested Formatting .............................................................................................................................. 13-17
Exercise: Program Localization ......................................................................................................... 13-19
Check Your Progress .......................................................................................................................... 13-20
Think Beyond ...................................................................................................................................... 13-21

Creating Custom Components ............................................................................................14-1


Overview ................................................................................................................................................ 14-2
Component Requirements ................................................................................................................... 14-3
Creating a New Component ................................................................................................................ 14-4
Lightweight Components .................................................................................................................... 14-5
Event Handling ..................................................................................................................................... 14-6
Event Sourcing Choices ........................................................................................................................ 14-7
Add/Remove Listener Methods ......................................................................................................... 14-8
Event Firing Convenience Method ..................................................................................................... 14-9
Example ................................................................................................................................................ 14-12
Exercise: Create a New Component ................................................................................................. 14-13
Check Your Progress .......................................................................................................................... 14-14
Think Beyond ...................................................................................................................................... 14-15

GUI Data Transfer ...............................................................................................................15-1


Overview ................................................................................................................................................ 15-2
Data Types ............................................................................................................................................. 15-3
The System Clipboard .......................................................................................................................... 15-4
Paste From Clipboard ........................................................................................................................... 15-5
Copy to Clipboard ................................................................................................................................ 15-7
Copy to Clipboard ................................................................................................................................ 15-8

GUI Construction With Java Foundation Classes viii


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

Implementing Transferable ................................................15-9


Exercise 1: Implementing Cut-and-Paste ........................................................................................ 15-10
Drag-and-Drop .................................................................................................................................... 15-11
DropTarget and DropTargetListener .......................................15-12
DragSource, DragSourceListener, and DragGestureListener ...................15-15
Exercise 2: Implementing Drag-and-Drop ...................................................................................... 15-17
Check Your Progress .......................................................................................................................... 15-18
Think Beyond ...................................................................................................................................... 15-19

Using the GridBagLayout ..................................................................................................16-1


Overview ................................................................................................................................................ 16-2
Layout Managers .................................................................................................................................. 16-3
The GridBagLayout ........................................................16-4
The GridBagConstraints Class ........................................................................................................ 16-8
Designing with GridBagLayout ..............................................16-9
Example ................................................................................................................................................ 16-10
RELATIVE and REMAINDER .......................................................................................................... 16-17
Exercise: Using GridBagLayout .............................................16-18
Check Your Progress .......................................................................................................................... 16-19
Think Beyond ...................................................................................................................................... 16-20

Delegation Event Handling ..................................................................................................A-1


Overview ................................................................................................................................................. A-2
JDK 1.1 Event Model ............................................................................................................................. A-3
What Is Event Handling? ...................................................................................................................... A-4
Coding With Events ............................................................................................................................... A-5
Event Classes .......................................................................................................................................... A-6

Printing ................................................................................................................................... B-1


Overview ..................................................................................................................................................B-2

GUI Construction With Java Foundation Classes ix


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A
Sun Educational Services

AWT Printing ..........................................................................................................................................B-3


Example ....................................................................................................................................................B-4
AWT Printing Limitations .....................................................................................................................B-5

Adding Fonts to the Java Runtime ..................................................................................... C-1


Overview ................................................................................................................................................. C-2
Fonts ......................................................................................................................................................... C-3
Font Configuration ................................................................................................................................ C-4
Adding a Font to Microsoft Windows ................................................................................................ C-5
Adding a Font to a Solaris System ....................................................................................................... C-6

Undo/Redo Handling ............................................................................................................D-1


Overview ................................................................................................................................................. D-2
Undo/Redo Features ............................................................................................................................. D-3
Undo Example ........................................................................................................................................ D-4

GUI Construction With Java Foundation Classes x


Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998, Revision A

You might also like