0% found this document useful (0 votes)
153 views24 pages

Webswing

Java Swing student workbook is published by ITCourseware, LLC. Many instructors whose ideas and review have contributed to the quality of this workbook. Many students have offered comments, suggestions, criticisms, and insights. No part of this book may be reproduced or utilized without permission.

Uploaded by

api-3772730
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
153 views24 pages

Webswing

Java Swing student workbook is published by ITCourseware, LLC. Many instructors whose ideas and review have contributed to the quality of this workbook. Many students have offered comments, suggestions, criticisms, and insights. No part of this book may be reproduced or utilized without permission.

Uploaded by

api-3772730
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Java Swing

Student Workbook
Java Swing

Java Swing

Published by ITCourseware, LLC, 7245 South Havana Street, Suite 100, Englewood, CO 80112

Contributing Authors: Channing Lovely, Rob Roselius, Rick Sussenbach, Danielle Waleri.

Editors: Rob Roselius, Danielle Waleri.

Editorial Staff: Jan Waleri, Mark Walters

Special thanks to: Many Java instructors whose ideas and careful review have contributed to the quality
of this workbook, including Jimmy Ball, Larry Burley, Julie Johnson, Roger Jones, Joe McGlynn, Jim
McNally, Richard Raab, and Todd Wright, and the many students who have offered comments,
suggestions, criticisms, and insights.

Copyright © 2002 by ITCourseware, LLC. All rights reserved. No part of this book may be reproduced
or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by
an information storage retrieval system, without permission in writing from the publisher. Inquiries should be
addressed to ITCourseware, LLC, 7245 South Havana Street, Suite 100, Englewood, CO 80112. (303)
302-5280.

All brand names, product names, trademarks, and registered trademarks are the property of their respective
owners.

Page ii Rev 4.1.2 © 2002 ITCourseware, LLC


Java Swing

Contents
Chapter 1 - Course Introduction ............................................................................................................... 7
Course Objectives .............................................................................................................................. 8
Course Overview .............................................................................................................................. 10
Using the Workbook ......................................................................................................................... 11
Suggested References ....................................................................................................................... 12

Chapter 2 - Collections ........................................................................................................................... 15


Java Arrays ....................................................................................................................................... 16
The Collections Framework .............................................................................................................. 18
Set Implementation Classes ............................................................................................................... 20
List Implementation Classes .............................................................................................................. 22
Map Implementation Classes ............................................................................................................. 24
Applying Algorithms .......................................................................................................................... 26
Implementation and Performance Strategies ...................................................................................... 28
Labs ................................................................................................................................................. 30

Chapter 3 - Introduction to Threads ........................................................................................................ 33


Non-Threaded Applications .............................................................................................................. 34
Threaded Applications ...................................................................................................................... 36
Creating Threads ............................................................................................................................... 38
Thread States .................................................................................................................................... 40
Runnable Threads ............................................................................................................................. 42
Coordinating Threads ........................................................................................................................ 44
Runnable Interface ............................................................................................................................ 46
Threads in Applets ............................................................................................................................ 48
Interrupting Threads .......................................................................................................................... 50
ThreadGroups ................................................................................................................................... 52
Labs ................................................................................................................................................. 54

© 2002 ITCourseware, LLC Rev 4.1.2 Page iii


Java Swing

Chapter 4 - Inner Classes ....................................................................................................................... 57


Inner Classes .................................................................................................................................... 58
Member Classes ............................................................................................................................... 60
Local Classes .................................................................................................................................... 62
Anonymous Classes .......................................................................................................................... 64
Instance Initializers ............................................................................................................................ 66
Nested Classes ................................................................................................................................. 68
Inheritance vs. Containment ............................................................................................................... 70
Labs ................................................................................................................................................. 72

Chapter 5 - Getting Started with Swing ................................................................................................... 75


AWT and Swing ............................................................................................................................... 76
Displaying a Window......................................................................................................................... 78
GUI Programming in Java ................................................................................................................. 80
Handling Events ................................................................................................................................ 82
Arranging Components ..................................................................................................................... 84
A Scrollable Component ................................................................................................................... 86
Configuring Components .................................................................................................................. 88
Menus ............................................................................................................................................... 90
Using the JFileChooser ..................................................................................................................... 92
Heavyweight vs. Lightweight Components ......................................................................................... 94
Labs ................................................................................................................................................. 96

Chapter 6 - Event Handling ................................................................................................................... 101


The Event Delegation Model ........................................................................................................... 102
Implementing a Listener ................................................................................................................... 104
Semantic Events .............................................................................................................................. 106
List Selection Events ....................................................................................................................... 108
Event Objects ................................................................................................................................. 110
Mouse Events ................................................................................................................................. 112
Other Low-level Events .................................................................................................................. 114
A Popup Menu Example ................................................................................................................. 116
Adapters ......................................................................................................................................... 118
Labs ............................................................................................................................................... 120

Page iv Rev 4.1.2 © 2002 ITCourseware, LLC


Java Swing

Chapter 7 - Components....................................................................................................................... 123


Controlling Component Appearance ................................................................................................ 124
The Component Hierarchy .............................................................................................................. 126
Fonts .............................................................................................................................................. 128
Font Manipulation ........................................................................................................................... 130
Color .............................................................................................................................................. 132
Getting Fancy .................................................................................................................................. 134
Text Components ............................................................................................................................ 136
More Text Components .................................................................................................................. 138
Scrolled Components ...................................................................................................................... 140
JTable and MVC ............................................................................................................................ 142
Labs ............................................................................................................................................... 144

Chapter 8 - Laying Out a Container ...................................................................................................... 149


Containment Hierarchy .................................................................................................................... 150
Using Layout Managers .................................................................................................................. 152
Top-Level Containers ..................................................................................................................... 154
General-Purpose Containers ........................................................................................................... 156
FlowLayout .................................................................................................................................... 158
Box and BoxLayout ........................................................................................................................ 160
CardLayout .................................................................................................................................... 162
JTabbedPane .................................................................................................................................. 164
GridLayout...................................................................................................................................... 166
GridBagLayout and GridBagConstraints.......................................................................................... 168
Non-Managed Containers ............................................................................................................... 170
Labs ............................................................................................................................................... 172

Chapter 9 - Specialized Components .................................................................................................... 177


Specialized Components ................................................................................................................. 178
Compound Components ................................................................................................................. 180
Dialogs ............................................................................................................................................ 182
Extending Dialog ............................................................................................................................. 184
Using JOptionPane.......................................................................................................................... 186
Choosers ........................................................................................................................................ 188
Labs ............................................................................................................................................... 190

© 2002 ITCourseware, LLC Rev 4.1.2 Page v


Java Swing

Chapter 10 - Applets ............................................................................................................................ 195


Loading Applets .............................................................................................................................. 196
The <APPLET> Tag ....................................................................................................................... 198
GUI Applets ................................................................................................................................... 200
Graphical Applets ............................................................................................................................ 202
HTML Parameters .......................................................................................................................... 204
Retrieving Images ............................................................................................................................ 206
Browser Interaction......................................................................................................................... 208
Applet Methods .............................................................................................................................. 210
Applet vs. Application ..................................................................................................................... 212
Swing Applets ................................................................................................................................. 214
Plug-Ins .......................................................................................................................................... 216
HTML Tags for Swing Applets ........................................................................................................ 218
Security ........................................................................................................................................... 220
Labs ............................................................................................................................................... 222

Chapter 11 - Input/Output Streams ....................................................................................................... 225


Overview of Streams....................................................................................................................... 226
Bytes vs. Characters ....................................................................................................................... 228
Converting Byte Streams to Character Streams ............................................................................... 230
Binary Input and Output .................................................................................................................. 232
PrintWriter Class ............................................................................................................................. 234
Reading and Writing Objects ........................................................................................................... 236
Streams Streams Streams ................................................................................................................ 238
Buffers, Channels and Charsets ....................................................................................................... 240
File and FileChannel Objects........................................................................................................... 242
Labs ............................................................................................................................................... 244

Chapter 12 - Managing Security Policies ............................................................................................... 247


The Java Security Model ................................................................................................................. 248
Policy Entries .................................................................................................................................. 250
Policy Files...................................................................................................................................... 252
Using the Policy Tool....................................................................................................................... 254
Security Managers .......................................................................................................................... 256
Default Applet Security ................................................................................................................... 258
Labs ............................................................................................................................................... 260

Solutions - Java Swing .......................................................................................................................... 265

Index..................................................................................................................................................... 325
Page vi Rev 4.1.2 © 2002 ITCourseware, LLC
Chapter 4 Inner Classes

Chapter 4 - Inner Classes

Objectives

¯ Use member, local and anonymous


classes.

¯ Create small classes when and where


you need them.

¯ Use nested classes.

© 2002 ITCourseware, LLC Rev 4.1.2 Page 57


Java Swing

Inner Classes

¯ Inner classes are classes defined within other classes.

Ø This syntax allows for quick and easy creation of classes for specific
purposes.

¯ The class that contains the inner class is called the enclosing class or the
enclosing instance (depending on the type of inner class).

¯ The enclosing class provides a namespace for its inner classes.

Ø Two enclosing classes can each have an inner class with exactly the same
name.

¯ Inner classes have some restrictions:

Ø They can't contain any static declarations.

Ø They can't have the same name as any containing class or package (unlike
fields and methods).

¯ There are three types of inner classes:

Ø Member classes.

Ø Local classes.

Ø Anonymous classes.

Page 58 Rev 4.1.2 © 2002 ITCourseware, LLC


Chapter 4 Inner Classes

The Java compiler compiles inner classes as "normal" classes, changing their names to ensure uniqueness
and indicate scope, and usually adding some code to them to make them work as described. Because the
compiler does this work, the Java Virtual Machine has not needed to be modified. This means that older
VMs will run code that uses inner classes.

The only thing that you, as a programmer, might notice are some strange .class files. Suppose that you have
a .java file with a class called MyOuter that has an inner class called MyInner. The compiler will create
a MyOuter.class file and a MyOuter$MyInner.class file. Don't use this name in your code at all. The
compiler takes care of everything!

© 2002 ITCourseware, LLC Rev 4.1.2 Page 59


Java Swing

Member Classes

¯ A class defined within an enclosing class, but without the static keyword, is a
member class.

¯ Every instance of the member class has an internal reference to the enclosing
object.

Ø A method in the member class can use its own data and the data in the
enclosing instance (including private fields), implicitly, without any
special syntax.

¯ You must specify an enclosing instance when creating a member instance from
another class.

Bank1 myBank = new Bank1(1234);


Teller t1 = myBank.new Teller("Dobbs", "Barb", 3);

¯ Member class methods can explicitly refer to the enclosing instance's data using
the enclosing class name along with this:

class Teller {
...
public string toString() {
String ret = "Bank #" + Bank1.this.bankId;
...

Page 60 Rev 4.1.2 © 2002 ITCourseware, LLC


Chapter 4 Inner Classes

Bank1.java
import java.util.*;

public class Bank1 {


int bankId;

class Teller {
private String lastname;
private String firstname;
private int accessLevel;

Teller(String l, String f, int access) {


lastname = l;
firstname = f;
accessLevel = access;
}
public String toString() {
// String ret = "Bank #" + bankId; // implicit
String ret = "Bank #" + Bank1.this.bankId; // explicit
ret = ret + " " + firstname + " " + lastname +
" : " + accessLevel;
return ret;
}
}
Bank1(int id) {
bankId = id;
}
public String toString() {
return "Bank ID: " + bankId;
}
}

RunBank1.java
import java.util.*;

public class RunBank1 {


public static void main(String[] args) {
Bank1 myBank = new Bank1(1234);
Bank1.Teller t1 = myBank.new Teller("Dobbs", "Barb", 3);
Bank1.Teller t2 = myBank.new Teller("Dobbs", "Bob", 2);
Bank1.Teller t3 = myBank.new Teller("Doe", "Jane", 4);

System.out.println("Teller 1: " + t1);


System.out.println("Teller 2: " + t2);
System.out.println("Teller 3: " + t3);
}
}
© 2002 ITCourseware, LLC Rev 4.1.2 Page 61
Java Swing

Local Classes

¯ A class defined within a code block is a local class; examples of code blocks
include:

Ø Methods

Ø Constructors

Ø static initialization blocks

Ø Instance initializers (discussed soon . . .)

¯ A local class has some interesting features:

Ø It is visible only within the code block in which it is defined, just like a
local variable.

Ø It can only use final method parameters or final local variables that
are within the same scope.

¯ A local class has access to member data and methods of the enclosing class,
just like a member class does.

Ø If the local class is within the static initialization block or method, then
it only has access to static fields.

¯ Local classes cannot be declared public, protected or private, since they


are not members of a class.

¯ Local classes are commonly used to implement event listeners.

Ø The definition and use of the class can be one after the other, making the
code more readable.

Page 62 Rev 4.1.2 © 2002 ITCourseware, LLC


Chapter 4 Inner Classes

RunBank1Local.java
import java.util.*;

public class RunBank1Local {


public static void main(String[] args) {
Bank1 myBank = new Bank1(1234);
Bank1.Teller t1 = myBank.new Teller("Dobbs", "Barb", 3);
Bank1.Teller t2 = myBank.new Teller("Dobbs", "Bob", 2);
Bank1.Teller t3 = myBank.new Teller("Doe", "Jane", 4);

// class TellerPrinter is local to main().


class TellerPrinter {
TellerPrinter(int n, Bank1.Teller t) {
System.out.println("Teller " + n + ": " + t);
}
}
new TellerPrinter(1, t1);
new TellerPrinter(2, t2);
new TellerPrinter(3, t3);
}
}

Local classes are often used to handle events in graphical Swing programs, implementing the method or
methods declared in an event listener interface:

Welcome.java
...
JButton bye = new JButton("Bye");
JButton adios = new JButton("Adios");
class ExitListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
f.dispose();
System.exit(0);
}
}
bye.addActionListener( new ExitListener() );
adios.addActionListener( new ExitListener() );
...

© 2002 ITCourseware, LLC Rev 4.1.2 Page 63


Java Swing

Anonymous Classes

¯ Anonymous classes combine the class definition with the object instantiation.

Ø They are used in expressions such as method calls or assignments.

¯ Additional syntax for the new operator was introduced to allow for anonymous
classes.

new Name( [arguments] ) {


//class definition
}

Ø If Name is a class name, then the anonymous class extends that class
and can provide constructor arguments.

Ø If Name is an interface name, then the anonymous class implements that


interface.

¯ Find a consistent, readable indentation style for your anonymous classes.

¯ Methods of local (including anonymous) classes can only use variables:

Ø Declared in the method body.

Ø Declared as parameters to the method.

Ø Declared as final in the local class's enclosing scope (the enclosing


method or block).

Ø Declared as fields of the enclosing class.

Page 64 Rev 4.1.2 © 2002 ITCourseware, LLC


Chapter 4 Inner Classes

RunBank1Anon.java
import java.util.*;

public class RunBank1Anon {


public static void main(String[] args) {
Bank1 myBank = new Bank1(1234);
Bank1.Teller t1 = myBank.new Teller("Dobbs", "Barb", 3);
Bank1.Teller t2 = myBank.new Teller("Dobbs", "Bob", 2);
Bank1.Teller t3 = myBank.new Teller("Doe", "Jane", 4);

// Anonymous class extends Teller, overrides Teller.toString()


Bank1.Teller th = myBank.new Teller("Clown", "Bozo", 9) {
public String toString () {
return super.toString() + " (Head Teller)";
}
};

System.out.println( "Teller 1: " + t1);


System.out.println( "Teller 2: " + t2);
System.out.println( "Teller 3: " + t3);
System.out.println( "Teller 4: " + th);
}
}

Anonymous classes are perfect for special-purpose event handlers for individual Swing components:

Welcome2.java
...
bye.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
System.exit(0);
}
});
...

© 2002 ITCourseware, LLC Rev 4.1.2 Page 65


Java Swing

Instance Initializers

¯ You would typically initialize data members of a class with a constructor.

Ø An anonymous class can not provide constructors, since it has no class


name.

¯ Instance initializers were added to allow an object to be properly initialized.

¯ A stand-alone code block inside a class definition is an instance initializer.

Ø Multiple instance initializers are allowed; they are run from top to bottom.

Ø They run after the superclass constructor, and before the current class'
constructor (if it isn't anonymous).

¯ The initialization of a data member can be done immediately after the declaration
of the variable.

Ø This is helpful if a simple assignment won't accomplish the task.

Page 66 Rev 4.1.2 © 2002 ITCourseware, LLC


Chapter 4 Inner Classes

Bank2.java
import java.util.*;
public class Bank2 {
int bankId;
class Teller {
private String lastname;
private String firstname;
protected int accessLevel;
Teller(String l, String f) {
lastname = l;
firstname = f;
accessLevel = 3;
}
public String toString() {
String ret = "Bank #" + bankId;
ret = ret + " " + firstname + " " + lastname + " : " + accessLevel;
return ret;
}
}
Bank2(int id) { bankId = id; }
public String toString() { return "Bank ID: " + bankId; }
}

RunBank2.java
import java.util.*;

public class RunBank2 {


public static void main(String[] args) {
Bank2 myBank = new Bank2(1234);
Bank2.Teller t1 = myBank.new Teller("Dobbs", "Barb");
Bank2.Teller t2 = myBank.new Teller("Dobbs", "Bob");
Bank2.Teller t3 = myBank.new Teller("Doe", "Jane");

// Anonymous class extends Teller


// - Overrides Teller.toString()
// - Initialized protected field accessLevel
Bank2.Teller th = myBank.new Teller("Clown", "Bozo") {
// Instance Initializer
{
accessLevel = 9;
}
public String toString () {
return super.toString() + " (Head Teller)";
}
};

System.out.println( "Teller 1: " + t1);


System.out.println( "Teller 2: " + t2);
System.out.println( "Teller 3: " + t3);
System.out.println( "Teller 4: " + th);
}
}
© 2002 ITCourseware, LLC Rev 4.1.2 Page 67
Java Swing

Nested Classes

¯ A class defined as a static member of another class is called a nested top-level


class.

Ø Nested top-level classes were introduced in Java 1.1, but are not inner
classes and do not have the restrictions of inner classes.

¯ Nested top-level classes have the same visibility as any other class within a
package.

¯ Special syntax is required to access these classes.

Ø Either use dot-notation:

Bank3.Teller t3 =
new Bank3.Teller("Doe", "Jane", 4);

Ø Or import the nested class:

import Bank3.*; // gets all nested classes


...
Teller t1 = new Teller("Doe", "Jane", 4);

¯ This nesting provides a new namespace; two classes can both contain nested top-
level classes with the same name.

¯ Interfaces defined within a class are implicitly static and are therefore top-level.

Ø It is not possible to have inner interfaces, only nested top-level interfaces.

Ø Declaring an interface as static is allowed, but has no effect.

Page 68 Rev 4.1.2 © 2002 ITCourseware, LLC


Chapter 4 Inner Classes

Bank3.java
import java.util.*;

public class Bank3 {


Vector tellers; Nested top-level classes
are static members of an
static class Teller { enclosing class.
private String lastname;
private String firstname;
private int accessLevel;

Teller(String l, String f, int access) {


lastname = l;
firstname = f;
accessLevel = access;
}
public String toString() {
return firstname + " " + lastname + " : " + accessLevel;
}
}

Bank3(Vector t) {
tellers = t;
}

public String toString() {


return "Tellers: " + tellers;
}
}

RunBank3.java
import java.util.*;

public class RunBank3 {


public static void main(String[] args) {
Bank3.Teller t1 = new Bank3.Teller("Dobbs", "Barb", 3);
Bank3.Teller t2 = new Bank3.Teller("Dobbs", "Bob", 2);
Bank3.Teller t3 = new Bank3.Teller("Doe", "Jane", 4);

Vector t = new Vector(); Nested top-level classes


t.addElement(t1); are referred to through their
t.addElement(t2); enclosing class.
t.addElement(t3);

Bank3 b = new Bank3(t);

System.out.println("My Bank: " + b);


}
}

Note: Nested top-level classes and interfaces are not considered true inner classes because they actually
have package scope. But they are commonly referred to in conjunction with inner classes since they were
introduced at the same time.
© 2002 ITCourseware, LLC Rev 4.1.2 Page 69
Java Swing

Inheritance vs. Containment

¯ There are two distinct hierarchies for an inner class:

Ø The inheritance hierarchy:

§ The Employee class inherits from the Person class.

Ø The containment hierarchy:

§ The Employee class is contained in the Business class.

Ø Special member access is available through both hierarchies:

§ An Employee object has access to Person members that are


protected.

§ An Employee object has access to Business members that are


private.

¯ Inner classes may inherit from any class that is visible within its scope.

Ø Top-level classes may also inherit from inner classes that are visible,
although this is not as common.

Page 70 Rev 4.1.2 © 2002 ITCourseware, LLC


Chapter 4 Inner Classes

Business.java
public class Business {
private class Employee extends Person {

// ... definition of an Employee goes here

// ... the rest of Business goes here

© 2002 ITCourseware, LLC Rev 4.1.2 Page 71


Java Swing

Labs

❶ Create a Department class with an Employee member class. The Employee class should
have data members for id, firstname, lastname, title and salary. Add a constructor
and display() method to Employee.
(Solution: Department.java)

❷ Modify the Department class. Add data members for an array of Employee objects, a
department code and a department name. Add a constructor that takes two arguments, the
department code and name.

The constructor would normally then initialize it's Employee array from a database, but just add
several "dummy" Employee objects to the array. Write a display() method for the
Department.
(Solution: Department1.java)

❸ Add a main() to Department that creates and displays a Department.


(Solution: Department2.java)

❹ Next, let's make our Department and Employee classes more useful from other classes. First,
remove the main() method from your Department class.

Add a method to Department named getEmployees() that returns the Department's


Employee[].

Add a method to Employee named getSalary() that returns the Employee's salary.

In another file, create a Headquarters class that has a main() method. In main(), create a
new Department object and display() it. Then get the Employee[] from that
Department by calling getEmployees(). Display the salary of the highest-paid employee.

Hint: For Headquarters to use the Employee class, it will have to be made
a public member of Department.
(Solutions: Department3.java, Headquarters.java)

Page 72 Rev 4.1.2 © 2002 ITCourseware, LLC


Chapter 4 Inner Classes

© 2002 ITCourseware, LLC Rev 4.1.2 Page 73


Java Swing

Page 74 Rev 4.1.2 © 2002 ITCourseware, LLC

You might also like