Download Examplets from The Java Developers Almanac 2000

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Examplets from The Java Developers Almanac 2000
Codesamples
Examplets from The Java Developers Almanac 2000
"Examplets" are code snippets that illustrate a particular task.
They're designed to show which classes and members are
involved in performing the task, and how the classes and
members interact with each other. You will see blue italicized
text in an examplet; this indicates code that should be replaced
if you use it in your program.
An examplet can have enough detail for you to use it, as is. Or
you might have to get more information about the involved
classes. A good place to find information about the Java 2
Platform APIs is the Java 2 Platform API index.
It's also good practice to add catch clauses, as appropriate, to
the examplets. If the code of an examplet throws a checked
exception, the code is surrounded by a try/catch statement.
However, to reduce space and distraction, the catch clause is
left blank. Catch clauses should always handle the exception
and should never be left blank. So, at the very least, you
should include a call to e.printStackTrace() to display the exception
on the console.
You'll find examplets in a variety of categories. See the Table of
Contents for a list of categories, and the examplets in each
category.
Table of Contents
http://developer.java.sun.com/developer/codesamples/ (1 of 13) [8/1/2000 7:46:26 AM]
Examplets from The Java Developers Almanac 2000
Accessibility
Arrays
Applets
Application and System
AWT (Abstract Windowing Toolkit)
Clipboard
Drag and Drop
Events
Fonts
Shapes
Compression
JAR files
Database - JDBC
Data Structures and Algorithms
Files, Streams, I/O
Images
Internationization
JavaBeans TM
JNDI
Directory
Event
Ldap
Math
Networking
Printing
Reference Objects
Reflection
RMI
Security
Sound
Sampled
Midi
Strings
Swing
Events
File Chooser
Layout
Tree
Text
Threads
Time
javax.rmi
javax.swing.undo
http://developer.java.sun.com/developer/codesamples/ (2 of 13) [8/1/2000 7:46:26 AM]
(javax.accessibility)
(java.lang)
(java.applet)
(java.lang)
(java.awt)
(java.awt.datatransfer)
(java.awt.dnd)
(java.awt.event)
(java.awt.font)
(java.awt.geom)
(java.util.zip)
(java.util.jar)
(java.sql)
(java.util)
(java.io)
(java.awt.image)
(java.text)
(java.beans)
(javax.naming)
(javax.naming.directory)
(javax.naming.event)
(javax.naming.ldap)
(java.math)
(java.net)
(java.awt.print)
(java.lang.ref)
(java.lang.reflect)
(java.rmi)
(java.security)
(javax.sound.sampled)
(javax.sound.midi)
(java.lang)
(javax.swing)
(javax.swing.event)
(javax.swing.filechooser)
(java.awt and javax.swing)
(javax.swing.tree)
(javax.swing.text)
(java.lang)
(java.lang)
(javax.naming)
(javax.naming.directory)
(javax.naming.event)
(javax.naming.ldap)
(javax.rmi)
(javax.swing.undo)
Examplets from The Java Developers Almanac 2000
Accessibility (javax.accessibility)
The Quintessential Accessible Object
Setting an Accessible Name for an Image Button
Setting a Description for Image Icons
Setting a Mnemomic for Buttons
Setting a Mnemonic for a Menu
Associating a Label with a Component
Setting a Keyboard Accelerator for a Menu Item
Applets (java.applet)
The Quintessential Applet
Getting an Applet Parameter
Making the Browser Visit a URL
Showing a Message in the Browser's Status Bar
Loading and Playing Audio in an Applet
Loading and Playing Audio in an Application
Loading and Painting an Image in an Applet
Animating an Array of Images in an Applet
AWT (Abstract Windowing Toolkit) (java.awt)
The Quintessential Drawing Program
Drawing Basic Shapes
Filling Basic Shapes
Loading an Image
Drawing an Image
Scaling, Shearing, Translating, and Rotating a Drawn
Image
Drawing Simple Text
Drawing Rotated Text
Getting the Dimensions of Text
Drawing Anti-Aliased Text and Graphics
Drawing with Alpha
Setting the Clipping Area with a Shape
Changing the Thickness of the Stroking Pen
Creating a Shape from a Stroked Shape
Stroking or Filling a Shape
Stroking or Filling with a Color
Stroking or Filling with a Gradient Color
Stroking or Filling with a Texture
Animating an Array of Images in an Application
http://developer.java.sun.com/developer/codesamples/ (3 of 13) [8/1/2000 7:46:26 AM]
Examplets from The Java Developers Almanac 2000
Setting a Component's Cursor
Clipboard (java.awt.datatransfer)
Retrieving Text from the System Clipboard
Placing Text on the System Clipboard
Drag and Drop (java.awt.dnd)
Making a Component Draggable
Making a Component a Drop Target
Handling a Drop Event
Events (java.awt.event)
Handling Events with an Anonymous Class
Handling Action Events
Handling Key Presses
Handling Mouse Clicks
Handling Mouse Motion
Detecting Double and Triple Clicks
Handling Focus Changes
Fonts (java.awt.font)
Listing All Available Fonts
Drawing a Paragraph of Text
Getting the Shape from the Outline of Text
Drawing Text with Mixed Styles
Shapes (java.awt.geom)
Creating a Shape with Lines and Curves
Creating Basic Shapes
Combining Shapes
Scaling, Shearing, Translating, and Rotating a Shape
Compression (java.util.zip)
Compressing a File
Decompressing a File
Listing the Contents of a ZIP File
Calculating the Checksum of a Byte Array
JAR files (java.util.jar)
Retrieving the Manifest of a JAR File
Database - JDBC (java.sql)
http://developer.java.sun.com/developer/codesamples/ (4 of 13) [8/1/2000 7:46:26 AM]
Examplets from The Java Developers Almanac 2000
Connecting to a Database
Creating a Database Table
Entering a New Row into a Database Table
Getting All Rows from a Database Table
Getting Particular Rows from a Database Table
Updating a Row of Data in a Database Table
Using a Prepared SQL Statement
Data Structures and Algorithms (java.util)
Creating a Set
Creating a List
Creating a Hash Table
Truncating a List
Converting a Collection to an Array
Converting an Array to a Collection
Implementing a Queue
Implementing a Stack
Iterating the Elements of a Collection
Sorting an Array
Finding an Element in a Sorted Array
Finding an Element in a Sorted List
Inserting an Element into a Sorted List
Generating a Random Number
Breaking a String into Words
Reading Properties from a Properties File
Creating Date Object From a Particular Date
Parsing a Date Using a Pattern
Reading and Writing a Properties File
Getting and Setting Properties
Scheduling a Timer Task to Run at a Certain Time
Scheduling a Timer Task to Run Repeatedly
Files, Streams, I/O (java.io)
http://developer.java.sun.com/developer/codesamples/ (5 of 13) [8/1/2000 7:46:26 AM]
Examplets from The Java Developers Almanac 2000
Constructing a Path
Reading Text from Standard Input
Reading Text from a File
Writing to a File
Creating a Directory
Appending to a File
Deleting a File
Deleting a Directory
Creating a Temporary File
Using a Random Access File
Listing the File System Roots
Setting File Modification Time
Serializing an Object
Deserializing an Object
Traversing a Directory
Reading UTF-8 Encoded Data
Writing UTF-8 Encoded Data
Reading ISO Latin-1 Encoded Data
Writing ISO Latin-1 Encoded Data
Images (java.awt.image)
Converting an Image to a Buffered Image
Getting Pixels from a Buffered Image
Getting a Sub-Image of an Image
Creating and Drawing on a Buffered Image
Scaling, Shearing, Translating, and Rotating an Image
Converting a Color Image to Gray
Blurring an Image
Sharpening an Image
Embossing an Image
Internationization (java.text)
Formatting and Parsing a Locale-specific Number
Formatting and Parsing Locale-specific Currency
Formatting and Parsing a Locale-specific Percentage
Formatting and Parsing a Locale-specific Date
Formatting and Parsing Locale-specific Time
Formatting and Parsing a Locale-specific Date and Time
Determining the Type of a Character
Comparing Strings in a Locale-independent Way
Determining the Character Boundaries in a Unicode String
Determining the Word Boundaries in a Unicode String
Determining the Sentence Boundaries in a Unicode String
http://developer.java.sun.com/developer/codesamples/ (6 of 13) [8/1/2000 7:46:26 AM]
Examplets from The Java Developers Almanac 2000
Determining Potential Line Breaks in a Unicode String
JavaBeans
TM
(java.beans)
The Quintessential Bean
Implementing a Bound Property
Implementing a Constrained Property
Instantiating a Bean
Handling a Property Change Event
Handling a Vetoable Property Change Event
Math (java.math)
Operating With Big Integer Values
Operating With Big Decimal Values
Setting the Decimal Place of a Big Decimal Value
Networking (java.net)
Creating a URL
Parsing a URL
Reading Text from a URL
Calling a CGI Using POST Method
Resolving a Hostname
Creating a Client Socket
Creating a Server Socket
Reading Text from a Socket
Writing Text to a Socket
Sending a Datagram
Receiving a Datagram
Joining a Multicast Group
Receiving from a Multicast Group
Sending to a Multicast Group
Printing (java.awt.print)
The Quintessential Printing Program
Getting the Dimensions of a Printed Page
Setting the Orientation of a Printed Page
Printing Pages with Different Formats
Displaying the Page Format Dialog
Displaying the Print Dialog
Reference Objects (java.lang.ref)
Holding onto an Object Until Memory Becomes Low
Determining When an Object Is No Longer Used
Determining When an Object Is About to be Reclaimed
http://developer.java.sun.com/developer/codesamples/ (7 of 13) [8/1/2000 7:46:26 AM]
Examplets from The Java Developers Almanac 2000
Reflection (java.lang.reflect)
Getting a Class Object
Getting the Modifiers of a Class Object
Getting the Interfaces of a Class Object
Getting the Methods of a Class Object
Getting a Constructor of a Class Object
Creating an Object Using a Constructor Object
Getting the Field Objects of a Class Object
Getting and Setting the Value of a Field
Invoking a Method Using a Method Object
Getting the Modifiers of a Member Object
Getting the Name of a Class or Member Object
Determining if an Object Is an Array
Determining the Dimensions of an Array
Getting the Component Type of an Array
Creating an Array
Expanding an Array
Getting and Setting the Value of an Element in an Array
Overriding Default Access
Creating a Proxy Object
RMI (java.rmi)
Starting Up the RMI Registry
Defining and Exporting a Remote Object
Looking Up a Remote Object and Invoking a Method
Passing Parameters to a Remote Method
Returning Values from a Remote Method
Throwing an Exception from a Remote Method
Sound
Sampled (javax.sound.sampled)
Loading and Playing Sampled Audio
Determining the File Format of a Sampled Audio File
Determining the Encoding of a Sampled Audio File
Determining the Duration of a Sampled Audio File
Playing Streaming Sampled Audio
Continuously Playing a Sampled Audio File
Determining the Position of a Sampled Audio Player
Determining When a Sampled Audio Player has
Finished Playing
Controlling the Volume of Playing Sampled Audio
Midi
http://developer.java.sun.com/developer/codesamples/ (8 of 13) [8/1/2000 7:46:26 AM]
Examplets from The Java Developers Almanac 2000
Loading and Playing Midi Audio
Determining the File Format of a MIdi Audio File
Determining the Duration of a Midi Audio File
Playing Streaming Midi Audio
Determining the Position of a Midi Sequencer
Determining When a Midi Audio Player has Finished
Playing
Controlling the Volume of Playing Midi Audio
Security (java.security)
Creating a New Key Pair and Self-signed Certificate
Creating and Signing a JAR File
Creating a New Policy File
Managing Policy Files
Creating a Keyed Digest Using MD5
Getting a Certificate from a Keystore
Checking Read/Write Permission for a Directory
Checking if One Permission Implies Another
Creating a Secure Random Number
Swing (javax.swing)
The Quintessential Swing User Interface
Centering a Frame on the Screen
Exiting an Application When a Frame Is Closed
Creating a Button
Creating a Checkbox Button
Creating a Color Chooser Dialog
Creating a ComboBox
Creating Image Radio Buttons
Retrieving the Selected Button in a Group
Firing Item Events
Creating a File Chooser Dialog
Displaying Only Directories in a File Chooser Dialog
Creating an Internal Frame
Creating a List Component
Creating a Scrolling List Component
Setting the Selection Mode of a List Component
Creating a Menu Bar, Menu, and Menu Item
Separating Menu Items in a Menu
Creating a Popup Menu
Creating a Progess Bar
Creating Radio Buttons
Creating a Scroll Pane
http://developer.java.sun.com/developer/codesamples/ (9 of 13) [8/1/2000 7:46:26 AM]
Examplets from The Java Developers Almanac 2000
Creating a Slider
Creating a Split Pane
Creating a Tabbed Pane
Creating a Text Field
Creating a Password Text Field
Creating a Table
Creating a Text Area
Displaying Simple HTML Files
Creating a Toolbar
Creating a Borderless Window
Showing a Dialog Box
Creating Key Strokes and Binding Them to Actions
Adding an InputMap to a Component
Setting a Tool Tip
Laying Out Components in a Row or Column
Separating Components in a Row or Column
Laying Out Components in a Flow (Left-to-Right,
Top-to-Bottom)
Laying Out Components in a Grid
Laying Out Components Using Absolute Coordinates
Setting a Border
Adding a Title to a Border
Creating a Compound Border
Determining the Available Look and Feels
Setting the Look and Feel
Painting the Background of a Container with an Image
Pattern
Events (javax.swing.event)
Handling Hyperlink Events
Handling Changes to a List Component
File Chooser (javax.swing.filechooser)
Adding a Filter to a File Chooser Dialog
Tree (javax.swing.tree)
Creating a Tree
Handling Selection Events in a Tree Component
Text (javax.swing.text)
Inserting Styled Text in a Text Pane
Inserting an Image into a Text Pane
Inserting a Component into a Text Pane
http://developer.java.sun.com/developer/codesamples/ (10 of 13) [8/1/2000 7:46:26 AM]
Examplets from The Java Developers Almanac 2000
java.lang
The Quintessential Java Application
Exiting a Java Program
The Quintessential Thread
Making an Object Cloneable
Constructing a String
Getting a Substring from a String
Searching a String
Replacing Characters in a String
Replacing Substrings in a String
Converting a String to Upper or Lower Case
Converting a String to a Number
Shifting Elements in an Array
Copying Elements from One Array to Another
Retrieving the SuperClass of an Object
Getting the Package of an Object
Implementing a Work Queue
Executes a Command
Reading Output from a Command
Sending Input to a Command
Pausing
Getting the Current Time
Getting the Value of a System Property
Setting the Value of a System Property
Using a Thread-local Variable
Loading Native Code
Converting Unicode to UTF-8
Converting UTF-8 to Unicode
Determining a Character's Unicode Block
JNDI
Creating an Initial Context to the Naming Service
Looking Up an Object From the Naming Service
Listing a Context in the Naming Service
Adding, Replacing, Removing, and Renaming a Binding in
the Naming Service
Creating and Destroying a Subcontext in the Naming
Service
Getting an Object's Fully Qualified Name
Using a URL as a Name to the Initial Context
Parsing a Composite Name
Parsing a Compound Name
Directory (javax.naming.directory)
http://developer.java.sun.com/developer/codesamples/ (11 of 13) [8/1/2000 7:46:26 AM]
Examplets from The Java Developers Almanac 2000
Creating an Initial Context to a Directory
Reading an Object's Attributes from the Directory
Modifying an Object's Attributes in the Directory
Creating an Directory Entry
Adding a Binding with Attributes to the Directory
Performing a Basic Directory Search
Searching the Directory By Using a Search Filter
Searching a Subtree in the Directory
Cancelling a Directory Search
Getting an Object's Schema from the Directory
Getting an Attribute's Schema from the Directory
Authenticating to the Directory
Event (javax.naming.event)
Registering for Namespace Changes in the Directory
Registering for Object Changes in the Directory
Ldap (javax.naming.ldap)
Setting LDAP Connection Request Controls
Setting LDAP Context Request Controls
Getting LDAP Response Controls
Performing an LDAP ``Extended'' Operation
javax.rmi
Starting the Name Server
Defining and Exporting a Portable Remote Object
Looking Up a Portable Remote Object and Invoking a
Method
javax.swing.undo
Adding Undo and Redo to a Text Component
These code examples and other materials are subject to Sun
Microsystems, Inc. Legal Terms
ExampletsSM provided by permission of the publisher, Addision-Wesley,
and Author Patrick Chan.
[ This page was updated: 31-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
http://developer.java.sun.com/developer/codesamples/ (12 of 13) [8/1/2000 7:46:26 AM]
Code Samples from the Java Developers Almanac 2000
javax.accessibility
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
The Quintessential Accessible Object
You should try to subclass from JComponent or one of its
descendents since that will automatically make your object
accessible. If that is not possible, your object should implement
Accessible.
import javax.accessibility.*;
public class BasicAccessible implements Accessible {
public AccessibleContext getAccessibleContext() {
return new AccessibleContext() {
// Implement all the abstract methods in this
// abstract class.
};
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.accessibility/174.html [8/1/2000 7:46:38 AM]
Code Samples from the Java Developers Almanac 2000
javax.accessibility
Code Samples Index
These code examples and other materials are subject to Sun Microsystems, Inc.
Legal Terms
Setting an Accessible Name for an Image Button
You should also set the accessible name for components that only
show an image. The tool tip text, if set, serves as the accessible
name for a component. However, if the tool tip text is being used for
something else, set the component's accessible name.
JButton button = new JButton(new ImageIcon("image.gif"));
button.setToolTipText("Button Name");
// If tool tip is being used for something else,
// set the accessible name.
button.getAccessibleContext().setAccessibleName(
"Button Name");
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.accessibility/175.html [8/1/2000 7:46:39 AM]
Code Samples from the Java Developers Almanac 2000
javax.accessibility
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Setting a Description for Image Icons
Image icons can be inserted in a variety of places such as in a text
or tree component. You should set a description for image icons to
help blind users.
ImageIcon icon = new ImageIcon("image.gif");
icon.setDescription("Description of Image");
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.accessibility/176.html [8/1/2000 7:46:40 AM]
Code Samples from the Java Developers Almanac 2000
javax.accessibility
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Setting a Mnemomic for Buttons
JButton button = new JButton("Button");
button.setMnemonic('B');
JCheckBox checkBox = new JCheckBox("CheckBox");
checkBox.setMnemonic('C');
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.accessibility/177.html [8/1/2000 7:46:41 AM]
Code Samples from the Java Developers Almanac 2000
javax.accessibility
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Setting a Mnemonic for a Menu
At least one menu in a menu bar should have a mnemonic. This
makes all the menus and menu items accessible.
JMenu menu = new JMenu("Menu");
menu.setMnemonic('M');
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.accessibility/178.html [8/1/2000 7:46:42 AM]
Code Samples from the Java Developers Almanac 2000
javax.accessibility
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Associating a Label with a Component
When a label is associated with a component, you should call
setLabelFor() to make the association explicit and then set a
mnemonic on the label. The associated component will get the
focus when the mnemonic is activated.
JLabel label = new JLabel("Name:");
label.setDisplayedMnemonic('N');
label.setLabelFor(component);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.accessibility/179.html [8/1/2000 7:46:43 AM]
Code Samples from the Java Developers Almanac 2000
javax.accessibility
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Setting a Keyboard Accelerator for a Menu Item
At least one menu in a menu bar should have a mnemonic. This
makes all the menus and menu items accessible.
JMenuItem item = new JMenuItem("Item");
//The next two lines should be in one line.
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.
VK_I, KeyEvent.SHIFT_MASK));
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.accessibility/180.html [8/1/2000 7:46:44 AM]
Code Samples from the Java Developers Almanac 2000
java.applet
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
The Quintessential Applet
Every applet must subclass Applet.
import java.applet.*;
import java.awt.*;
public class BasicApplet extends Applet {
public void init() {
// Called once by the browser when
// it starts the applet.
}
public void start() {
// Called whenever the page containing
// this applet is made visible.
}
public void stop() {
// Called whenever the page containing this
// applet is not visible.
}
public void destroyed() {
// Called once when the browser destroys
// this applet.
}
public void paint(Graphics g) {
// Called whenever this applet needs to
// repaint itself.
}
}
This is the applet's accompanying HTML file.
<applet code=BasicApplet width=100 height=100>
</applet>
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
http://developer.java.sun.com/developer/codesamples/java.applet/0.html (1 of 2) [8/1/2000 7:46:45 AM]
Code Samples from the Java Developers Almanac 2000
java.applet
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting an Applet Parameter
String s = getParameter("p");
Here is a sample HTML file containing a value for the parameter
\meta{p}.
<applet code=AppletClassName width=100 height=100>
<param name=p value="some text">
</applet>
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.applet/1.html [8/1/2000 7:46:46 AM]
Code Samples from the Java Developers Almanac 2000
java.applet
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Making the Browser Visit a URL
try {
// The following 2 lines of code must be
// on the same line
getAppletContext().showDocument(new URL(
getDocumentBase(), "http://hostname/page.html"));
} catch (MalformedURLException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.applet/2.html [8/1/2000 7:46:47 AM]
Code Samples from the Java Developers Almanac 2000
java.applet
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Showing a Message in the Browser's Status Bar
showStatus("Your Message Here");
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.applet/3.html [8/1/2000 7:46:48 AM]
Code Samples from the Java Developers Almanac 2000
java.applet
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Loading and Playing Audio in an Applet
// The following 2 lines of code must be
// on the same line
AudioClip ac = getAudioClip(getDocumentBase(),
"http://hostname/audio.au");
ac.play();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.applet/4.html [8/1/2000 7:46:49 AM]
Code Samples from the Java Developers Almanac 2000
java.applet
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Loading and Playing Audio in an Application
try {
URL url = new URL("http://hostname/audio.au");
AudioClip ac = Applet.newAudioClip(url);
ac.play();
} catch (MalformedURLException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.applet/5.html [8/1/2000 7:46:50 AM]
Code Samples from the Java Developers Almanac 2000
java.applet
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Loading and Painting an Image in an Applet
Image image;
public void init() {
image = getImage(getDocumentBase(),
"http://hostname/image.gif");
}
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.applet/6.html [8/1/2000 7:46:52 AM]
Code Samples from the Java Developers Almanac 2000
java.applet
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Animating an Array of Images in an Applet
This is the simplest applet to animate an array of images. In
practice, you should use double-buffering (which this example does
not use) to eliminate ``flickering.''
import java.applet.*;
import java.awt.*;
public class AnimApplet extends Applet
implements Runnable {
Image[] images = new Image[2];
int frame = 0;
volatile Thread thread;
public void init() {
images[0] = getImage(getDocumentBase(),
"http://hostname/image0.gif");
images[1] = getImage(getDocumentBase(),
"http://hostname/image1.gif");
}
public void start() {
(thread = new Thread(this)).start();
}
public void stop() {
thread = null;
}
public void paint(Graphics g) {
g.drawImage(images[frame], 0, 0, this);
}
public void run() {
int delay = 1000;
// 1 second
try {
while (thread == Thread.currentThread()) {
frame = (frame+1)%images.length;
repaint();
http://developer.java.sun.com/developer/codesamples/java.applet/7.html (1 of 2) [8/1/2000 7:46:56 AM]
Code Samples from the Java Developers Almanac 2000
Thread.sleep(delay);
}
} catch (Exception e) {
}
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 31-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.applet/7.html (2 of 2) [8/1/2000 7:46:56 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
The Quintessential Drawing Program
This example creates a frame and draws an oval within the frame.
import java.awt.*;
import javax.swing.*;
class BasicDraw extends JComponent {
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.drawOval(0, 0, getSize().width-1,
getSize().height-1);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new BasicDraw());
int frameWidth = 300;
int frameHeight = 300;
frame.setSize(frameWidth, frameHeight);
frame.setVisible(true);
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/java.awt/8.html (1 of 2) [8/1/2000 7:46:57 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Drawing Basic Shapes
There are two ways to draw basic shapes like lines and rectangles.
The first is to use specific drawing methods like
Graphics.drawOval(). This example uses these methods. The
second is to construct a shape and then use Graphics2D.draw() to
draw the shape. See the java.awt.geom package for examples that
create shapes.
g2d.drawLine(x1, y1, x2, y2);
g2d.drawArc(x, y, w, h, startAngle, arcAngle);
g2d.drawOval(x, y, w, h);
g2d.drawRect(x, y, w, h);
g2d.drawRoundRect(x, y, w, h, arcWidth, arcHeight);
Polygon polygon = new Polygon();
polygon.addPoint(x, y);
// ...continue adding points
g2d.drawPolygon(polygon);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt/9.html [8/1/2000 7:46:58 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Filling Basic Shapes
There are two ways to fill basic shapes like lines and rectangles.
The first is to use specific drawing methods like Graphics.fillOval().
This example uses these methods. The second is to construct a
shape and then use Graphics2D.fill() to fill the shape. See the
java.awt.geom package for examples that create shapes.
g2d.fillArc(x, y, w, h, startAngle, arcAngle);
g2d.fillOval(x, y, w, h);
g2d.fillRect(x, y, w, h);
g2d.fillRoundRect(x, y, w, h, arcWidth, arcHeight);
Polygon polygon = new Polygon();
polygon.addPoint(x, y);
// ...continue adding points
g2d.fillPolygon(polygon);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt/10.html [8/1/2000 7:46:59 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Loading an Image
// This call returns immediately and pixels
// are loaded in background.
// The following 2 lines of code must be
// on the same line
Image image = Toolkit.getDefaultToolkit().getImage(
"image.gif");
// This method ensures that all pixels have
// been loaded before returning.
image = new ImageIcon("image.gif").getImage();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt/11.html [8/1/2000 7:47:00 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Drawing an Image
public void paint(Graphics g) {
// Drawing an Image object.
g.drawImage(image, x, y, this);
// Drawing an ImageIcon object.
imageIcon.paintIcon(this, g, x, y);
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt/12.html [8/1/2000 7:47:02 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Scaling, Shearing, Translating, and Rotating a Drawn
Image
AffineTransform tx = new AffineTransform();
tx.scale(scalex, scaley);
tx.shear(shiftx, shifty);
tx.translate(x, y);
tx.rotate(radians);
g2d.drawImage(image, tx, this);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt/13.html [8/1/2000 7:47:03 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Drawing Simple Text
// Set the desired font if different from default font.
Font font = new Font("Serif", Font.PLAIN, 12);
g2d.setFont(font);
// Draw the string such that its base line is at x, y.
g2d.drawString("aString", x, y);
// Draw the string such that the top-left corner
// is at x, y.
FontMetrics fontMetrics = g2d.getFontMetrics();
g2d.drawString(
"aString", x, y+fontMetrics.getAscent());
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt/14.html [8/1/2000 7:47:04 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Drawing Rotated Text
// Draw string rotated clockwise 90 degrees.
AffineTransform at = new AffineTransform();
at.setToRotation(Math.PI/2.0);
g2d.setTransform(at);
g2d.drawString("aString", x, y);
// Draw string rotated counter-clockwise 90 degrees.
at = new AffineTransform();
at.setToRotation(-Math.PI/2.0);
g2d.setTransform(at);
g2d.drawString("aString", x, y);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt/15.html [8/1/2000 7:47:05 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting the Dimensions of Text
// From within the paint() method.
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
Font font = new Font("Serif", Font.PLAIN, 12);
FontMetrics fontMetrics = g2d.getFontMetrics();
int width = fontMetrics.stringWidth("aString");
int height = fontMetrics.getHeight();
}
// From within a component.
class MyComponent extends JComponent {
MyComponent() {
Font font = new Font("Serif", Font.PLAIN, 12);
FontMetrics fontMetrics = getFontMetrics(font);
int width = fontMetrics.stringWidth("aString");
int height = fontMetrics.getHeight();
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/java.awt/16.html (1 of 2) [8/1/2000 7:47:06 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Drawing Anti-Aliased Text and Graphics
// Text only
g2d.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
// Text and graphics
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawGraphics(g2d);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt/17.html [8/1/2000 7:47:07 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Drawing with Alpha
drawGraphic1(g2d);
// Set alpha. 0.0f is 100% transparent and 1.0f is
// 100% opaque.
float alpha = .7f;
g2d.setComposite(
AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, alpha));
drawGraphic2(g2d);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt/18.html [8/1/2000 7:47:09 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Setting the Clipping Area with a Shape
g2d.setClip(shape);
drawGraphics(g2d);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt/19.html [8/1/2000 7:47:10 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Changing the Thickness of the Stroking Pen
dashPhase is the offset to start the dashing pattern.
float strokeThickness = 5.0f;
// A solid stroke
BasicStroke stroke = new BasicStroke(strokeThickness);
g2d.setStroke(stroke);
drawShape(g2d);
// A dashed stroke
float miterLimit = 10f;
float[] dashPattern = {10f};
float dashPhase = 5f;
stroke = new BasicStroke(
strokeThickness, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, miterLimit,
dashPattern, dashPhase);
g2d.setStroke(stroke);
drawShape(g2d);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt/20.html [8/1/2000 7:47:12 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Shape from a Stroked Shape
float strokeThickness = 5.0f;
BasicStroke stroke = new BasicStroke(strokeThickness);
Shape newShape = stroke.createStrokedShape(shape);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt/21.html [8/1/2000 7:47:13 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Stroking or Filling a Shape
// Stroke the shape.
g2d.draw(shape);
// Fill the shape.
g2d.fill(shape);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt/22.html [8/1/2000 7:47:14 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Stroking or Filling with a Color
// Use a predefined color.
g2d.setColor(Color.red);
drawShape(g2d);
// Use a custom color.
int red = 230;
int green = 45;
int blue = 67;
g2d.setColor(new Color(red, green, blue));
drawShape(g2d);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt/23.html [8/1/2000 7:47:15 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Stroking or Filling with a Gradient Color
Color startColor = Color.red;
Color endColor = Color.blue;
// A non-cyclic gradient
GradientPaint gradient = new GradientPaint(
startX, startY, startColor,
endX, endY, endColor);
g2d.setPaint(gradient);
drawShape(g2d);
// A cyclic gradient
gradient = new GradientPaint(
startX, startY, startColor,
endX, endY, endColor, true);
g2d.setPaint(gradient);
drawShape(g2d);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt/24.html [8/1/2000 7:47:16 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Stroking or Filling with a Texture
The buffered image used to create the TexturePaint object is scaled
down/up to width w and height h. Conceptually, the scaled
down/up buffered image is first painted at (x, y) in user space, and
then replicated around it.
TexturePaint texture = new TexturePaint(
bufferedImage,
new Rectangle(x, y, 50/*w*/, 25/*h*/));
g2d.setPaint(texture);
drawShape(g2d);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt/25.html [8/1/2000 7:47:17 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Animating an Array of Images in an Application
This is the simplest application to animate a an array of images.
import java.awt.*;
import javax.swing.*;
public class AnimApp extends JComponent
implements Runnable {
Image[] images = new Image[2];
int frame = 0;
public void paint(Graphics g) {
Image image = images[frame];
if (image != null) {
g.drawImage(image, 0, 0, this);
}
}
public void run() {
images[0] = new ImageIcon(
"image1.gif").getImage();
images[1] = new ImageIcon(
"image2.gif").getImage();
int delay = 1000;
// 1 second
try {
while (true) {
frame = (frame+1)%images.length;
repaint();
Thread.sleep(delay);
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
http://developer.java.sun.com/developer/codesamples/java.awt/26.html (1 of 2) [8/1/2000 7:47:18 AM]
Code Samples from the Java Developers Almanac 2000
AnimApp app = new AnimApp();
JFrame frame = new JFrame();
frame.getContentPane().add(app);
frame.setSize(300, 300);
frame.setVisible(true);
(new Thread(app)).start();
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt/26.html (2 of 2) [8/1/2000 7:47:18 AM]
Code Samples from the Java Developers Almanac 2000
java.awt
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Setting a Component's Cursor
See the Cursor class for available cursors.
component.setCursor(Cursor.getPredefinedCursor(
Cursor.HAND_CURSOR));
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt/27.html [8/1/2000 7:47:19 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.datatransfer
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Retrieving Text from the System Clipboard
// The following 3 lines of code must be
// on the same line
Transferable t =
Toolkit.getDefaultToolkit().getSystemClipboard().
getContents(null);
try {
if (t != null && t.isDataFlavorSupported(
DataFlavor.stringFlavor)) {
String s = (String)t.getTransferData(
DataFlavor.stringFlavor);
process(s);
}
} catch (UnsupportedFlavorException e) {
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.datatransfer/32.html [8/1/2000 7:47:21 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.datatransfer
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Placing Text on the System Clipboard
StringSelection ss =
new StringSelection("aString");
// The following 2 lines of code must be
// on the same line
Toolkit.getDefaultToolkit().getSystemClipboard().
setContents(ss, null);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.datatransfer/33.html [8/1/2000 7:47:22 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.dnd
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Making a Component Draggable
This example demonstrates the code needed to make a component
draggable. The object being transferred in this example is a string.
// The following 3 lines of code must be
// on the same line
public class DraggableComponent extends JComponent
implements DragGestureListener,
DragSourceListener {
DragSource dragSource;
public DraggableComponent() {
dragSource = new DragSource();
dragSource.createDefaultDragGestureRecognizer(
this, DnDConstants.ACTION_COPY_OR_MOVE, this);
}
public void dragGestureRecognized(
DragGestureEvent evt) {
Transferable t = new StringSelection(
"aString");
dragSource.startDrag (
evt, DragSource.DefaultCopyDrop, t, this);
}
public void dragEnter(DragSourceDragEvent evt) {
// Called when the user is dragging this drag
// source and enters the drop target.
}
public void dragOver(DragSourceDragEvent evt) {
// Called when the user is dragging this drag
// source and moves over the drop target.
}
public void dragExit(DragSourceEvent evt) {
// Called when the user is dragging this drag
// source and leaves the drop target.
http://developer.java.sun.com/developer/codesamples/java.awt.dnd/34.html (1 of 2) [8/1/2000 7:47:23 AM]
Code Samples from the Java Developers Almanac 2000
}
public void dropActionChanged(
DragSourceDragEvent evt) {
// Called when the user changes the drag
// action between copy or move.
}
public void dragDropEnd(DragSourceDropEvent evt) {
// Called when the user finishes or cancels
// the drag operation.
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.dnd/34.html (2 of 2) [8/1/2000 7:47:23 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.dnd
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Making a Component a Drop Target
public class DropTargetComponent extends JComponent
implements DropTargetListener {
public DropTargetComponent() {
new DropTarget(this, this);
}
public void dragEnter(DropTargetDragEvent evt) {
// Called when the user is dragging and enters
// this drop target.
}
public void dragOver(DropTargetDragEvent evt) {
// Called when the user is dragging and moves
// over this drop target.
}
public void dragExit(DropTargetEvent evt) {
// Called when the user is dragging and
// leaves this drop target.
}
public void dropActionChanged(
DropTargetDragEvent evt) {
// Called when the user changes the drag
// action between copy or move.
}
public void drop(DropTargetDropEvent evt) {
// Called when the user finishes or cancels
// the drag operation.
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
http://developer.java.sun.com/developer/codesamples/java.awt.dnd/35.html (1 of 2) [8/1/2000 7:47:24 AM]
Code Samples from the Java Developers Almanac 2000
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.dnd/35.html (2 of 2) [8/1/2000 7:47:24 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.dnd
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Handling a Drop Event
The drop target in this example only accepts dropped String
objects. A drop target must implement DropTargetListener and
supply an implementation for drop().
public void drop(DropTargetDropEvent evt) {
try {
Transferable t = evt.getTransferable();
if (t.isDataFlavorSupported(
DataFlavor.stringFlavor)) {
evt.acceptDrop(
DnDConstants.ACTION_COPY_OR_MOVE);
String s = (String)t.getTransferData(
DataFlavor.stringFlavor);
evt.getDropTargetContext().dropComplete(true);
process(s);
} else {
evt.rejectDrop();
}
} catch (IOException e) {
evt.rejectDrop();
} catch (UnsupportedFlavorException e) {
evt.rejectDrop();
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
http://developer.java.sun.com/developer/codesamples/java.awt.dnd/36.html (1 of 2) [8/1/2000 7:47:25 AM]
Code Samples from the Java Developers Almanac 2000
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.dnd/36.html (2 of 2) [8/1/2000 7:47:25 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.event
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Handling Events with an Anonymous Class
If an event handler is specific to a component (that is, not shared
by other components), there is no need to declare a class to handle
the event. The event handler can be implemented using an
anonymous inner class. This example demonstrates an anonymous
inner class to handle key events for a component.
component.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
}
});
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.event/54.html [8/1/2000 7:47:26 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.event
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Handling Action Events
Action events are fired by subclasses of AbstractButton and
includes buttons, checkboxes, and menus.
AbstractButton button = new JButton("OK");
button.addActionListener(new MyActionListener());
public class MyActionListener implements
ActionListener {
public void actionPerformed(ActionEvent evt) {
// Determine which abstract button fired the
// event.
AbstractButton button = (
AbstractButton)evt.getSource();
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.event/55.html [8/1/2000 7:47:27 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.event
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Handling Key Presses
You can get the key that was pressed either as a key character
(which is a Unicode character) or as a key code (a special value
representing a particular key on the keyboard).
component.addKeyListener(new MyKeyListener());
public class MyKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
// Check for key characters.
if (evt.getKeyChar() == 'a') {
process(evt.getKeyChar());
}
// Check for key codes.
if (evt.getKeyCode() == KeyEvent.VK_HOME) {
process(evt.getKeyCode());
}
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.event/56.html [8/1/2000 7:47:29 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.event
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Handling Mouse Clicks
component.addMouseListener(new MyMouseListener());
public class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent evt) {
if ((evt.getModifiers() &
InputEvent.BUTTON1_MASK) != 0) {
processLeft(evt.getPoint());
}
if ((evt.getModifiers() &
InputEvent.BUTTON2_MASK) != 0) {
processMiddle(evt.getPoint());
}
if ((evt.getModifiers() &
InputEvent.BUTTON3_MASK) != 0) {
processRight(evt.getPoint());
}
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.event/57.html [8/1/2000 7:47:30 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.event
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Handling Mouse Motion
component.addMouseMotionListener(
new MyMouseMotionListener());
public class MyMouseMotionListener extends
MouseMotionAdapter {
public void mouseMoved(MouseEvent evt) {
// Process current position of cursor while
// all mouse buttons are up.
process(evt.getPoint());
}
public void mouseDragged(MouseEvent evt) {
// Process current position of cursor
// while mouse button is pressed.
process(evt.getPoint());
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.event/58.html [8/1/2000 7:47:30 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.event
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Detecting Double and Triple Clicks
component.addMouseListener(new MyMouseListener());
public class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 3) {
// triple-click
} else if (evt.getClickCount() == 2) {
// double-click
}
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.event/59.html [8/1/2000 7:47:31 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.event
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Handling Focus Changes
component.addFocusListener(new MyFocusListener());
public class MyFocusListener extends FocusAdapter {
public void focusGained(FocusEvent evt) {
// The component gained the focus.
}
public void focusLost(FocusEvent evt) {
// The component lost the focus.
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.event/60.html [8/1/2000 7:47:32 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.font
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Listing All Available Fonts
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String fontNames[] = ge.getAvailableFontFamilyNames();
for (int i=0; i<fontNames.length; i++) {
process(fontNames[i]);
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.font/37.html [8/1/2000 7:47:33 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.font
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Drawing a Paragraph of Text
In order to change the font of the text, you need to supply an
attributed string to the LineBreakMeasurer. See ``Drawing Text
with Mixed Styles'' for an example.
public void drawParagraph(Graphics2D g,
String paragraph, float width) {
LineBreakMeasurer linebreaker =
new LineBreakMeasurer(
new AttributedString(paragraph).getIterator(),
g.getFontRenderContext());
float y = 0.0f;
while (linebreaker.getPosition() <
paragraph.length()) {
TextLayout tl =
linebreaker.nextLayout(width);
y += tl.getAscent();
tl.draw(g, 0, y);
y += tl.getDescent() + tl.getLeading();
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/java.awt.font/38.html (1 of 2) [8/1/2000 7:47:35 AM]
Code Samples from the Java Developers Almanac 2000
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.font/38.html (2 of 2) [8/1/2000 7:47:35 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.font
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting the Shape from the Outline of Text
Shape getTextShape(
Graphics2D g2d, String str, Font font) {
TextLayout tl = new TextLayout(
str, font, g2d.getFontRenderContext());
return tl.getOutline(null);
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.font/39.html [8/1/2000 7:47:36 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.font
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Drawing Text with Mixed Styles
This example applies a new font and background color to a part of
the text. You can apply styles to as many parts of the text as you
need. See TextAttributes for available styles.
// Apply styles to text.
AttributedString astr =
new AttributedString("aString");
astr.addAttribute(
TextAttribute.FONT, font, start, end);
astr.addAttribute(
TextAttribute.BACKGROUND, color, start, end);
// Draw mixed-style text.
TextLayout tl = new TextLayout(
astr.getIterator(), g2d.getFontRenderContext());
tl.draw(g2d, x, y);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.font/40.html [8/1/2000 7:47:37 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.geom
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Shape with Lines and Curves
GeneralPath shape = new GeneralPath();
shape.moveTo(x, y);
shape.lineTo(x, y);
shape.quadTo(controlPointX, controlPointY, x, y);
shape.curveTo(controlPointX1, controlPointY1,
controlPointX2, controlPointY2, x, y);
shape.closePath();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.geom/41.html [8/1/2000 7:47:38 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.geom
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating Basic Shapes
Shape line = new Line2D.Float(x1, y1, x2, y2);
Shape arc = new Arc2D.Float(x, y, w,
h, start, extent, type);
Shape oval = new Ellipse2D.Float(x, y, w, h);
Shape rectangle = new Rectangle2D.Float(x, y, w, h);
Shape roundRectangle = new RoundRectangle2D.Float(x,
y, w, h, arcWidth, arcHeight);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.geom/42.html [8/1/2000 7:47:39 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.geom
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Combining Shapes
Area shape = new Area(shape1);
shape.add(new Area(shape2));
shape.subtract(new Area(shape3));
shape.intersect(new Area(shape4));
shape.exclusiveOr(new Area(shape5));
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.geom/43.html [8/1/2000 7:47:40 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.geom
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Scaling, Shearing, Translating, and Rotating a Shape
AffineTransform tx = new AffineTransform();
tx.scale(scalex, scaley);
tx.shear(shiftx, shifty);
tx.translate(x, y);
tx.rotate(radians);
Shape newShape = tx.createTransformedShape(shape);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.geom/44.html [8/1/2000 7:47:41 AM]
Code Samples from the Java Developers Almanac 2000
java.util.zip
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Compressing a File
This example creates a ZIP file with one entry.
try {
String inFilename = "infile";
String outFilename = "outfile.zip";
FileInputStream in = new FileInputStream(
inFilename);
ZipOutputStream out = new ZipOutputStream(
new FileOutputStream(outFilename));
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(inFilename));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
out.close();
in.close();
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
http://developer.java.sun.com/developer/codesamples/java.util.zip/169.html (1 of 2) [8/1/2000 7:47:42 AM]
Code Samples from the Java Developers Almanac 2000
java.util.zip
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Decompressing a File
This example reads a ZIP file and decompresses the first entry.
try {
String inFilename = "infile.zip";
String outFilename = "outfile";
ZipInputStream in = new ZipInputStream(
new FileInputStream(inFilename));
OutputStream out = new FileOutputStream(
outFilename);
ZipEntry entry;
byte[] buf = new byte[1024];
int len;
if ((entry = in.getNextEntry()) != null) {
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
out.close();
in.close();
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/java.util.zip/170.html (1 of 2) [8/1/2000 7:47:44 AM]
Code Samples from the Java Developers Almanac 2000
java.util.zip
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Listing the Contents of a ZIP File
try {
ZipFile zf = new ZipFile(filename);
for (Enumeration entries = zf.entries();
entries.hasMoreElements();) {
//The next three lines should be in one
//line
process(
((ZipEntry)entries.nextElement())
.getName());
}
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util.zip/171.html [8/1/2000 7:47:45 AM]
Code Samples from the Java Developers Almanac 2000
java.util.zip
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Calculating the Checksum of a Byte Array
public static long checksum(byte[] buf) {
try {
CheckedInputStream cis =
new CheckedInputStream(new
ByteArrayInputStream(buf),
new Adler32());
byte[] tempBuf = new byte[128];
while (cis.read(tempBuf) >= 0) {
}
return cis.getChecksum().getValue();
} catch (IOException e) {
return -1;
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util.zip/172.html [8/1/2000 7:47:45 AM]
Code Samples from the Java Developers Almanac 2000
java.util.jar
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Retrieving the Manifest of a JAR File
try {
JarFile jarfile = new JarFile(filename);
// Get manifest and write its contents
jarfile.getManifest().write(System.out);
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util.jar/173.html [8/1/2000 7:47:46 AM]
Code Samples from the Java Developers Almanac 2000
java.sql
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Connecting to a Database
This example uses the JDBC-ODBC bridge to connect to a database
called ``mydatabase''.
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:mydatabase";
Connection connection =
DriverManager.getConnection(
url, "login", "password");
} catch (ClassNotFoundException e) {
} catch (SQLException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.sql/140.html [8/1/2000 7:47:47 AM]
Code Samples from the Java Developers Almanac 2000
java.sql
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Database Table
This example creates a table called ``mytable'' with three
columns: COL_A which holds strings, COL_B which holds integers,
and COL_C which holds floating point numbers.
try {
Statement stmt =
connection.createStatement();
stmt.executeUpdate("CREATE TABLE mytable (
COL_A VARCHAR(100), COL_B INTEGER, COL_C FLOAT)");
} catch (SQLException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.sql/141.html [8/1/2000 7:47:48 AM]
Code Samples from the Java Developers Almanac 2000
java.sql
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Entering a New Row into a Database Table
This example enters a row containing a string, an integer, and a
floating point number into the table called ``mytable''.
try {
Statement stmt = connection.createStatement();
stmt.executeUpdate("INSERT INTO mytable
VALUES ('Patrick Chan', 123, 1.23)");
connection.close();
} catch (SQLException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.sql/142.html [8/1/2000 7:47:49 AM]
Code Samples from the Java Developers Almanac 2000
java.sql
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting All Rows from a Database Table
This example retrieves all the rows from a table called ``mytable''.
A row in ``mytable'' consists of a string, integer, and floating point
number.
try {
Statement stmt = connection.createStatement();
// Get data using colunm names.
ResultSet rs = stmt.executeQuery(
"SELECT * FROM mytable");
while (rs.next()) {
String s = rs.getString("COL_A");
int i = rs.getInt("COL_B");
float f = rs.getFloat("COL_C");
process(s, i, f);
}
// Get data using colunm numbers.
rs = stmt.executeQuery(
"SELECT * FROM mytable");
while (rs.next()) {
String s = rs.getString(1);
int i = rs.getInt(2);
float f = rs.getFloat(3);
process(s, i, f);
}
} catch (SQLException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
http://developer.java.sun.com/developer/codesamples/java.sql/143.html (1 of 2) [8/1/2000 7:47:51 AM]
Code Samples from the Java Developers Almanac 2000
java.sql
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting Particular Rows from a Database Table
This example retrieves all rows from a table called ``mytable''
whose column COL_A equals ``Patrick Chan''. A row in ``mytable''
consists of a string, integer, and floating point number.
try {
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(
"SELECT * FROM mytable WHERE COL_A =
'Patrick Chan'");
rs.next();
String s = rs.getString("COL_A");
int i = rs.getInt("COL_B");
float f = rs.getFloat("COL_C");
process(s, i, f);
} catch (SQLException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.sql/144.html [8/1/2000 7:47:52 AM]
Code Samples from the Java Developers Almanac 2000
java.sql
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Updating a Row of Data in a Database Table
This example updates a row in a table called ``mytable''. In
particular, for all rows whose column COL_B equals 123, column
COL_A is set to ``John Doe''.
try {
Statement stmt = connection.createStatement();
int numUpdated = stmt.executeUpdate(
"UPDATE mytable SET COL_A =
'John Doe' WHERE COL_B = 123");
connection.close();
} catch (SQLException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.sql/145.html [8/1/2000 7:47:53 AM]
Code Samples from the Java Developers Almanac 2000
java.sql
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Using a Prepared SQL Statement
A prepared statement should be used in cases where a particular
SQL statement is used frequently. The prepared statement is more
expensive to set up but executes faster than a statement. This
example demonstrates a prepared statement for getting all rows
from a table called ``mytable'' whose column COL_A equals
``Patrick Chan''. This example also demonstrates a prepared
statement for updating data in the table. In particular, for all rows
whose column COL_B equals 123, column COL_A is set to ``John
Doe''.
try {
// Retrieving rows from the database.
PreparedStatement stmt =
connection.prepareStatement(
"SELECT * FROM mytable WHERE COL_A = ?");
int colunm = 1;
stmt.setString(colunm, "Patrick Chan");
ResultSet rs = stmt.executeQuery();
// Updating the database.
stmt = connection.prepareStatement(
"UPDATE mytable SET COL_A =
? WHERE COL_B = ?");
colunm = 1;
stmt.setString(colunm, "John Doe");
colunm = 2;
stmt.setInt(colunm, 123);
int numUpdated = stmt.executeUpdate();
} catch (SQLException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
http://developer.java.sun.com/developer/codesamples/java.sql/146.html (1 of 2) [8/1/2000 7:47:54 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Set
Set set = new HashSet();
// hash table
set = new TreeSet();
// sorted set
// Some operations.
set.add(value);
boolean b = set.contains(value);
set.remove(value);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util/147.html [8/1/2000 7:47:55 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a List
// doubly-linked list
List list = new LinkedList();
// list implemented as growable array
list = new ArrayList();
// Some operations.
list.add(value);
list.get(0);
list.remove(value);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util/148.html [8/1/2000 7:47:57 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Hash Table
Map map = new HashMap();
// hash table
map = new TreeMap();
// sorted map
// Some operations.
map.put(key, value);
value = map.get(key);
map.remove(key);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util/149.html [8/1/2000 7:47:58 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Truncating a List
list.subList(index, list.size()).clear();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util/150.html [8/1/2000 7:47:59 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Converting a Collection to an Array
Object[] objectArray = list.toArray();
AnObject[] array = (AnObject[])list.toArray(
new AnObject[list.size()]);
objectArray = set.toArray();
array = (AnObject[])set.toArray(
new AnObject[set.size()]);
objectArray = map.keySet().toArray();
array = (AnObject[])map.keySet().toArray(
new AnObject[set.size()]);
objectArray = map.values().toArray();
array = (AnObject[])map.values().toArray(
new AnObject[set.size()]);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util/151.html [8/1/2000 7:48:00 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Converting an Array to a Collection
// Ungrowable list.
List list = Arrays.asList(array);
// Growable list.
list = new LinkedList(Arrays.asList(array));
// Duplicate elements are discarded.
Set set = new HashSet(Arrays.asList(array));
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util/152.html [8/1/2000 7:48:01 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Implementing a Queue
LinkedList queue = new LinkedList();
// Add to end of queue.
queue.add(object);
// Get head of queue.
Object o = queue.removeFirst();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util/153.html [8/1/2000 7:48:02 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Implementing a Stack
LinkedList stack = new LinkedList();
// Push on top of stack.
stack.addFirst(object);
// Pop off top of stack.
Object o = stack.getFirst();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util/154.html [8/1/2000 7:48:03 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Iterating the Elements of a Collection
// For sets and lists
for (Iterator it=collection.iterator();
it.hasNext(); ) {
process(it.next());
}
// For keys of a map
for (Iterator it=map.keySet().iterator();
it.hasNext(); ) {
process(it.next());
}
// For values of a map
for (Iterator it=map.values().iterator();
it.hasNext(); ) {
process(it.next());
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/java.util/155.html (1 of 2) [8/1/2000 7:48:04 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Sorting an Array
int[] intArray = new int[] {4, 1, 3, -23};
Arrays.sort(intArray);
String[] strArray = new String[] {"z", "a", "C"};
Arrays.sort(strArray);
// Case-insensitive sort.
Arrays.sort(strArray,
String.CASE_INSENSITIVE_ORDER);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util/156.html [8/1/2000 7:48:06 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Finding an Element in a Sorted Array
This example also works if the object is a primitive type.
int index = Arrays.binarySearch(
sortedArray, object);
if (index < 0) {
// not found
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util/157.html [8/1/2000 7:48:07 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Finding an Element in a Sorted List
int index = Collections.binarySearch(
sortedList, object);
if (index < 0) {
// not found
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util/158.html [8/1/2000 7:48:08 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Inserting an Element into a Sorted List
int index = Collections.binarySearch(
sortedList, object);
if (index < 0) {
sortedList.add(-index-1, object);
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util/159.html [8/1/2000 7:48:09 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Generating a Random Number
Random rand = new Random();
int rnum = rand.nextInt();
// Continually call nextInt() for more random
//integers.
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util/160.html [8/1/2000 7:48:10 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Breaking a String into Words
String aString = "word1 word2 word3";
StringTokenizer parser =
new StringTokenizer(aString);
while (parser.hasMoreTokens()) {
processWord(parser.nextToken());
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util/161.html [8/1/2000 7:48:11 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Reading Properties from a Properties File
A properties filename has the form ``basename_locale.properties''.
You only pass the string ``basename'' to getBundle().
ResourceBundle bundle =
ResourceBundle.getBundle("basename");
// Enumerate contents of resource bundle
//The next two lines should be in one line.
for (Enumeration props = bundle.getKeys();
props.hasMoreElements(); ) {
String key = (String)props.nextElement();
process(key, bundle.getObject(key));
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util/162.html [8/1/2000 7:48:12 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating Date Object From a Particular Date
Calendar xmas = new GregorianCalendar(
1998, Calendar.DECEMBER, 25);
Date date = xmas.getTime();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util/163.html [8/1/2000 7:48:14 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Parsing a Date Using a Pattern
try {
SimpleDateFormat formatter =
new SimpleDateFormat("EEEE, MMMM dd, yyyy");
Date d = formatter.parse(
"Tuesday, January 03, 1956");
formatter = new SimpleDateFormat(
"EE, MMM d, yy");
d = formatter.parse("Tue, Jan 3, 56");
formatter = new SimpleDateFormat(
"EE, MM d, yy");
d = formatter.parse("Tue, 01 3, 56");
process(d);
} catch (ParseException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/java.util/164.html (1 of 2) [8/1/2000 7:48:15 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Reading and Writing a Properties File
// Read properties file.
Properties properties = new Properties();
try {
properties.load(new FileInputStream(
"infilename"));
} catch (IOException e) {
}
// Write properties file.
try {
properties.store(new FileOutputStream(
"outfilename"), null);
} catch (IOException e) {
}
Here is an example of the contents of a properties file:
# a comment
! a comment
a = a string
b = a string with escape sequences \t
\n \r \\ \" \' \ (space) \u0123
c = a string with a continuation line \
contination line
d.e.f = another string
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
http://developer.java.sun.com/developer/codesamples/java.util/165.html (1 of 2) [8/1/2000 7:48:16 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting and Setting Properties
String string = properties.getProperty("a.b");
properties.setProperty("a.b", "new value");
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util/166.html [8/1/2000 7:48:17 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Scheduling a Timer Task to Run at a Certain Time
Date timeToRun =
new Date(System.currentTimeMillis()+
numberOfMillisecondsInTheFuture);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
// Task here
}
}, timeToRun);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util/167.html [8/1/2000 7:48:19 AM]
Code Samples from the Java Developers Almanac 2000
java.util
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Scheduling a Timer Task to Run Repeatedly
// delay for 5 sec.
int delay = 5000;
// repeat every sec.
int period = 1000;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
// Task here
}
}, delay, period);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.util/168.html [8/1/2000 7:48:20 AM]
Code Samples from the Java Developers Almanac 2000
java.io
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Constructing a Path
On Windows, this example creates the path \blash a\blash b. On
Unix, the path would be /a/b.
String path = File.separator + "a" + File.separator
+ "b";
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.io/258.html [8/1/2000 7:48:21 AM]
Code Samples from the Java Developers Almanac 2000
java.io
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Reading Text from Standard Input
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String str = "";
while (str != null) {
System.out.print("> prompt ");
str = in.readLine();
process(str);
}
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.io/259.html [8/1/2000 7:48:22 AM]
Code Samples from the Java Developers Almanac 2000
java.io
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Reading Text from a File
try {
BufferedReader in = new BufferedReader(
new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null) {
process(str);
}
in.close();
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 31-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.io/260.html [8/1/2000 7:48:23 AM]
Code Samples from the Java Developers Almanac 2000
java.io
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Writing to a File
If the file does not already exist, it is automatically created.
try {
BufferedWriter out = new BufferedWriter(
new FileWriter("outfilename"));
out.write("aString");
out.close();
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.io/261.html [8/1/2000 7:48:24 AM]
Code Samples from the Java Developers Almanac 2000
java.io
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Directory
(new File("directoryName")).mkdir();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.io/262.html [8/1/2000 7:48:25 AM]
Code Samples from the Java Developers Almanac 2000
java.io
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Appending to a File
try {
BufferedWriter out = new BufferedWriter(
new FileWriter("filename", true));
out.write("aString");
out.close();
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.io/263.html [8/1/2000 7:48:26 AM]
Code Samples from the Java Developers Almanac 2000
java.io
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Deleting a File
(new File("filename")).delete();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.io/264.html [8/1/2000 7:48:27 AM]
Code Samples from the Java Developers Almanac 2000
java.io
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Deleting a Directory
(new File("directoryName")).delete();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.io/265.html [8/1/2000 7:48:28 AM]
Code Samples from the Java Developers Almanac 2000
java.io
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Temporary File
try {
// Create temp file.
File temp = File.createTempFile(
"pattern", ".suffix");
// Delete temp file when program exits.
temp.deleteOnExit();
// Write to temp file
BufferedWriter out = new BufferedWriter(
new FileWriter(temp));
out.write("aString");
out.close();
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.io/266.html [8/1/2000 7:48:30 AM]
Code Samples from the Java Developers Almanac 2000
java.io
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Using a Random Access File
try {
File f = new File("filename");
RandomAccessFile raf = new RandomAccessFile(f, "rw");
// Read a character.
char ch = raf.readChar();
// Seek to end of file.
raf.seek(f.length());
// Append to the end.
raf.writeChars("aString");
raf.close();
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.io/267.html [8/1/2000 7:48:32 AM]
Code Samples from the Java Developers Almanac 2000
java.io
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Listing the File System Roots
UNIX file systems have a single root, "/". On Windows, each drive
is a root. For example the C drive is represented by the root
"C:\blash{}".
File[] roots = File.listRoots();
for (int i=0; i<roots.length; i++) {
process(roots[i]);
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.io/268.html [8/1/2000 7:48:34 AM]
Code Samples from the Java Developers Almanac 2000
java.io
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Setting File Modification Time
This example sets the modified time of a file to the current time.
File file = new File("filename");
boolean success = file.setLastModified(
System.currentTimeMillis());
if (!success) {
// operation failed.
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.io/269.html [8/1/2000 7:48:34 AM]
Code Samples from the Java Developers Almanac 2000
java.io
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Serializing an Object
The object to be serialized must implement java.io.Serializable.
try {
ObjectOutput out = new ObjectOutputStream(
new FileOutputStream("filename.ser"));
out.writeObject(object);
out.close();
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.io/270.html [8/1/2000 7:48:36 AM]
Code Samples from the Java Developers Almanac 2000
java.io
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Deserializing an Object
This example deserializes a java.awt.Button object.
try {
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("filename.ser"));
AnObject object = (AnObject) in.readObject();
in.close();
} catch (ClassNotFoundException e) {
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.io/271.html [8/1/2000 7:48:37 AM]
Code Samples from the Java Developers Almanac 2000
java.io
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Traversing a Directory
public static void traverse(File f) {
process(f);
if (f.isDirectory()) {
String[] children = f.list();
for (int i=0; i<children.length; i++) {
traverse(new File(f, children[i]));
}
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.io/272.html [8/1/2000 7:48:38 AM]
Code Samples from the Java Developers Almanac 2000
java.io
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Reading UTF-8 Encoded Data
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(
new FileInputStream(
"infilename"), "UTF8"));
String str = in.readLine();
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.io/273.html [8/1/2000 7:48:39 AM]
Code Samples from the Java Developers Almanac 2000
java.io
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Writing UTF-8 Encoded Data
try {
Writer out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(
"outfilename"), "UTF8"));
out.write(aString);
out.close();
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.io/274.html [8/1/2000 7:48:40 AM]
Code Samples from the Java Developers Almanac 2000
java.io
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Reading ISO Latin-1 Encoded Data
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream(
"infilename"), "8859_1"));
String str = in.readLine();
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.io/275.html [8/1/2000 7:48:41 AM]
Code Samples from the Java Developers Almanac 2000
java.io
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Writing ISO Latin-1 Encoded Data
try {
Writer out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(
"outfilename"), "8859_1"));
out.write(aString);
out.close();
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.io/276.html [8/1/2000 7:48:42 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.image
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Converting an Image to a Buffered Image
BufferedImage toBufferedImage(Image image) {
// This code ensures that all the pixels in
// the image are loaded.
image = new ImageIcon(image).getImage();
// Create the buffered image.
BufferedImage bufferedImage = new BufferedImage(
image.getWidth(null), image.getHeight(null),
BufferedImage.TYPE_INT_RGB);
// Copy image to buffered image.
Graphics g = bufferedImage.createGraphics();
// Clear background and paint the image.
g.setColor(Color.white);
g.fillRect(0, 0, image.getWidth(null),
image.getHeight(null));
g.drawImage(image, 0, 0, null);
g.dispose();
return bufferedImage;
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/java.awt.image/45.html (1 of 2) [8/1/2000 7:48:43 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.image
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting Pixels from a Buffered Image
// Get one pixel.
int rgb = bufferedImage.getRGB(x, y);
// Get all the pixels.
int w = bufferedImage.getWidth(null);
int h = bufferedImage.getHeight(null);
int[] rgbs = new int[w*h];
bufferedImage.getRGB(0, 0, w, h, rgbs, 0, w);
// Set a pixel.
rgb = 0xFF00FF00; // green
bufferedImage.setRGB(x, y, rgb);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.image/46.html [8/1/2000 7:48:45 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.image
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting a Sub-Image of an Image
// From an Image.
image = createImage(new FilteredImageSource(
image.getSource(), new CropImageFilter(x, y, w, h)));
// From a BufferedImage.
bufferedImage = bufferedImage.getSubimage(x, y, w, h);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.image/47.html [8/1/2000 7:48:46 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.image
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating and Drawing on a Buffered Image
// Creating a BufferedImage with a component.
bufferedImage =
(BufferedImage)component.createImage(w, h);
// Creating a BufferedImage without a component.
bufferedImage = new BufferedImage(
w, h, BufferedImage.TYPE_INT_RGB);
// Draw on the image.
Graphics2D g2d = bufferedImage.createGraphics();
drawGraphics(g2d);
g2d.dispose();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.image/48.html [8/1/2000 7:48:47 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.image
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Scaling, Shearing, Translating, and Rotating an Image
AffineTransform tx = new AffineTransform();
tx.scale(scalex, scaley);
tx.shear(shiftx, shifty);
tx.translate(x, y);
tx.rotate(radians, bufferedImage.getWidth()/2,
bufferedImage.getHeight()/2);
AffineTransformOp op = new AffineTransformOp(
tx, AffineTransformOp.TYPE_BILINEAR);
bufferedImage = op.filter(bufferedImage, null);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.image/49.html [8/1/2000 7:48:49 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.image
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Converting a Color Image to Gray
ColorSpace cs = ColorSpace.getInstance(
ColorSpace.CS_GRAY);
ColorConvertOp op = new ColorConvertOp(cs, null);
bufferedImage = op.filter(bufferedImage, null);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.image/50.html [8/1/2000 7:48:50 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.image
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Blurring an Image
This example demonstrates a 3x3 kernel that blurs an image.
Kernel kernel = new Kernel(3, 3, new float[] {
1f/9f, 1f/9f, 1f/9f,
1f/9f, 1f/9f, 1f/9f,
1f/9f, 1f/9f, 1f/9f});
BufferedImageOp op = new ConvolveOp(kernel);
bufferedImage = op.filter(bufferedImage, null);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.image/51.html [8/1/2000 7:48:51 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.image
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Sharpening an Image
This example demonstrates a 3x3 kernel that sharpens an image.
Kernel kernel = new Kernel(3, 3,
new float[] {
-1, -1, -1,
-1, 9, -1,
-1, -1, -1});
BufferedImageOp op = new ConvolveOp(kernel);
bufferedImage = op.filter(bufferedImage, null);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.image/52.html [8/1/2000 7:48:52 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.image
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Embossing an Image
This example demonstrates a 3x3 kernel that embosses an image.
Kernel kernel = new Kernel(3, 3,
new float[] {
-2, 0, 0,
0, 1, 0,
0, 0, 2});
BufferedImageOp op = new ConvolveOp(kernel);
bufferedImage = op.filter(bufferedImage, null);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.image/53.html [8/1/2000 7:48:53 AM]
Code Samples from the Java Developers Almanac 2000
java.text
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Formatting and Parsing a Locale-specific Number
// Format
Locale locale = Locale.CANADA;
String string = NumberFormat.getNumberInstance(
locale).format(123.45);
// Parse
try {
Number number = NumberFormat.getNumberInstance(
locale).parse("123.45");
if (number instanceof Long) {
// Long value
} else {
// Double value
}
} catch (ParseException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 31-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.text/237.html [8/1/2000 7:48:54 AM]
Code Samples from the Java Developers Almanac 2000
java.text
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Formatting and Parsing Locale-specific Currency
// Format
Locale locale = Locale.CANADA;
String string = NumberFormat.getCurrencyInstance(
locale).format(123.45);
// Parse
try {
Number number =
NumberFormat.getCurrencyInstance(
locale).parse("$123.45");
if (number instanceof Long) {
// Long value
} else {
// Double value
}
} catch (ParseException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.text/238.html [8/1/2000 7:48:55 AM]
Code Samples from the Java Developers Almanac 2000
java.text
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Formatting and Parsing a Locale-specific Percentage
// Format
Locale locale = Locale.CANADA;
String string = NumberFormat.getPercentInstance(
locale).format(123.45);
// Parse
try {
Number number = NumberFormat.getPercentInstance(
locale).parse("123.45%");
if (number instanceof Long) {
// Long value
} else {
// Double value
}
} catch (ParseException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.text/239.html [8/1/2000 7:49:01 AM]
Code Samples from the Java Developers Almanac 2000
java.text
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Formatting and Parsing a Locale-specific Date
// Format
Locale locale = Locale.FRENCH;
Date date = new Date();
String string = DateFormat.getDateInstance(
DateFormat.DEFAULT, locale).format(date);
// Parse
try {
//The next three lines should be in one line.
date = DateFormat.getDateInstance(
DateFormat.DEFAULT, locale).parse(
"15 nov. 98");
} catch (ParseException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.text/240.html [8/1/2000 7:49:02 AM]
Code Samples from the Java Developers Almanac 2000
java.text
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Formatting and Parsing Locale-specific Time
// Format
Locale locale = Locale.FRENCH;
Date date = new Date();
String string = DateFormat.getTimeInstance(
DateFormat.DEFAULT, locale).format(date);
// Parse
try {
date = DateFormat.getTimeInstance(
DateFormat.DEFAULT, locale).parse("01:37:11");
} catch (ParseException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.text/241.html [8/1/2000 7:49:03 AM]
Code Samples from the Java Developers Almanac 2000
java.text
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Formatting and Parsing a Locale-specific Date and
Time
// Format
Locale locale = Locale.ITALIAN;
Date date = new Date();
String string = DateFormat.getDateTimeInstance(
DateFormat.DEFAULT,
DateFormat.DEFAULT, locale).format(date);
// Parse
try {
date = DateFormat.getDateTimeInstance(
DateFormat.DEFAULT,
DateFormat.DEFAULT, locale).parse(
"15-nov-98 1.45.12");
} catch (ParseException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.text/242.html [8/1/2000 7:49:04 AM]
Code Samples from the Java Developers Almanac 2000
java.text
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining the Type of a Character
You should use the methods in the class Character to determine
the properties of a character. These methods work for the entire
Unicode character set.
char ch = 'a';
if (Character.isLetter(ch)) {
} else if (Character.isDigit(ch)) {
} else if (Character.isLowerCase(ch)) {
} else if (Character.isUpperCase(ch)) {
}
// See Character for more methods.
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.text/243.html [8/1/2000 7:49:05 AM]
Code Samples from the Java Developers Almanac 2000
java.text
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Comparing Strings in a Locale-independent Way
Collator collator = Collator.getInstance(
Locale.CANADA);
int compare = collator.compare(aString1, aString2);
if (compare < 0) {
// aString1 < aString2
} else if (compare > 1) {
// aString1 > aString2
} else {
// aString1 = aString2
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.text/244.html [8/1/2000 7:49:05 AM]
Code Samples from the Java Developers Almanac 2000
java.text
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining the Character Boundaries in a Unicode
String
BreakIterator iterator =
BreakIterator.getCharacterInstance(Locale.CANADA);
iterator.setText("aString");
for (int index=iterator.first(); index !=
BreakIterator.DONE; index=iterator.next()) {
process(index);
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.text/245.html [8/1/2000 7:49:06 AM]
Code Samples from the Java Developers Almanac 2000
java.text
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining the Word Boundaries in a Unicode String
The word break iterator finds both the beginning and end of words.
BreakIterator iterator =
BreakIterator.getWordInstance(Locale.CANADA);
iterator.setText("a sentence");
for (int index=iterator.first(); index !=
BreakIterator.DONE;
index=iterator.next()) {
process(index);
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.text/246.html [8/1/2000 7:49:07 AM]
Code Samples from the Java Developers Almanac 2000
java.text
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining the Sentence Boundaries in a Unicode
String
BreakIterator iterator =
BreakIterator.getSentenceInstance(Locale.CANADA);
iterator.setText("A sentence. Another
sentence.");
for (int index=iterator.first();
index != BreakIterator.DONE;
index=iterator.next()) {
process(index);
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 26-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.text/247.html [8/1/2000 7:49:08 AM]
Code Samples from the Java Developers Almanac 2000
java.text
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining Potential Line Breaks in a Unicode String
BreakIterator iterator =
BreakIterator.getLineInstance(Locale.CANADA);
iterator.setText("line1\nline2");
for (int index=iterator.first(); index !=
BreakIterator.DONE; index=iterator.next()) {
process(index);
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.text/248.html [8/1/2000 7:49:10 AM]
Code Samples from the Java Developers Almanac 2000
java.beans
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
The Quintessential Bean
This example bean has a single property called ``property''. If the
property were not a boolean, it would not have an is\meta{X()}
method. Also, if the property were read-only, it would not have a
set\meta{X()} method.
import java.io.Serializable;
public class BasicBean implements Serializable {
boolean property;
public BasicBean() {
}
public boolean getProperty() {
return property;
}
public boolean isProperty() {
return property;
}
public void setProperty(boolean newValue) {
property = newValue;
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/java.beans/67.html (1 of 2) [8/1/2000 7:49:11 AM]
Code Samples from the Java Developers Almanac 2000
java.beans
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Implementing a Bound Property
Bound properties fire a PropertyChangeEvent whenever its value is
changed. This example bean implements a single bound integer
property called ``property''.
int property;
public int getProperty() {
return property;
}
public void setProperty(
int newValue) {
property = newValue;
pceListeners.firePropertyChange(
"property"
,new Integer(property),
new Integer(newValue));
}
// Create the listener list.
PropertyChangeSupport pceListeners =
new PropertyChangeSupport(this);
// The listener list wrapper methods.
public synchronized void addPropertyChangeListener(
PropertyChangeListener listener) {
pceListeners.addPropertyChangeListener(listener);
}
public synchronized void removePropertyChangeListener(
PropertyChangeListener listener) {
pceListeners.removePropertyChangeListener(
listener);
}
http://developer.java.sun.com/developer/codesamples/java.beans/68.html (1 of 2) [8/1/2000 7:49:12 AM]
Code Samples from the Java Developers Almanac 2000
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.beans/68.html (2 of 2) [8/1/2000 7:49:12 AM]
Code Samples from the Java Developers Almanac 2000
java.beans
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Implementing a Constrained Property
Constrained properties fire a PropertyChangeEvent whenever its
value is about to be changed. Any listener can veto the event,
thereby preventing the change. This example bean implements a
single constrained integer property called ``property.''
int property;
public int getProperty() {
return property;
}
public void setProperty(int newValue) throws
PropertyVetoException {
try {
vceListeners.fireVetoableChange(
"property",
new Integer(property),
new Integer(newValue));
property = newValue;
} catch (PropertyVetoException e) {
throw e;
}
}
// Create the listener list.
VetoableChangeSupport vceListeners =
new VetoableChangeSupport(this);
// The listener list wrapper methods.
public synchronized void
addVetoableChangeListener(
VetoableChangeListener listener) {
vceListeners.addVetoableChangeListener(
listener);
}
public synchronized void
removeVetoableChangeListener(
http://developer.java.sun.com/developer/codesamples/java.beans/69.html (1 of 2) [8/1/2000 7:49:13 AM]
Code Samples from the Java Developers Almanac 2000
VetoableChangeListener
listener) {
vceListeners.removeVetoableChangeListener(
listener);
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 31-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.beans/69.html (2 of 2) [8/1/2000 7:49:13 AM]
Code Samples from the Java Developers Almanac 2000
java.beans
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Instantiating a Bean
try {
MyBean bean = (MyBean)Beans.instantiate(
ClassLoader.getSystemClassLoader(), "MyBean");
} catch (ClassNotFoundException e) {
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.beans/70.html [8/1/2000 7:49:14 AM]
Code Samples from the Java Developers Almanac 2000
java.beans
Code Samples Index
These code examples and other materials are subject to Sun Microsystems, Inc.
Legal Terms
Handling a Property Change Event
Property change events are fired when a bound property is changed.
bean.addPropertyChangeListener(
new MyPropertyChangeListener());
class MyPropertyChangeListener implements
PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
Object oldValue = evt.getOldValue();
Object newValue = evt.getNewValue();
process(oldValue, newValue);
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.beans/71.html [8/1/2000 7:49:15 AM]
Code Samples from the Java Developers Almanac 2000
java.beans
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Handling a Vetoable Property Change Event
Vetoable property change events are fired when a constrained
property is changed. A listener can veto the change by throwing
PropertyVetoException.
bean.addVetoableChangeListener(
new MyVetoableChangeListener());
class MyVetoableChangeListener implements
VetoableChangeListener {
public void vetoableChange(PropertyChangeEvent evt)
throws PropertyVetoException {
Object oldValue = evt.getOldValue();
Object newValue = evt.getNewValue();
if (!process(oldValue, newValue)) {
throw new PropertyVetoException(
"message", evt);
}
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.beans/72.html [8/1/2000 7:49:16 AM]
Code Samples from the Java Developers Almanac 2000
java.math
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Operating With Big Integer Values
// Create via a string.
BigInteger bi1 = new BigInteger(
"1234567890123456890");
// Create via a long.
BigInteger bi2 = BigInteger.valueOf(123);
bi1
bi1
bi1
bi1
bi1
int
bi1
= bi1.add(bi2);
= bi1.multiply(bi2);
= bi1.subtract(bi2);
= bi1.divide(bi2);
= bi1.negate();
exponent = 2;
= bi1.pow(exponent);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.math/123.html [8/1/2000 7:49:18 AM]
Code Samples from the Java Developers Almanac 2000
java.math
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Operating With Big Decimal Values
// Create via a string.
BigDecimal bd1 = new BigDecimal(
"123456789.0123456890");
// Create via a long.
BigDecimal bd2 = BigDecimal.valueOf(123);
bd1
bd1
bd1
bd1
bd1
=
=
=
=
=
bd1.add(bd2);
bd1.multiply(bd2);
bd1.subtract(bd2);
bd1.divide(bd2, BigDecimal.ROUND_UP);
bd1.negate();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.math/124.html [8/1/2000 7:49:19 AM]
Code Samples from the Java Developers Almanac 2000
java.math
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Setting the Decimal Place of a Big Decimal Value
int decimalPlaces = 2;
// Truncates the big decimal value.
bd = bd.setScale(decimalPlaces,
BigDecimal.ROUND_DOWN);
String string = bd.toString();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.math/125.html [8/1/2000 7:49:20 AM]
Code Samples from the Java Developers Almanac 2000
java.net
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a URL
try {
// With components.
URL url = new URL("http", "hostname", 80,
"index.html");
// With a single string.
url = new URL("http://hostname:80/index.html");
} catch (MalformedURLException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.net/126.html [8/1/2000 7:49:21 AM]
Code Samples from the Java Developers Almanac 2000
java.net
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Parsing a URL
try {
URL url = new URL(
"http://hostname:80/index.html#_top_");
String protocol = url.getProtocol();
// http
String host = url.getHost();
// hostname
int port = url.getPort();
// 80
String file = url.getFile();
// index.html
String ref = url.getRef();
// _top_
} catch (MalformedURLException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.net/127.html [8/1/2000 7:49:22 AM]
Code Samples from the Java Developers Almanac 2000
java.net
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Reading Text from a URL
try {
URL url = new URL(
"http://hostname:80/index.html");
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
process(str);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.net/128.html [8/1/2000 7:49:23 AM]
Code Samples from the Java Developers Almanac 2000
java.net
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Calling a CGI Using POST Method
try {
// Construct data.
String line = URLEncoder.encode("key1")
+ "=" + URLEncoder.encode("value1");
line += &" + URLEncoder.encode("key2")
+ "=" + URLEncoder.encode("value2");
// Send data.
URL url = new URL("http://hostname:80/cgi");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(line);
wr.flush();
wr.close();
// Read lines from cgi-script.
BufferedReader rd = new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
while ((line = rd.readLine()) != null) {
process(line);
}
rd.close();
} catch (Exception e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
http://developer.java.sun.com/developer/codesamples/java.net/129.html (1 of 2) [8/1/2000 7:49:23 AM]
Code Samples from the Java Developers Almanac 2000
java.net
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Resolving a Hostname
try {
InetAddress addr = InetAddress.getByName(
"java.sun.com");
} catch (UnknownHostException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.net/130.html [8/1/2000 7:49:25 AM]
Code Samples from the Java Developers Almanac 2000
java.net
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Client Socket
try {
InetAddress addr = InetAddress.getByName(
"java.sun.com");
int port = 80;
Socket sock = new Socket(addr, port);
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.net/131.html [8/1/2000 7:49:26 AM]
Code Samples from the Java Developers Almanac 2000
java.net
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Server Socket
try {
int port = 2000;
ServerSocket srv = new ServerSocket(port);
// Wait for connection from client.
Socket socket = srv.accept();
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.net/132.html [8/1/2000 7:49:27 AM]
Code Samples from the Java Developers Almanac 2000
java.net
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Reading Text from a Socket
try {
BufferedReader rd = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String str;
while ((str = rd.readLine()) != null) {
process(str);
}
rd.close();
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.net/133.html [8/1/2000 7:49:28 AM]
Code Samples from the Java Developers Almanac 2000
java.net
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Writing Text to a Socket
try {
BufferedWriter wr = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
wr.write("aString");
wr.flush();
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.net/134.html [8/1/2000 7:49:29 AM]
Code Samples from the Java Developers Almanac 2000
java.net
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Sending a Datagram
public static void send(InetAddress dst,
int port, byte[] outbuf, int len) {
try {
DatagramPacket request =
new DatagramPacket(outbuf, len, dst, port);
DatagramSocket socket =
new DatagramSocket();
socket.send(request);
} catch (SocketException e) {
} catch (IOException e) {
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.net/135.html [8/1/2000 7:49:30 AM]
Code Samples from the Java Developers Almanac 2000
java.net
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Receiving a Datagram
try {
byte[] inbuf = new byte[256]; // default size
DatagramSocket socket = new DatagramSocket();
// Wait for packet
DatagramPacket packet = new DatagramPacket
(inbuf, inbuf.length);
socket.receive(packet);
// Data is now in inbuf
int numBytesReceived = packet.getLength();
} catch (SocketException e) {
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.net/136.html [8/1/2000 7:49:31 AM]
Code Samples from the Java Developers Almanac 2000
java.net
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Joining a Multicast Group
public void join(String groupName, int port) {
try {
MulticastSocket msocket =
new MulticastSocket(port);
group = InetAddress.getByName(groupName);
msocket.joinGroup(group);
} catch (IOException e) {
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.net/137.html [8/1/2000 7:49:32 AM]
Code Samples from the Java Developers Almanac 2000
java.net
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Receiving from a Multicast Group
Once you've created a multicast socket and joined the group, all
datagrams sent to its corresponding multicast address will be
available to be read from the socket. You can read from the socket
just like you would from a unicast socket.
public void read(
MulticastSocket msocket, byte[] inbuf) {
try {
DatagramPacket packet =
new DatagramPacket(inbuf, inbuf.length);
// Wait for packet
msocket.receive(packet);
// Data is now in inbuf
int numBytesReceived = packet.getLength();
} catch (IOException e) {
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.net/138.html [8/1/2000 7:49:33 AM]
Code Samples from the Java Developers Almanac 2000
java.net
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Sending to a Multicast Group
You can send to a multicast socket using either a DatagramSocket
or a MulticastSocket. What makes it multicast is the address that is
in the datagram. If the address is a multicast address, the
datagram will reach the multicast members in the group. You only
need to use MulticastSocket if you want to control the time-to-live
of the datagram.
byte[] outbuf = new byte[1024];
int port = 1234;
try {
DatagramSocket socket = new DatagramSocket();
InetAddress groupAddr =
InetAddress.getByName("228.1.2.3");
DatagramPacket packet =
new DatagramPacket(outbuf, outbuf.length,
groupAddr, port);
socket.send(packet);
} catch (SocketException e) {
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.net/139.html [8/1/2000 7:49:34 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.print
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
The Quintessential Printing Program
Note that (0, 0) of the Graphics object is at the top-left of the
actual page, outside the printable area. In this example, the
Graphics object is translated so that (0, 0) becomes the top-left
corner of the printable area.
import java.awt.*;
import java.awt.print.*;
public class BasicPrint extends JComponent
implements Printable {
public int print(Graphics g, PageFormat pf,
int pageIndex) {
if (pageIndex > 0) {
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(),
pf.getImageableY());
drawGraphics(g2d, pf);
return Printable.PAGE_EXISTS;
}
public static void main(String[] args) {
PrinterJob pjob = PrinterJob.getPrinterJob();
PageFormat pf = pjob.defaultPage();
pjob.setPrintable(new BasicPrint(), pf);
try {
pjob.print();
} catch (PrinterException e) {
}
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
http://developer.java.sun.com/developer/codesamples/java.awt.print/61.html (1 of 2) [8/1/2000 7:49:35 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.print
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting the Dimensions of a Printed Page
Note that (0, 0) of the Graphics object is at the top-left of the
actual page, which is outside the printable area.
public int print(Graphics g, PageFormat pf,
int pageIndex) {
// The area of the printable area.
double ix = pf.getImageableX();
double iy = pf.getImageableY();
double iw = pf.getImageableWidth();
double ih = pf.getImageableHeight();
// The
double
double
double
double
return
area of the actual page.
x = 0;
y = 0;
w = pf.getWidth();
h = pf.getHeight();
Printable.NO_SUCH_PAGE;
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.print/62.html [8/1/2000 7:49:36 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.print
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Setting the Orientation of a Printed Page
PrinterJob pjob = PrinterJob.getPrinterJob();
PageFormat pf = pjob.defaultPage();
if (portrait) {
pf.setOrientation(PageFormat.PORTRAIT);
} else {
pf.setOrientation(PageFormat.LANDSCAPE);
}
pjob.setPrintable(printable, pf);
try {
pjob.print();
} catch (PrinterException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.print/63.html [8/1/2000 7:49:37 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.print
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Printing Pages with Different Formats
A Book object is used when printing pages with different page
formats. This example prints the first page in landscape and five
more pages in portrait.
public class PrintBook {
public static void main(String[] args) {
PrinterJob pjob = PrinterJob.getPrinterJob();
Book book = new Book();
// First part.
PageFormat landscape = pjob.defaultPage();
landscape.setOrientation(PageFormat.LANDSCAPE);
book.append(new Printable1(), landscape);
// Second part.
PageFormat portrait = pjob.defaultPage();
portrait.setOrientation(PageFormat.PORTRAIT);
book.append(new Printable2(), portrait, 5);
pjob.setPageable(book);
try {
pjob.print();
} catch (PrinterException e) {
}
}
static class Printable1 implements Printable {
public int print(Graphics g, PageFormat pf,
int pageIndex) {
drawGraphics(g, pf);
return Printable.PAGE_EXISTS;
}
}
static class Printable2 implements Printable {
public int print(Graphics g, PageFormat pf,
int pageIndex) {
http://developer.java.sun.com/developer/codesamples/java.awt.print/64.html (1 of 2) [8/1/2000 7:49:38 AM]
Code Samples from the Java Developers Almanac 2000
drawGraphics(g, pf);
return Printable.PAGE_EXISTS;
}
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.print/64.html (2 of 2) [8/1/2000 7:49:38 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.print
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Displaying the Page Format Dialog
The page format dialog allows the user to change the default page
format values such as the orientation and paper size.
PrinterJob pjob = PrinterJob.getPrinterJob();
// Get and change default page format settings if
// necessary.
PageFormat pf = pjob.defaultPage();
pf.setOrientation(PageFormat.LANDSCAPE);
// Show page format dialog with page format settings.
pf = pjob.pageDialog(pf);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.print/65.html [8/1/2000 7:49:39 AM]
Code Samples from the Java Developers Almanac 2000
java.awt.print
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Displaying the Print Dialog
The print dialog allows the user to change the default printer
settings such as the default printer, number of copies, range of
pages, etc.
PrinterJob pjob = PrinterJob.getPrinterJob();
PageFormat pf = pjob.defaultPage();
pjob.setPrintable(new PrintableClass(), pf);
try {
if (pjob.printDialog()) {
pjob.print();
}
} catch (PrinterException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.awt.print/66.html [8/1/2000 7:49:40 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.ref
Code Samples Index
These code examples and other materials are subject to Sun Microsystems, Inc.
Legal Terms
Holding onto an Object Until Memory Becomes Low
A soft reference holds onto its referent until memory becomes low.
// Create up the soft reference.
SoftReference sr = new SoftReference(object);
// Use the soft reference.
Object o = sr.get();
if (o != null) {
process(o);
} else {
// The object is being collected or has been reclaimed.
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang.ref/101.html [8/1/2000 7:49:41 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.ref
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining When an Object Is No Longer Used
A weak reference is used to determine when an object is no longer
being referenced.
// Create the weak reference.
ReferenceQueue rq = new ReferenceQueue();
WeakReference wr = new WeakReference(object, rq);
// Wait for all the references to the object.
try {
while (true) {
Reference r = rq.remove();
if (r == wr) {
// Object is no longer referenced.
}
}
} catch (InterruptedException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang.ref/102.html [8/1/2000 7:49:42 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.ref
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining When an Object Is About to be Reclaimed
A phantom reference is used to determine when an object is just
about to be reclaimed. Phantom references are safer to use than
finalization because once an object is phantom reachable, it cannot
be resurrected.
// Create the phantom reference.
ReferenceQueue rq = new ReferenceQueue();
PhantomReference pr = new PhantomReference(object, rq);
// Wait until the object is about to be reclaimed.
try {
while (true) {
Reference r = rq.remove();
if (r == pr) {
// The object is about to be reclaimed.
// Clear the referent so that it can be reclaimed.
r.clear();
}
}
} catch (InterruptedException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/java.lang.ref/103.html (1 of 2) [8/1/2000 7:49:44 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.reflect
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting a Class Object
There are three ways to retrieve a Class object.
// By way of an object.
Class cls = object.getClass();
// By way of a string
try {
cls = Class.forName("java.lang.String");
} catch (ClassNotFoundException e) {
}
// By way of .class
cls = java.lang.String.class;
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/104.html [8/1/2000 7:49:45 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.reflect
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting the Modifiers of a Class Object
int mods = cls.getModifiers();
if (Modifier.isPublic(mods)) {
// class is public
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/105.html [8/1/2000 7:49:47 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.reflect
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting the Interfaces of a Class Object
Class[] intfs = cls.getInterfaces();
for (int i=0; i<intfs.length; i++) {
process(intfs[i]);
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/106.html [8/1/2000 7:49:47 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.reflect
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting the Methods of a Class Object
There are three ways of obtaining a Method object from a Class
object.
Class cls = java.lang.String.class;
// By obtaining a list of all declared methods.
Method[] methods = cls.getDeclaredMethods();
// By obtaining a list of all public
// methods, both declared and inherited.
methods = cls.getMethods();
for (int i=0; i<methods.length; i++) {
Class returnType = methods[i].getReturnType();
Class[] paramTypes =
methods[i].getParameterTypes();
process(methods[i]);
}
// By obtaining a particular Method
// object.
// This example retrieves String.substring(int).
try {
Method method = cls.getMethod(
"substring", new Class[] {int.class});
process(method);
} catch (NoSuchMethodException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/107.html (1 of 2) [8/1/2000 7:49:48 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.reflect
Code Samples Index
These code examples and other materials are subject to Sun Microsystems, Inc.
Legal Terms
Getting a Constructor of a Class Object
There are two ways of obtaining a Constructor object from a Class
object.
// By obtaining a list of all Constructors object.
Constructor[] cons = cls.getDeclaredConstructors();
for (int i=0; i<cons.length; i++) {
Class[] paramTypes = cons[i].getParameterTypes();
process(cons[i]);
}
// By obtaining a particular Constructor object.
// This example retrieves java.awt.Point(int, int).
try {
Constructor con =
java.awt.Point.class.getConstructor(
new Class[]{int.class, int.class});
process(con);
} catch (NoSuchMethodException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/108.html [8/1/2000 7:49:49 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.reflect
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating an Object Using a Constructor Object
This example creates a new Point object from the constructor
Point(int,int).
try {
java.awt.Point obj = (
java.awt.Point)con.newInstance(
new Object[]{new Integer(123), new Integer(123)});
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/109.html [8/1/2000 7:49:50 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.reflect
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting the Field Objects of a Class Object
There are three ways of obtaining a Field object from a Class
object.
Class cls = java.awt.Point.class;
// By obtaining a list of all declared fields.
Field[] fields = cls.getDeclaredFields();
// By obtaining a list of all public fields,
// both declared and inherited.
fields = cls.getFields();
for (int i=0; i<fields.length; i++) {
Class type = fields[i].getType();
process(fields[i]);
}
// By obtaining a particular Field object.
// This example retrieves java.awt.Point.x.
try {
Field field = cls.getField("x");
process(field);
} catch (NoSuchFieldException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/110.html (1 of 2) [8/1/2000 7:49:51 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.reflect
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting and Setting the Value of a Field
This example assumes that the field has the type int.
try {
// Get value
field.getInt(object);
// Set value
field.setInt(object, 123);
} catch (IllegalAccessException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/111.html [8/1/2000 7:49:52 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.reflect
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Invoking a Method Using a Method Object
try {
Object result = method.invoke(
object, new Object[] {param1, param2, ..., paramN});
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/112.html [8/1/2000 7:49:53 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.reflect
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting the Modifiers of a Member Object
Field, Constructor, and Method are all subclasses of Member.
// Modifiers from a field.
int mods = member.getModifiers();
if (Modifier.isPublic(mods)) {
// member is public
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/113.html [8/1/2000 7:49:54 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.reflect
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting the Name of a Class or Member Object
This example shows how to get the fully-qualified and
non-fully-qualified name of a class and reflected objects.
// Non-fully-qualified names.
name = cls.getName().substring(
cls.getPackage().getName().length()+1);
name = field.getName();
name = constructor.getName().substring(
cls.getPackage().getName().length()+1);
name = method.getName();
// Fully-qualified names.
name = cls.getName();
name = cls.getName()+"."+field.getName();
name = constructor.getName();
name = cls.getName()+"."+method.getName();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/114.html [8/1/2000 7:49:56 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.reflect
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining if an Object Is an Array
object.getClass().isArray();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/115.html [8/1/2000 7:49:57 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.reflect
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining the Dimensions of an Array
public static int getDim(Object array) {
int dim = 0;
Class cls = array.getClass();
while (cls.isArray()) {
dim++;
cls = cls.getComponentType();
}
return dim;
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/116.html [8/1/2000 7:49:58 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.reflect
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting the Component Type of an Array
The component type of an array is the type of an array's elements.
For example, the component type of int[] is int. The component
type of int[][] is int[].
object.getClass().getComponentType();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/117.html [8/1/2000 7:49:59 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.reflect
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating an Array
// An array of 10 ints.
int[] ints =
(int[])Array.newInstance(int.class, 10);
// An array of 10 int-arrays.
int[][] ints2 =
(int[][])Array.newInstance(int[].class, 10);
// A 10x20 2-dimenional int array.
ints2 = (int[][])Array.newInstance
(int.class, new int[]{10, 20});
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 31-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/118.html [8/1/2000 7:50:00 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.reflect
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Expanding an Array
The length of an array cannot be changed. The closest thing to
expanding an array is to create a larger one of the same type and
copy the contents from the old array.
Object newArray = Array.newInstance(
array.getClass().getComponentType(),
Array.getLength(array)*2);
System.arraycopy(array, 0, newArray,
0, Array.getLength(array));
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/119.html [8/1/2000 7:50:01 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.reflect
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting and Setting the Value of an Element in an Array
// Get the value of the third element.
Object o = Array.get(array, 2);
// Set the value of the third element.
Array.set(array, 2, newValue);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/120.html [8/1/2000 7:50:02 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.reflect
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Overriding Default Access
By default, a reflected object enforces the access as defined by the
Java language. For example, by default you cannot retrieve the
value from a Field object if the Field object represents a private
field. To bypass these access checks, you call setAccessible() on
the reflected object. However, the program may not have
permission to call setAccessible(), in which case SecurityException
is thrown.
field.setAccessible(true);
constructor.setAccessible(true);
method.setAccessible(true);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/121.html [8/1/2000 7:50:03 AM]
Code Samples from the Java Developers Almanac 2000
java.lang.reflect
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Proxy Object
public interface MyInterface {
void method();
}
public class MyInterfaceImpl implements MyInterface {
public void method() {
}
}
public class ProxyClass implements InvocationHandler {
Object obj;
public ProxyClass(Object o) {
obj = o;
}
public Object invoke(Object proxy, Method m,
Object[] args) throws Throwable {
Object result = null;
try {
// do something before the method is called
result = m.invoke(obj, args);
} catch (InvocationTargetException e) {
} catch (Exception e) {
} finally {
// do something after the method is called
}
return result;
}
}
// This fragment creates a proxy for a
// MyInterface object.
MyInterface myintf =
(MyInterface)Proxy.newProxyInstance(
MyInterface.class.getClassLoader(),
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/122.html (1 of 2) [8/1/2000 7:50:03 AM]
Code Samples from the Java Developers Almanac 2000
new Class[]{MyInterface.class},
new ProxyClass(new MyInterfaceImpl()));
// Invoke the method
myintf.method();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 20-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang.reflect/122.html (2 of 2) [8/1/2000 7:50:03 AM]
Code Samples from the Java Developers Almanac 2000
java.rmi
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Starting Up the RMI Registry
Starting up the RMI registry allows you to create and export
remote objects.
> rmiregistry
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 24-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.rmi/277.html [8/1/2000 7:50:04 AM]
Code Samples from the Java Developers Almanac 2000
java.rmi
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Defining and Exporting a Remote Object
1. Define the remote interface.
import java.rmi.*;
public interface RObject
extends Remote {
void aMethod() throws RemoteException;
}
2. Define the remote object implementation.
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class RObjectImpl
extends UnicastRemoteObject
implements RObject {
public RObjectImpl()
throws RemoteException {
super();
}
// All remote methods must
//throw RemoteException
public void aMethod()
throws RemoteException {
}
}
3. Compile the remote object implementation.
> javac RObject.java RObjectImpl.java
4. Generate the skeletons and stubs.
> rmic RObjectImpl
http://developer.java.sun.com/developer/codesamples/java.rmi/278.html (1 of 2) [8/1/2000 7:50:05 AM]
Code Samples from the Java Developers Almanac 2000
5. Create an instance of the remote object and bind it to the RMI
Registry.
try {
RObject robj =
new RObjectImpl();
Naming.rebind(
"//localhost/RObjectServer", robj);
} catch (MalformedURLException e) {
} catch (UnknownHostException e) {
} catch (RemoteException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 31-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.rmi/278.html (2 of 2) [8/1/2000 7:50:05 AM]
Code Samples from the Java Developers Almanac 2000
java.rmi
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Looking Up a Remote Object and Invoking a Method
try {
// Look up remote object
RObject robj = (RObject) Naming.lookup(
"//localhost/RObjectServer");
}
}
}
}
}
// Invoke method on remote object
robj.aMethod();
catch (MalformedURLException e) {
catch (UnknownHostException e) {
catch (NotBoundException e) {
catch (RemoteException e) {
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.rmi/279.html [8/1/2000 7:50:05 AM]
Code Samples from the Java Developers Almanac 2000
java.rmi
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Passing Parameters to a Remote Method
Arguments to remote methods must be primitive, serializable, or
Remote. This example demonstrates the declaration and use of all
three parameter types.
1. Define the remote interface.
import java.rmi.*;
public interface RObject extends Remote {
// This parameter is primitive.
void primitiveArg(int num)
throws RemoteException;
// This parameter implements Serializable.
void byValueArg(Integer num)
throws RemoteException;
// This parameter implements Remote.
void byRefArg(ArgObject arg)
throws RemoteException;
}
public interface ArgObject extends Remote {
int aMethod()
throws RemoteException;
}
2. Define the remote object implementation.
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class RObjectImpl
extends UnicastRemoteObject
implements RObject {
public RObjectImpl()
http://developer.java.sun.com/developer/codesamples/java.rmi/280.html (1 of 3) [8/1/2000 7:50:06 AM]
Code Samples from the Java Developers Almanac 2000
throws RemoteException {
super();
}
public void primitiveArg(int num)
throws RemoteException {
}
public void byValueArg(Integer num)
throws RemoteException {
}
public void byRefArg(ArgObject arg)
throws RemoteException {
}
}
3. Compile the remote object implementation.
> javac RObject.java RObjectImpl.java
4. Generate the skeletons and stubs.
> rmic RObjectImpl
5. Create an instance of the remote object and bind it to the RMI
Registry.
try {
RObject robj = new RObjectImpl();
Naming.rebind("//localhost/RObjectServer", robj);
} catch (MalformedURLException e) {
} catch (UnknownHostException e) {
} catch (RemoteException e) {
}
6. Look up the remote object and pass the parameters.
try {
// Look up the remote object
RObject robj =
(RObject) Naming.lookup(
"//localhost/RObjectServer");
// Pass a primitive value as argument
robj.primitiveArg(1998);
// Pass a serializable object as argument
robj.byValueArg(
new Integer(9));
// Pass a Remote object as argument
robj.byRefArg(
new ArgObjectImpl());
http://developer.java.sun.com/developer/codesamples/java.rmi/280.html (2 of 3) [8/1/2000 7:50:06 AM]
Code Samples from the Java Developers Almanac 2000
}
}
}
}
}
catch
catch
catch
catch
(MalformedURLException e) {
(UnknownHostException e) {
(NotBoundException e) {
(RemoteException e) {
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 31-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.rmi/280.html (3 of 3) [8/1/2000 7:50:06 AM]
Code Samples from the Java Developers Almanac 2000
java.rmi
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Returning Values from a Remote Method
Return values from remote methods must be primitive, serializable,
or Remote. This example demonstrates the declaration and use of
all three return types.
1. Define the remote interface.
import java.rmi.*;
public interface RObject extends Remote {
// This return value is primitive.
int primitiveRet() throws RemoteException;
// This return value implements Serializable.
Integer byValueRet() throws RemoteException;
// This return value implements Remote.
ArgObject byRefRet() throws RemoteException;
}
public interface ArgObject extends Remote {
int aMethod() throws RemoteException;
}
2. Define the remote object implementation.
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class RObjectImpl extends UnicastRemoteObject
implements RObject {
public RObjectImpl() throws RemoteException {
super();
}
public int primitiveRet() throws RemoteException {
return 3000;
}
http://developer.java.sun.com/developer/codesamples/java.rmi/281.html (1 of 3) [8/1/2000 7:50:07 AM]
Code Samples from the Java Developers Almanac 2000
public Integer byValueRet() throws RemoteException {
return new Integer(2000);
}
public ArgObject byRefRet() throws RemoteException {
return new ArgObjectImpl();
}
}
3. Compile the remote object implementation.
> javac RObject.java RObjectImpl.java
4. Generate the skeletons and stubs.
> rmic RObjectImpl
5. Create an instance of the remote object and bind it to the RMI
Registry.
try {
RObject robj = new RObjectImpl();
Naming.rebind("//localhost/RObjectServer", robj);
} catch (MalformedURLException e) {
} catch (UnknownHostException e) {
} catch (RemoteException e) {
}
6. Look up the remote object, invoke the methods, and receive the
return values.
try {
// Look up the remote object
RObject robj = (RObject) Naming.lookup(
"//localhost/RObjectServer");
// Receive the primitive value as return value
int r1 = robj.primitiveRet();
// Receive the serializable object as return value
Integer r2 = robj.byValueRet();
}
}
}
}
}
// Receive the Remote Object as return value
ArgObject aobj = robj.byRefRet();
catch (MalformedURLException e) {
catch (UnknownHostException e) {
catch (NotBoundException e) {
catch (RemoteException e) {
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
http://developer.java.sun.com/developer/codesamples/java.rmi/281.html (2 of 3) [8/1/2000 7:50:07 AM]
Code Samples from the Java Developers Almanac 2000
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.rmi/281.html (3 of 3) [8/1/2000 7:50:07 AM]
Code Samples from the Java Developers Almanac 2000
java.rmi
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Throwing an Exception from a Remote Method
1. Define the remote interface.
import java.rmi.*;
public interface RObject extends Remote {
void aMethod() throws RemoteException;
}
2. Define the remote object implementation.
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class RObjectImpl extends UnicastRemoteObject
implements RObject {
public RObjectImpl() throws RemoteException {
super();
}
public void aMethod() throws RemoteException {
// The actual exception must be wrapped in
// a RemoteException
throw new RemoteException(
"message", new FileNotFoundException(
"message"));
}
}
3. Compile the remote object implementation.
> javac RObject.java RObjectImpl.java
4. Generate the skeletons and stubs.
> rmic RObjectImpl
5. Create an instance of the remote object and bind it to the RMI
Registry.
http://developer.java.sun.com/developer/codesamples/java.rmi/282.html (1 of 2) [8/1/2000 7:50:07 AM]
Code Samples from the Java Developers Almanac 2000
try {
RObject robj = new RObjectImpl();
Naming.rebind("//localhost/RObjectServer", robj);
} catch (MalformedURLException e) {
} catch (UnknownHostException e) {
} catch (RemoteException e) {
}
6. Look up the remote object, invoke the method, and catch the
exception.
try {
// Look up the remote object.
RObject robj = (RObject) Naming.lookup(
"//localhost/RObjectServer");
}
}
}
}
// Invoke the method.
robj.aMethod();
catch (MalformedURLException e) {
catch (UnknownHostException e) {
catch (NotBoundException e) {
catch (RemoteException e) {
// Get the actual exception that was thrown.
Throwable realException = e.detail;
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.rmi/282.html (2 of 2) [8/1/2000 7:50:07 AM]
Code Samples from the Java Developers Almanac 2000
javax.sound.sampled
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Loading and Playing Sampled Audio
Supported audio file formats: aif, au, and wav.
try {
// From file
AudioInputStream stream =
AudioSystem.getAudioInputStream(
new File("audiofile"));
// From URL
stream = AudioSystem.getAudioInputStream(
new URL("http://hostname/audiofile"));
// At present, ALAW and ULAW encodings must be
//converted
// to PCM_SIGNED before it can be played.
AudioFormat format = stream.getFormat();
if (format.getEncoding() !=
AudioFormat.Encoding.PCM_SIGNED) {
format = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
format.getSampleRate(),
format.getSampleSizeInBits()*2,
format.getChannels(),
format.getFrameSize()*2,
format.getFrameRate(),
true);
// big endian
stream = AudioSystem.getAudioInputStream(
format, stream);
}
DataLine.Info info = new DataLine.Info(
Clip.class, stream.getFormat(),
//The next two lines should be in one line.
((int)stream.getFrameLength(
)*format.getFrameSize()));
http://developer.java.sun.com/developer/codesamples/javax.sound.sampled/313.html (1 of 2) [8/1/2000 7:50:08 AM]
Code Samples from the Java Developers Almanac 2000
Clip clip = (Clip) AudioSystem.getLine(info);
// This method does not return until the audio
//file is completely loaded.
clip.open(stream);
}
}
}
}
}
// Start playing.
clip.start();
catch (MalformedURLException e) {
catch (IOException e) {
catch (LineUnavailableException e) {
catch (UnsupportedAudioFileException e) {
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.sound.sampled/313.html (2 of 2) [8/1/2000 7:50:08 AM]
Code Samples from the Java Developers Almanac 2000
javax.sound.sampled
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining the File Format of a Sampled Audio File
try {
// From file
AudioFileFormat fformat =
AudioSystem.getAudioFileFormat(
new File("audiofile"));
// From URL
fformat = AudioSystem.getAudioFileFormat(
new URL("http://hostname/audiofile"));
if (fformat.getType() ==
AudioFileFormat.Type.AIFC) {
} else if (fformat.getType() ==
AudioFileFormat.Type.AIFF) {
} else if (fformat.getType() ==
AudioFileFormat.Type.AU) {
} else if (fformat.getType() ==
AudioFileFormat.Type.WAVE) {
}
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (UnsupportedAudioFileException e) {
// File format is not supported.
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
http://developer.java.sun.com/developer/codesamples/javax.sound.sampled/314.html (1 of 2) [8/1/2000 7:50:08 AM]
Code Samples from the Java Developers Almanac 2000
javax.sound.sampled
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining the Encoding of a Sampled Audio File
try {
// From file
// The next three lines should be in one line
AudioInputStream stream =
AudioSystem.getAudioInputStream(
new File("audiofile"));
// From URL
stream = AudioSystem.getAudioInputStream(
new URL("http://hostname/audiofile"));
AudioFormat format = stream.getFormat();
if (format.getEncoding() ==
AudioFormat.Encoding.ULAW) {
} else if (format.getEncoding() ==
AudioFormat.Encoding.ULAW) {
}
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (UnsupportedAudioFileException e) {
// Audio format is not supported.
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
http://developer.java.sun.com/developer/codesamples/javax.sound.sampled/315.html (1 of 2) [8/1/2000 7:50:09 AM]
Code Samples from the Java Developers Almanac 2000
javax.sound.sampled
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining the Duration of a Sampled Audio File
To create a DataLine object, see ``Loading and Playing Sampled
Audio'' and ``Playing Streaming Sampled Audio''.
double durationInSecs = dataline.getBufferSize() /
//The next two lines should be in one line
(dataline.getFormat().getFrameSize(
) * dataline.getFormat().getFrameRate());
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.sound.sampled/316.html [8/1/2000 7:50:09 AM]
Code Samples from the Java Developers Almanac 2000
javax.sound.sampled
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Playing Streaming Sampled Audio
try {
// From file
AudioInputStream stream =
AudioSystem.getAudioInputStream(
new File("audiofile"));
// From URL
stream = AudioSystem.getAudioInputStream(
new URL("http://hostname/audiofile"));
// At present, ALAW and ULAW encodings must be
// converted
// to PCM_SIGNED before it can be played.
AudioFormat format = stream.getFormat();
if (format.getEncoding() !=
AudioFormat.Encoding.PCM_SIGNED) {
format = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
format.getSampleRate(),
format.getSampleSizeInBits()*2,
format.getChannels(),
format.getFrameSize()*2,
format.getFrameRate(),
true);
// big endian
stream = AudioSystem.getAudioInputStream(
format, stream);
}
SourceDataLine.Info info = new DataLine.Info(
//The next two lines should be in one line
SourceDataLine.class, stream.getFormat(),
//The next two lines should be in one line
((int)stream.getFrameLength(
)*format.getFrameSize()));
http://developer.java.sun.com/developer/codesamples/javax.sound.sampled/317.html (1 of 2) [8/1/2000 7:50:10 AM]
Code Samples from the Java Developers Almanac 2000
//The next two lines should be in one line
SourceDataLine line = (SourceDataLine)
AudioSystem.getLine(info);
line.open(stream.getFormat());
line.start();
int numRead = 0;
byte[] buf = new byte[line.getBufferSize()];
}
}
}
}
}
//The next two lines should be in one line
while ((numRead = stream.read(buf,
0, buf.length)) >= 0) {
int offset = 0;
while (offset < numRead) {
offset += line.write(buf, offset,
numRead-offset);
}
}
line.drain();
line.stop();
catch (MalformedURLException e) {
catch (IOException e) {
catch (LineUnavailableException e) {
catch (UnsupportedAudioFileException e) {
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.sound.sampled/317.html (2 of 2) [8/1/2000 7:50:10 AM]
Code Samples from the Java Developers Almanac 2000
javax.sound.sampled
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Continuously Playing a Sampled Audio File
Only DataLine objects that are of type Clip can be repeated. See
the ``Loading and Playing Sampled Audio'' examplet to create a
clip.
// Loop forever.
clip.loop(Clip.LOOP_CONTINUOUSLY);
// Loop for a certain number of times.
clip.loop(3);
// Start playing.
clip.start();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.sound.sampled/318.html [8/1/2000 7:50:10 AM]
Code Samples from the Java Developers Almanac 2000
javax.sound.sampled
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining the Position of a Sampled Audio Player
To create a DataLine object, see ``Loading and Playing Sampled
Audio'' and ``Playing Streaming Sampled Audio''.
double timeInSeconds =
dataline.getMicrosecondPosition()/1000000.0d;
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.sound.sampled/319.html [8/1/2000 7:50:11 AM]
Code Samples from the Java Developers Almanac 2000
javax.sound.sampled
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining When a Sampled Audio Player has
Finished Playing
To create a DataLine object, see ``Loading and Playing Sampled
Audio'' and ``Playing Streaming Audio''.
dataline.addLineListener(new LineListener() {
public void update(LineEvent evt) {
if (evt.getType() == LineEvent.Type.STOP) {
}
}
});
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.sound.sampled/320.html [8/1/2000 7:50:11 AM]
Code Samples from the Java Developers Almanac 2000
javax.sound.sampled
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Controlling the Volume of Playing Sampled Audio
To create a DataLine object, see ``Loading and Playing Sampled
Audio'' and ``Playing Streaming Audio''.
// Set Volume
FloatControl gainControl =
(FloatControl)dataline.getControl(
FloatControl.Type.MASTER_GAIN);
double gain = .5d;
// number between 0 and 1.
float dB = (float)(Math.log(gain)/Math.log(10.0)*20.0);
gainControl.setValue(dB);
// Mute On
//The next three lines should all be in one line
BooleanControl muteControl =
(BooleanControl)dataline.getControl(
BooleanControl.Type.MUTE);
muteControl.setValue(true);
// Mute Off
muteControl.setValue(false);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/javax.sound.sampled/321.html (1 of 2) [8/1/2000 7:50:12 AM]
Code Samples from the Java Developers Almanac 2000
javax.sound.midi
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Loading and Playing Midi Audio
Supported audio file formats: mid
try {
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
// From file
Sequence sequence = MidiSystem.getSequence(
new File("midifile"));
// From URL
sequence = MidiSystem.getSequence(new URL(
"http://hostname/midifile"));
sequencer.setSequence(sequence);
// Start playing.
sequencer.start();
}
catch
}
catch
}
catch
}
catch
}
(MalformedURLException e) {
(IOException e) {
(MidiUnavailableException e) {
(InvalidMidiDataException e) {
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
http://developer.java.sun.com/developer/codesamples/javax.sound.midi/322.html (1 of 2) [8/1/2000 7:50:12 AM]
Code Samples from the Java Developers Almanac 2000
javax.sound.midi
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining the File Format of a Midi Audio File
try {
// From file
MidiFileFormat fformat =
MidiSystem.getMidiFileFormat(new File(
"midifile"));
// From URL
fformat = MidiSystem.getMidiFileFormat(new URL(
"http://hostname/midifile"));
switch (fformat.getType()) {
case 0:
// mid
break;
case 1:
// rmf
break;
}
}
catch (MalformedURLException e) {
}
catch (IOException e) {
}
catch (InvalidMidiDataException e) {
// File format is not supported.
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
http://developer.java.sun.com/developer/codesamples/javax.sound.midi/323.html (1 of 2) [8/1/2000 7:50:13 AM]
Code Samples from the Java Developers Almanac 2000
javax.sound.midi
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining the Duration of a Midi Audio File
To create a Sequencer object, see ``Loading and Playing Midi
Audio'' and ``Playing Streaming Midi Audio''.
double durationInSecs =
sequencer.getMicrosecondLength() / 1000000.0;
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.sound.midi/324.html [8/1/2000 7:50:13 AM]
Code Samples from the Java Developers Almanac 2000
javax.sound.midi
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Playing Streaming Midi Audio
Supported audio file formats: mid, rmf
try {
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
// From file
InputStream is = new BufferedInputStream(
new FileInputStream(new File("midifile")));
// From URL
is = new BufferedInputStream(
new URL("http://hostname/rmffile").openStream());
sequencer.setSequence(is);
// Start playing.
sequencer.start();
}
catch
}
catch
}
catch
}
catch
}
(MalformedURLException e) {
(IOException e) {
(MidiUnavailableException e) {
(InvalidMidiDataException e) {
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
http://developer.java.sun.com/developer/codesamples/javax.sound.midi/325.html (1 of 2) [8/1/2000 7:50:14 AM]
Code Samples from the Java Developers Almanac 2000
javax.sound.midi
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining the Position of a Midi Sequencer
To create a Sequencer object, see ``Loading and Playing Midi
Audio'' and ``Playing Streaming Midi Audio''.
double seconds = sequencer.
getMicrosecondPosition() / 1000000.0;
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.sound.midi/326.html [8/1/2000 7:50:14 AM]
Code Samples from the Java Developers Almanac 2000
javax.sound.midi
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining When a Midi Audio Player has Finished
Playing
To create a Sequencer object, see ``Loading and Playing Midi
Audio'' and ``Playing Streaming Midi Audio''.
sequencer.addMetaEventListener(
new MetaEventListener() {
public void meta(MetaMessage event) {
if (event.getType() == 47) {
// Sequencer is done playing
}
}
});
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.sound.midi/327.html [8/1/2000 7:50:15 AM]
Code Samples from the Java Developers Almanac 2000
javax.sound.midi
Code Samples Index
These code examples and other materials are subject to Sun Microsystems, Inc.
Legal Terms
Controlling the Volume of Playing Midi Audio
To create a Sequencer object, see ``Loading and Playing Midi
Audio'' and ``Playing Streaming Midi Audio''.
if (sequencer instanceof Synthesizer) {
Synthesizer synthesizer = (Synthesizer)sequencer;
MidiChannel[] channels = synthesizer.getChannels();
// gain is a value between 0 and 1.
for (int i=0; i<channels.length; i++) {
channels[i].controlChange(7, (int)(gain * 127.0));
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.sound.midi/328.html [8/1/2000 7:50:15 AM]
Code Samples from the Java Developers Almanac 2000
java.security
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a New Key Pair and Self-signed Certificate
This example uses the keytool program to create a new key pair
and self-signed certificate for the principal Duke.
< keytool -genkey -alias alias -keystore .keystore
Enter keystore password: password
What is your first and last name?
[Unknown]: Duke
What is the name of your organizational unit?
[Unknown]: JavaSoft
What is the name of your organization?
[Unknown]: Sun
What is the name of your City or Locality?
[Unknown]: Cupertino
What is the name of your State or Province?
[Unknown]: CA
What is the two-letter country code for this unit?
[Unknown]: US
Is correct?
[no]: yes
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 31-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.security/249.html [8/1/2000 7:50:15 AM]
Code Samples from the Java Developers Almanac 2000
java.security
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating and Signing a JAR File
> jar cf myjar.jar MyClass.class
> jarsigner -keystore .keystore -storepass
password myjar.jar alias
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.security/250.html [8/1/2000 7:50:16 AM]
Code Samples from the Java Developers Almanac 2000
java.security
Code Samples Index
These code examples and other materials are subject to Sun Microsystems, Inc.
Legal Terms
Creating a New Policy File
Use policytool to create or edit an existing policy file. This is an
example of a policy file created using policytool. It grants two
permissions. It grants code signed by ``Duke'' permission to read files
located in the user's home directory. It also grants code from the
location ``http://someserver/myjar.jar'' (regardless of who signed it)
to read the ``file.encoding'' system property.
> policytool -file .policy
keystore ".keystore";
grant signedBy "Duke" {
permission java.io.FilePermission "${user.dir}/-",
"read";
};
grant codeBase "http://someserver/myjar.jar" {
permission java.util.PropertyPermission "file.encoding",
"read";
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.security/251.html [8/1/2000 7:50:16 AM]
Code Samples from the Java Developers Almanac 2000
java.security
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Managing Policy Files
The Java Runtime provides default policy files to be used. See
http://java.sun.com/products/jdk/1.2/docs
/guide/security/PolicyFiles.html
for more information. The location of these file is specified in the
file java.home/lib/security/java.security. By default, this file specifies two
locations:
file:/java.home
/lib/security/java.policy
file:/user.home
/lib/security/.java.policy
The runtime's policy is the union of entries in these files. To specify
an additional policy file, you can add entries to the java.security file:
> java -Djava.security.manager
-Djava.security.policy=someURL MyApp
or specify the addition at runtime:
> appletviewer
-J-Djava.security.policy=someURL HTMLfile
To ignore the policies in the java.security file, and only use the
specified policy, use == instead of =:
>java -Djava.security.manager
-Djava.security.policy==someURL MyApp
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 31-Jul-2000 ]
http://developer.java.sun.com/developer/codesamples/java.security/252.html (1 of 2) [8/1/2000 7:50:17 AM]
Code Samples from the Java Developers Almanac 2000
java.security
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Keyed Digest Using MD5
A ``keyed'' digest is one in which a secret key is used to create a
digest for a buffer of bytes. You can use different keys to create
different digests for the same buffer of bytes.
public static byte[] getKeyedDigest(byte[]
buffer, byte[] key) {
try {
MessageDigest md5 =
MessageDigest.getInstance("MD5");
md5.update(buffer);
return md5.digest(key);
} catch (NoSuchAlgorithmException e) {
}
return null;
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 31-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.security/253.html [8/1/2000 7:50:17 AM]
Code Samples from the Java Developers Almanac 2000
java.security
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting a Certificate from a Keystore
try {
KeyStore keyStore = KeyStore.getInstance(
KeyStore.getDefaultType());
InputStream in = new FileInputStream(".keystore");
keyStore.load(in, "password".toCharArray());
}
}
}
}
}
java.security.cert.Certificate cert =
keyStore.getCertificate("Principal");
process(cert);
catch (KeyStoreException e) {
catch (java.security.cert.CertificateException e) {
catch (NoSuchAlgorithmException e) {
catch (java.io.IOException e) {
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.security/254.html [8/1/2000 7:50:18 AM]
Code Samples from the Java Developers Almanac 2000
java.security
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Checking Read/Write Permission for a Directory
AccessController.checkPermission(new FilePermission(
"/tmp/*", "read,write"));
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.security/255.html [8/1/2000 7:50:18 AM]
Code Samples from the Java Developers Almanac 2000
java.security
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Checking if One Permission Implies Another
Permission perm1 = new FilePermission(
"/tmp/*", "read,write");
Permission perm2 = new FilePermission(
"/tmp/abc", "read");
if (perm1.implies(perm2)) {
// perm1 implies perm2
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.security/256.html [8/1/2000 7:50:19 AM]
Code Samples from the Java Developers Almanac 2000
java.security
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Secure Random Number
public static float create(byte[] seed) {
SecureRandom sr = new SecureRandom(seed);
return sr.nextFloat();
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.security/257.html [8/1/2000 7:50:20 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
The Quintessential Swing User Interface
This example creates and shows a frame with a button.
import java.awt.*;
import javax.swing.*;
public class BasicUI {
public static void main(String[] args) {
JButton button =
new JButton("Label");
JFrame frame = new JFrame();
// Add button to the frame.
frame.getContentPane().add(
button, BorderLayout.CENTER);
// Set initial size.
frame.setSize(300,
300);
// Show the frame.
frame.setVisible(true);
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
http://developer.java.sun.com/developer/codesamples/javax.swing/181.html (1 of 2) [8/1/2000 7:50:20 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Centering a Frame on the Screen
//The next two lines should be in one line.
Dimension dim = Toolkit.getDefaultToolkit(
).getScreenSize();
int w = frame.getSize().width;
int h = frame.getSize().height;
int x = (dim.width-w)/2;
int y = (dim.height-h)/2;
frame.setBounds(x, y, w, h);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/182.html [8/1/2000 7:50:20 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Exiting an Application When a Frame Is Closed
// The next two lines should be in one line.
frame.
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/183.html [8/1/2000 7:50:21 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Button
JButton button = new JButton("Label");
button.addActionListener(actionListener);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/184.html [8/1/2000 7:50:21 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Checkbox Button
JCheckBox checkBox = new JCheckBox("Label");
checkBox.addActionListener(actionListener);
// Set the current state of the checkbox.
checkBox.setSelected(false);
// Get the current state of the checkbox.
boolean on = checkBox.isSelected();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/185.html [8/1/2000 7:50:22 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Color Chooser Dialog
Color initialColor = Color.red;
Color newColor = JColorChooser.showDialog(
frame, "Dialog Title", initialColor);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/186.html [8/1/2000 7:50:23 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a ComboBox
// A read-only combo box.
String[] items = {"item1", "item2"};
JComboBox readOnlyCB = new JComboBox(items);
readOnlyCB.addActionListener(actionListener);
// An editable combo box.
JComboBox editableCB = new JComboBox(items);
editableCB.setEditable(true);
editableCB.addActionListener(actionListener);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/187.html [8/1/2000 7:50:24 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating Image Radio Buttons
When using an image to represent the state of a radio button, it is
necessary to provide it with two images - one that represents the
``selected'' state and another to represent the ``unselected''
state. The ``unselected'' image is assigned via the JRadioButton
constructor while the ``selected'' image is assigned via the method
setSelectedIcon().
ButtonGroup group = new ButtonGroup();
JRadioButton b1 = new JRadioButton("image1.gif");
b1.setSelectedIcon(new ImageIcon("images1s.gif"));
b1.addActionListener(actionListener);
group.add(b1);
JRadioButton b2 = new JRadioButton("image1.gif");
b1.setSelectedIcon(new ImageIcon("images2s.gif"));
b2.addActionListener(actionListener);
group.add(b2);
// Set one of the radio buttons on.
group.setSelected(b1.getModel(), true);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/javax.swing/188.html (1 of 2) [8/1/2000 7:50:24 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Retrieving the Selected Button in a Group
When you ask a button group for the currently selected button, it
returns the selected button's model (rather than the selected
button itself). Fortunately, the button group maintains the list of
buttons and so you can iterate over this list looking for one with
the same model.
static AbstractButton getSelection(ButtonGroup group) {
// The next two lines should be in one line.
for (Enumeration e=group.getElements();
e.hasMoreElements(); ) {
// The next two lines should be in one line.
AbstractButton b =
(AbstractButton)e.nextElement();
if (b.getModel() == group.getSelection()) {
return b;
}
}
return null;
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/javax.swing/189.html (1 of 2) [8/1/2000 7:50:25 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems, Inc. Legal
Terms
Firing Item Events
An object wishing to fire item events must implement ItemSelectable. This
example shows typical code that an object must implement to fire item
events. When an item event is to be fired, fireItemEvent() should be called.
public class ItemEvents implements ItemSelectable {
protected EventListenerList listenerList =
new EventListenerList();
public Object[] getSelectedObjects() {
return selectedObjects;
}
public void addItemListener(ItemListener l) {
listenerList.add(ItemListener.class, l);
}
public void removeItemListener(ItemListener l) {
listenerList.remove(ItemListener.class, l);
}
void fireItemEvent(int selected) {
ItemEvent evt = null;
// The next two lines should be in one line
Object[] listeners =
listenerList.getListenerList();
for (int i=0; i<listeners.length-2; i+=2) {
if (listeners[i] == ItemListener.class) {
if (evt == null) {
// The next two lines should be in one line
evt = new ItemEvent(
this, ItemEvent.ITEM_STATE_CHANGED,
this, selected);
}
// The next two lines should be in one
// line.
((ItemListener)listeners[i+1])
.itemStateChanged(evt);
}
http://developer.java.sun.com/developer/codesamples/javax.swing/190.html (1 of 2) [8/1/2000 7:50:26 AM]
Code Samples from the Java Developers Almanac 2000
}
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author
Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/190.html (2 of 2) [8/1/2000 7:50:26 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a File Chooser Dialog
String filename = File.separator+"tmp";
JFileChooser fc = new JFileChooser(new File(filename));
// Open file dialog.
fc.showOpenDialog(frame);
openFile(fc.getSelectedFile());
// Save file dialog.
fc.showSaveDialog(frame);
saveFile(fc.getSelectedFile());
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/191.html [8/1/2000 7:50:26 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Displaying Only Directories in a File Chooser Dialog
JFileChooser fileChooser = new JFileChooser(file);
fileChooser.setFileSelectionMode(
JFileChooser.DIRECTORIES_ONLY);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/192.html [8/1/2000 7:50:27 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating an Internal Frame
boolean resizable = true;
boolean closeable = true;
boolean maximizable = true;
boolean iconifiable = true;
int width = 200;
int height = 50;
JInternalFrame iframe =
new JInternalFrame("", resizable, closeable,
maximizable, iconifiable);
iframe.setSize(width, height);
// Add component to internal frame.
// Add internal frame to desktop.
JDesktopPane desktop = new JDesktopPane();
desktop.add(iframe);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/193.html [8/1/2000 7:50:28 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a List Component
The list fires a list selection event whenever its set of selected
items changes.
// A multiple selection list.
String[] items = {"item1", "item2"};
JList list = new JList(items);
// The next two lines should be in one line.
list.addListSelectionListener(
new MyListSelectionListener());
// Make the list single selection mode
// The next two lines should be in one line.
list.setSelectionMode(
ListSelectionModel.SINGLE_SELECTION);
// The next two lines should be in one line.
class MyListSelectionListener implements
ListSelectionListener {
// The next two lines should be in one line.
public void valueChanged(
ListSelectionEvent evt) {
if (!evt.getValueIsAdjusting()) {
JList list = (JList)evt.getSource();
// The next two lines should be in one line.
Object[] selected =
list.getSelectedValues();
for (int i=0; i<selected.length; i++) {
process(selected[i]);
}
}
}
}
http://developer.java.sun.com/developer/codesamples/javax.swing/194.html (1 of 2) [8/1/2000 7:50:28 AM]
Code Samples from the Java Developers Almanac 2000
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/194.html (2 of 2) [8/1/2000 7:50:28 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Scrolling List Component
JList doesn't directly support scrolling. You need to wrap a JList in a
JScrollPane.
JList list = new JList(new String[]{"element1",
"element2", "element3"});
JScrollPane scrollingList = new JScrollPane(list);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/195.html [8/1/2000 7:50:29 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems, Inc.
Legal Terms
Setting the Selection Mode of a List Component
// The default mode is MULTIPLE_INTERVAL_SELECTION.
JList list = new JList(new String[]{"element1",
"element2", "element3"});
ListSelectionModel lsm = list.getSelectionModel();
// Only one item can be selected.
lsm.setSelectionMode(
DefaultListSelectionModel.SINGLE_SELECTION);
// The selected items must be in a contiguous range.
lsm.setSelectionMode(
DefaultListSelectionModel.SINGLE_INTERVAL_SELECTION);
// Multiple ranges of selected items are allowed.
lsm.setSelectionMode(
DefaultListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/196.html [8/1/2000 7:50:29 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Menu Bar, Menu, and Menu Item
When the user selects a menu item, it fires an action event.
// Create the menu bar.
JMenuBar menuBar = new JMenuBar();
// Create a menu.
JMenu menu = new JMenu("Menu Label");
menuBar.add(menu);
// Create a menu item.
JMenuItem item = new JMenuItem("Item Label");
item.addActionListener(actionListener);
menu.add(item);
// Install the menu bar in the frame.
frame.setJMenuBar(menuBar);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/197.html [8/1/2000 7:50:30 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Separating Menu Items in a Menu
menu.add(item1);
menu.add(new JSeparator());
menu.add(item2);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/198.html [8/1/2000 7:50:30 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Popup Menu
final JPopupMenu menu = new JPopupMenu();
// Create and add a menu item.
JMenuItem item = new JMenuItem("Item Label");
item.addActionListener(actionListener);
menu.add(item);
// Set the component to show the popup menu.
component.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
if (evt.isPopupTrigger()) {
menu.show(evt.getComponent(), evt.getX(),
evt.getY());
}
}
public void mouseReleased(MouseEvent evt) {
if (evt.isPopupTrigger()) {
menu.show(evt.getComponent(), evt.getX(),
evt.getY());
}
}
});
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
http://developer.java.sun.com/developer/codesamples/javax.swing/199.html (1 of 2) [8/1/2000 7:50:31 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Progess Bar
int minimum = 0;
int maximum = 100;
JProgressBar progress = new JProgressBar(
minimum, maximum);
// Change the progess bar's value.
int initValue = 50;
progress.setValue(initValue);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/200.html [8/1/2000 7:50:31 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating Radio Buttons
ButtonGroup group = new ButtonGroup();
JRadioButton b1 = new JRadioButton("Label1");
b1.addActionListener(actionListener);
group.add(b1);
JRadioButton b2 = new JRadioButton("Label2");
b2.addActionListener(actionListener);
group.add(b2);
// Set one of the radio buttons on.
group.setSelected(b1.getModel(), true);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/201.html [8/1/2000 7:50:32 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Scroll Pane
The Swing components do not typically have scroll bars. In order to
automatically display scroll bars, you need to insert the component
in a scroll pane.
JTextArea textArea = new JTextArea(10, 10);
JScrollPane scrollableTextArea =
new JScrollPane(textArea);
JList list = new JList();
JScrollPane scrollableList = new JScrollPane(list);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/202.html [8/1/2000 7:50:32 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Slider
int minimum = 0;
int maximum = 100;
int initValue = 50;
// A horizontal slider.
JSlider hSlider = new JSlider(
JSlider.HORIZONTAL, minimum, maximum, initValue);
hSlider.addChangeListener(new MyChangeListener());
// A vertical slider.
JSlider vSlider = new JSlider(
JSlider.VERTICAL, minimum, maximum, initValue);
vSlider.addChangeListener(new MyChangeListener());
class MyChangeListener implements ChangeListener {
public void stateChanged(ChangeEvent evt) {
JSlider slider = (JSlider)evt.getSource();
if (!slider.getValueIsAdjusting()) {
int value = slider.getValue();
process(value);
}
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
http://developer.java.sun.com/developer/codesamples/javax.swing/203.html (1 of 2) [8/1/2000 7:50:33 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Split Pane
// A left-right split pane.
JSplitPane hpane = new JSplitPane(
JSplitPane.HORIZONTAL_SPLIT, leftComponent,
rightComponent);
// A top-bottom split pane.
JSplitPane vpane = new JSplitPane(
JSplitPane.VERTICAL_SPLIT, topComponent,
bottomComponent);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/204.html [8/1/2000 7:50:34 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Tabbed Pane
int location = JTabbedPane.TOP; // or BOTTOM,
LEFT, RIGHT
JTabbedPane pane = new JTabbedPane(location);
ImageIcon icon = new ImageIcon("image.gif");
// or null;
pane.addTab("Tab Label", icon, panel,
"Tool Tip Text");
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/205.html [8/1/2000 7:50:35 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Text Field
When the user hits RETURN, the text field fires an action event.
JTextField textfield =
new JTextField("Initial Text");
textfield.addActionListener(new MyActionListener());
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
JTextField textfield =
(JTextField)evt.getSource();
process(textfield.getText());
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/206.html [8/1/2000 7:50:35 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Password Text Field
When the user hits RETURN, the text field fires an action event.
JPasswordField textfield = new JPasswordField(
"Initial Text");
textfield.setEchoChar('#');
textfield.addActionListener(actionListener);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/207.html [8/1/2000 7:50:36 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems, Inc.
Legal Terms
Creating a Table
A table fires change events when the contents of one of its cells is
modified.
Object[][] cellData = {
{"row1-col1", "row1-col2"},
{"row2-col1", "row2-col2"}};
String[] columnNames = {"col1", "col2"};
JTable table = new JTable(cellData, columnNames);
// The next two lines should be in one line.
table.getModel().addTableModelListener(
new MyTableChangedListener());
// Make the table scrollable.
JScrollPane scrollPane = new JScrollPane(table);
// The next two lines should be in one line.
class MyTableChangedListener
implements TableModelListener {
public void tableChanged(TableModelEvent evt) {
int row = evt.getFirstRow();
int column = evt.getColumn();
// The next three lines should all be in one line.
Object data =
((TableModel)evt.getSource()).getValueAt(
row, column);
process(data);
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
http://developer.java.sun.com/developer/codesamples/javax.swing/208.html (1 of 2) [8/1/2000 7:50:36 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Text Area
The text area fires a document event whenever the text changes or
some style on the text changes.
TextArea textArea = new JTextArea("Line1\nLine2");
TextArea.getDocument().addDocumentListener(
new MyDocumentListener());
// The next two lines should be in one line.
class MyDocumentListener implements
DocumentListener {
public void insertUpdate(DocumentEvent evt) {
// Some text was inserted.
}
public void removeUpdate(DocumentEvent evt) {
// Some text was inserted.
}
public void changedUpdate(DocumentEvent evt) {
// The style of some text was changed.
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/javax.swing/209.html (1 of 2) [8/1/2000 7:50:37 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Displaying Simple HTML Files
try {
String url = "http://java.sun.com";
JEditorPane editorPane = new JEditorPane(url);
editorPane.setEditable(false);
JFrame frame = new JFrame();
frame.getContentPane().add(editorPane,
BorderLayout.CENTER);
frame.setSize(width, height);
frame.setVisible(true);
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/210.html [8/1/2000 7:50:37 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Toolbar
This example adds an image button to the toolbar.
ImageIcon icon = new ImageIcon("image.gif");
JButton button = new JButton(icon);
button.addActionListener(actionListener);
JToolBar toolbar = new JToolBar();
toolbar.add(button);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/211.html [8/1/2000 7:50:38 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Borderless Window
JWindow window = new JWindow();
// Add component to the window.
// The next two lines should be in one line.
window.getContentPane().add(component,
BorderLayout.CENTER);
// Set initial size.
window.setSize(300, 300);
// Show the window.
window.setVisible(true);
<
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/212.html [8/1/2000 7:50:38 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Showing a Dialog Box
// Modal dialog with OK button.
JOptionPane.showMessageDialog(frame, "Line1\nLine2");
// Modal dialog with yes/no button.
int answer = JOptionPane.showConfirmDialog(
frame, "Line1\nLine2");
if (answer == JOptionPane.YES_OPTION) {
// User clicked YES.
} else if (answer == JOptionPane.NO_OPTION) {
// User clicked NO.
}
// Modal dialog with OK/cancel and a text field
String text = JOptionPane.showInputDialog(
frame, "Line1\nLine2");
if (text == null) {
// User clicked cancel
} else {
process(text);
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/javax.swing/213.html (1 of 2) [8/1/2000 7:50:39 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating Key Strokes and Binding Them to Actions
// Some examples of keystrokes
component.getInputMap().put(KeyStroke.getKeyStroke(
"F2"), "actionName");
component.getInputMap().put(KeyStroke.getKeyStroke(
"control A"), "actionName");
component.getInputMap().put(KeyStroke.getKeyStroke(
"shift F2"), "actionName");
component.getInputMap().put(KeyStroke.getKeyStroke(
'('), "actionName");
component.getInputMap().put(KeyStroke.getKeyStroke(
"button3 F"), "actionName");
component.getInputMap().put(KeyStroke.getKeyStroke(
"typed x"), "actionName");
component.getInputMap().put(KeyStroke.getKeyStroke(
"released DELETE"), "actionName");
component.getInputMap().put(KeyStroke.getKeyStroke(
"shift UP"), "actionName");
component.getActionMap().put("actionName",
new AbstractAction("actionName") {
// The next two lines should be in one line
public void actionPerformed(
ActionEvent evt) {
process(evt);
}
}
);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
http://developer.java.sun.com/developer/codesamples/javax.swing/214.html (1 of 2) [8/1/2000 7:50:40 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Adding an InputMap to a Component
InputMap inputMap = new InputMap();
// Add a KeyStroke
inputMap.put(KeyStroke.getKeyStroke(
"F2"), "actionName");
inputMap.setParent(component.getInputMap(
JComponent.WHEN_FOCUSED));
component.setInputMap(
JComponent.WHEN_FOCUSED, inputMap);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/215.html [8/1/2000 7:50:41 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Setting a Tool Tip
component.setToolTipText("aString");
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/216.html [8/1/2000 7:50:41 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Laying Out Components in a Row or Column
// Use Y_AXIS for a vertical column.
Box box = new Box(BoxLayout.X_AXIS);
box.add(component1);
box.add(component2);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/217.html [8/1/2000 7:50:42 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Separating Components in a Row or Column
Box box = new Box(BoxLayout.X_AXIS);
// Glue spreads the components as far apart as
// possible.
box.add(component1);
box.add(Box.createGlue());
box.add(component2);
// Strut spreads the components apart by a fixed
// distance.
int width = 10;
box.add(Box.createHorizontalStrut(width));
box.add(component3);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/218.html [8/1/2000 7:50:42 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Laying Out Components in a Flow (Left-to-Right,
Top-to-Bottom)
int align = FlowLayout.CENTER;
// or LEFT, RIGHT
JPanel panel = new JPanel(new FlowLayout(align));
panel.add(component1);
panel.add(component2);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/219.html [8/1/2000 7:50:43 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Laying Out Components in a Grid
When components are added to the container, they fill the grid
left-to-right, top-to-bottom.
int rows = 2;
int cols = 2;
// The next two lines should be in one line.
JPanel panel = new JPanel(new GridLayout(
rows, cols));
panel.add(component1);
panel.add(component2);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/220.html [8/1/2000 7:50:43 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Laying Out Components Using Absolute Coordinates
JPanel panel = new JPanel(null);
component.setBounds(x, y, w, h);
panel.add(component);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/221.html [8/1/2000 7:50:44 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Setting a Border
This example lists the various borders that are available.
component.setBorder(
BorderFactory.createEmptyBorder());
component.setBorder(
BorderFactory.createLineBorder(
Color.black));
component.setBorder(
BorderFactory.createEtchedBorder());
component.setBorder(
BorderFactory.createRaisedBevelBorder());
component.setBorder(
BorderFactory.createLoweredBevelBorder());
ImageIcon icon = new ImageIcon("image.gif");
component.setBorder(BorderFactory.createMatteBorder(
-1, -1, -1, -1, icon));
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/222.html [8/1/2000 7:50:44 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Adding a Title to a Border
// Use default border.
TitledBorder titledBorder =
BorderFactory.createTitledBorder("Title");
// Create around existing border.
titledBorder = BorderFactory.createTitledBorder(
border, "Title");
// Also available: DEFAULT_JUSTIFICATION, LEFT,
// RIGHT
titledBorder.setTitleJustification(
TitledBorder.CENTER);
// Also available: DEFAULT_POSITION, ABOVE_TOP, TOP,
// ABOVE_BOTTOM, BOTTOM, BELOW_BOTTOM
titledBorder.setTitlePosition(
TitledBorder.BELOW_TOP);
component.setBorder(titledBorder);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/javax.swing/223.html (1 of 2) [8/1/2000 7:50:50 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Compound Border
// border1 is around border2
Border newBorder =
BorderFactory.createCompoundBorder(border1, border2);
component.setBorder(newBorder);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/224.html [8/1/2000 7:50:51 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining the Available Look and Feels
UIManager.LookAndFeelInfo[] info =
UIManager.getInstalledLookAndFeels();
for (int i=0; i<info.length; i++) {
String humanReadableName = info[i].getName();
String className = info[i].getClassName();
// The className is used with
// UIManager.setLookAndFeel()
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/225.html [8/1/2000 7:50:52 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Setting the Look and Feel
To change the look and feel, you need to know the class name of
the new look and feel. This example changes it to the Windows look
and feel.
try {
// The next three lines should all be in one line.
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.windows.
WindowsLookAndFeel");
} catch (InstantiationException e) {
} catch (ClassNotFoundException e) {
} catch (UnsupportedLookAndFeelException e) {
} catch (IllegalAccessException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing/226.html [8/1/2000 7:50:53 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Painting the Background of a Container with an Image
Pattern
This example shows how to use an image pattern to fill the
background of a container instead of a solid color. The method
used in this example makes use of a TexturePaint object to paint
the image pattern. For information on how to convert an image to
a buffered image, see "Converting an Image to a Buffered Image".
public class ImageBgPanel extends JPanel {
TexturePaint texture;
ImageBgPanel() {
texture = new TexturePaint(bufferedImage,
// The next two lines should be in one line.
new Rectangle(0, 0,
bufferedImage.getWidth(
), bufferedImage.getHeight()));
}
// The class should override this method.
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(texture);
// The next two lines should be in one line.
g2d.fillRect(0, 0, getSize(
).width, getSize().height);
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 25-Jul-2000 ]
http://developer.java.sun.com/developer/codesamples/javax.swing/227.html (1 of 2) [8/1/2000 7:50:53 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing.event
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Handling Hyperlink Events
Hyperlink events are fired by a JEditorPane when the user clicks on
a hyperlink.
try {
String url = "http://java.sun.com";
JEditorPane editorPane = new JEditorPane(url);
editorPane.setEditable(false);
editorPane.addHyperlinkListener(
new MyHyperlinkListener());
} catch (IOException e) {
}
class MyHyperlinkListener implements HyperlinkListener {
public void hyperlinkUpdate(HyperlinkEvent evt) {
if (evt.getEventType() ==
HyperlinkEvent.EventType.ACTIVATED) {
JEditorPane pane =
(JEditorPane)evt.getSource();
try {
// Show the new page in the editor pane.
pane.setPage(evt.getURL());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
http://developer.java.sun.com/developer/codesamples/javax.swing.event/228.html (1 of 2) [8/1/2000 7:50:54 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing.event
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Handling Changes to a List Component
List data events are fired by a ListModel whenever one or more
items are changed, added, or removed.
JList list = new JList(new DefaultListModel());
list.getModel().addListDataListener(
new MyListDataListener());
class MyListDataListener implements ListDataListener {
public void contentsChanged(ListDataEvent evt) {
// A non-contiguous set of items were added,
// removed, or modified.
ListModel model = (ListModel)evt.getSource();
// The next tow lines should be in one line
for (int i=evt.getIndex0(); i<=evt.getIndex1();
i++) {
process(model.getElementAt(i));
}
}
public void intervalAdded(ListDataEvent evt) {
// The items between evt.getIndex0() and
// evt.getIndex1(), inclusive, were added.
ListModel model = (ListModel)evt.getSource();
for (int i=evt.getIndex0();
i<=evt.getIndex1(); i++) {
process(model.getElementAt(i));
}
}
public void intervalRemoved(ListDataEvent evt) {
// The items between evt.getIndex0()
// and evt.getIndex1(), inclusive,
// have been removed.
}
}
http://developer.java.sun.com/developer/codesamples/javax.swing.event/229.html (1 of 2) [8/1/2000 7:50:54 AM]
Code Samples from the Java Developers Almanac 2000
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing.event/229.html (2 of 2) [8/1/2000 7:50:54 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing.filechooser
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Adding a Filter to a File Chooser Dialog
This example add a filter for .java files to the file chooser.
JFileChooser fileChooser =
new JFileChooser(new File(filename));
fileChooser.addChoosableFileFilter(new MyFilter());
// Open file dialog.
fileChooser.showOpenDialog(frame);
openFile(fileChooser.getSelectedFile());
class MyFilter extends
javax.swing.filechooser.FileFilter {
public boolean accept(File file) {
String filename = file.getName();
return filename.endsWith(".java");
}
public String getDescription() {
return "*.java";
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 31-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/javax.swing.filechooser/230.html (1 of 2) [8/1/2000 7:50:55 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing.tree
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating a Tree
This example creates a tree component with a root node and a
child of the root node. You build the tree hierarchy by adding nodes
to nodes.
DefaultMutableTreeNode root =
new DefaultMutableTreeNode("Root Label");
root.add(new DefaultMutableTreeNode(
"Node Label"));
JTree tree = new JTree(root);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing.tree/234.html [8/1/2000 7:50:56 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing.tree
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Handling Selection Events in a Tree Component
This example adds a listener for selection events to a tree
component.
tree.addTreeSelectionListener(
new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent evt) {
DefaultMutableTreeNode node =
(DefaultMutableTreeNode)
(evt.getPath().getLastPathComponent());
process(node);
}
});
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing.tree/235.html [8/1/2000 7:50:57 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing.text
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Inserting Styled Text in a Text Pane
See the StyleConstants class for more attributes.
try {
JTextPane textPane = new JTextPane();
StyledDocument doc =
(StyledDocument)textPane.getDocument();
Style style = doc.addStyle("StyleName", null);
// Italic
StyleConstants.setItalic(style, true);
// Bold
StyleConstants.setBold(style, true);
// Font Family
StyleConstants.setFontFamily(style, "SansSerif");
// Font Size
StyleConstants.setFontSize(style, 30);
// Background Color
StyleConstants.setBackground(style, Color.blue);
// Foreground Color
StyleConstants.setForeground(style, Color.white);
// Append to document.
doc.insertString(doc.getLength(),
"Some Text", style);
} catch (BadLocationException e) {
}
http://developer.java.sun.com/developer/codesamples/javax.swing.text/231.html (1 of 2) [8/1/2000 7:50:57 AM]
Code Samples from the Java Developers Almanac 2000
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing.text/231.html (2 of 2) [8/1/2000 7:50:57 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing.text
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Inserting an Image into a Text Pane
try {
Style style = doc.addStyle("StyleName", null);
StyleConstants.setIcon(style,
new ImageIcon("imagefile"));
doc.insertString(doc.getLength(),
"ignored text", style);
} catch (BadLocationException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing.text/232.html [8/1/2000 7:50:58 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing.text
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Inserting a Component into a Text Pane
try {
Style style = doc.addStyle("StyleName", null);
StyleConstants.setComponent(
style, new JButton("OK"));
doc.insertString(doc.getLength(),
"ignored text", style);
} catch (BadLocationException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing.text/233.html [8/1/2000 7:50:58 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
The Quintessential Java Application
The parameters to the application are made available in ``args''.
public class BasicApp {
public static void main(String[] args) {
for (int i=0; i<args.length; i++) {
// process args[i];
}
}
}
This is the command to run the program:
>java BasicApp param1 param2 ...
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/73.html [8/1/2000 7:50:59 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Exiting a Java Program
// Normal termination.
System.exit(0);
// Abnormal termination.
int errorCode = -1;
System.exit(errorCode);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/74.html [8/1/2000 7:50:59 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
The Quintessential Thread
There are two ways to declare a thread. The first way is to declare
a class that extends Thread. Here is an example followed by code
used to create and start the thread.
class BasicThread1 extends Thread {
public void run() {
// This method is called when the thread runs.
}
}
Thread thread = new BasicThread1();
thread.start();
The second way is to have a class implement Runnable. This
method is typically used when a class makes use of a thread that is
not shared with other classes. This example demonstrates the
typical way in which such classes declare, create, and start a
thread.
class BasicThread2 implements Runnable {
public void run() {
// This method is called when the thread runs.
}
public void aMethod() {
// Create and start a thread.
Thread thread = new Thread(this);
thread.start();
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
http://developer.java.sun.com/developer/codesamples/java.lang/75.html (1 of 2) [8/1/2000 7:51:00 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Making an Object Cloneable
class AnObject implements Cloneable {
public AnObject() {
}
public Object clone() {
AnObject theClone = new AnObject();
// Initialize theClone.
return theClone;
}
}
Here's some code to create a clone.
AnObject anObject = new AnObject();
AnObject copy = (AnObject)anObject.clone();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/76.html [8/1/2000 7:51:00 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Constructing a String
If you are constructing a string with several appends, it may be
more efficient to construct it using a StringBuffer and then convert
it to an immutable String object.
StringBuffer buf = new StringBuffer("Initial Text");
// Modify
int index = 1;
buf.insert(index, "123");
buf.append("456");
buf.delete(1, 4);
buf.replace(12, 15, " XY");
//
//
//
//
// Convert to string
String s = buf.toString();
// Initial Text XY
I123nitial Text
I123nitial Text456
Initial Text456
Initial Text XY
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/77.html [8/1/2000 7:51:01 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting a Substring from a String
int start = 1;
int end = 4;
String substr =
"aString".substring(start, end);
// Str
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/78.html [8/1/2000 7:51:01 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Searching a String
String string = "aString";
// First occurrence.
int index = string.indexOf('S');
// 1
// Last occurrence.
index = string.lastIndexOf('i');
// 4
// Not found.
index = string.lastIndexOf('z');
// -1
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/79.html [8/1/2000 7:51:02 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Replacing Characters in a String
// Replace all occurrences of 'a' with 'o'
String newString = string.replace('a', 'o');
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/80.html [8/1/2000 7:51:02 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Replacing Substrings in a String
static String replace(
String str, String pattern, String replace) {
int s = 0;
int e = 0;
StringBuffer result = new StringBuffer();
while ((e = str.indexOf(pattern, s)) >= 0) {
result.append(str.substring(s, e));
result.append(replace);
s = e+pattern.length();
}
result.append(str.substring(s));
return result.toString();
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/81.html [8/1/2000 7:51:02 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Converting a String to Upper or Lower Case
// Convert to upper case
String upper = string.toUpperCase();
// Convert to lower case
String lower = string.toLowerCase();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/82.html [8/1/2000 7:51:03 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Converting a String to a Number
int i = Integer.parseInt("123");
long l = Long.parseLong("123");
float f = Float.parseFloat("123.4");
double d = Double.parseDouble("123.4e10");
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/83.html [8/1/2000 7:51:03 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems, Inc.
Legal Terms
Shifting Elements in an Array
// Shift all elements right by one
System.arraycopy(array, 0, array, 1, array.length-1);
// Shift all elements left by one
System.arraycopy(array, 1, array, 0, array.length-1);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/84.html [8/1/2000 7:51:04 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Copying Elements from One Array to Another
System.arraycopy(src, 0, dst, 0, Math.min(
src.length, dst.length));
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/85.html [8/1/2000 7:51:04 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Retrieving the SuperClass of an Object
Class supercls = object.getClass().getSuperclass();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/86.html [8/1/2000 7:51:05 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting the Package of an Object
Package pkg = object.getClass().getPackage();
String pkgName = pkg.getName();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/87.html [8/1/2000 7:51:06 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Implementing a Work Queue
The work queue is thread-safe so that multiple threads can
simultaneously add and remove objects from it.
class WorkQueue {
LinkedList queue = new LinkedList();
public synchronized void addWork(Object o) {
queue.addLast(o);
notify();
}
public synchronized Object getWork()
throws InterruptedException {
while (queue.size() == 0) {
wait();
}
return queue.removeFirst();
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/88.html [8/1/2000 7:51:06 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Executes a Command
try {
String command = "ls";
Process child =
Runtime.getRuntime().exec(command);
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/89.html [8/1/2000 7:51:07 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Reading Output from a Command
try {
// Execute command
String command = "ls";
Process child =
Runtime.getRuntime().exec(command);
// Get input stream to read from it
InputStream in = child.getInputStream();
int c;
while ((c = in.read()) != -1) {
process((char)c);
}
in.close();
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/90.html [8/1/2000 7:51:07 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Sending Input to a Command
try {
// Execute command
String command = "cat";
Process child =
Runtime.getRuntime().exec(command);
// Get output stream to write from it
OutputStream out = child.getOutputStream();
out.write("some text".getBytes());
out.close();
} catch (IOException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/91.html [8/1/2000 7:51:08 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Pausing
try {
Thread.sleep(5000); // 5 seconds
} catch (InterruptedException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/92.html [8/1/2000 7:51:08 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting the Current Time
There are two ways of getting the current time.
// One way
long time = System.currentTimeMillis();
// Another way
Date now = new Date();
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/93.html [8/1/2000 7:51:09 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting the Value of a System Property
String dir = System.getProperty("user.dir");
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/94.html [8/1/2000 7:51:09 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Setting the Value of a System Property
String previousValue = System.setProperty(
"application.property", "newValue");
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/95.html [8/1/2000 7:51:10 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Using a Thread-local Variable
static ThreadLocal tlData = new ThreadLocal();
public void aMethod() {
// Retrieve value.
Object o = tlData.get();
// Set value.
tlData.set(o);
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/96.html [8/1/2000 7:51:10 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Loading Native Code
On Windows, loadLibrary(``s'') loads s.dll. On Solaris, it loads s.so.
System.loadLibrary("libraryName");
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/97.html [8/1/2000 7:51:11 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Converting Unicode to UTF-8
try {
String string = "\u5639\u563b";
byte[] utf8 = string.getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/98.html [8/1/2000 7:51:11 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Converting UTF-8 to Unicode
public static String toUnicode(byte[] utf8buf) {
try {
return new String(utf8buf, "UTF8");
} catch (UnsupportedEncodingException e) {
}
return null;
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/99.html [8/1/2000 7:51:12 AM]
Code Samples from the Java Developers Almanac 2000
java.lang
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Determining a Character's Unicode Block
char ch = '\u5639';
Character.UnicodeBlock block =
Character.UnicodeBlock.of(ch);
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/java.lang/100.html [8/1/2000 7:51:12 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating an Initial Context to the Naming Service
This example uses the JNDI/COS naming service provider to
connect to the local tnameserv.
String url = "iiop://localhost/";
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.cosnaming.CNCtxFactory");
env.put(Context.PROVIDER_URL, url);
try {
Context ctx = new InitialContext(env);
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.naming/283.html [8/1/2000 7:51:14 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Looking Up an Object From the Naming Service
This example looks up an object from the naming service.
try {
Object obj = ctx.lookup("Sample");
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.naming/284.html [8/1/2000 7:51:14 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Listing a Context in the Naming Service
This example lists a context in the naming service.
try {
NamingEnumeration enum = ctx.list("child");
while (enum.hasMore()) {
NameClassPair entry =
(NameClassPair)enum.next();
process(entry);
}
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.naming/285.html [8/1/2000 7:51:15 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Adding, Replacing, Removing, and Renaming a Binding
in the Naming Service
try {
// Add a binding.
ctx.bind("Name", new SampleObjectImpl());
// Replace a binding.
ctx.rebind("Name", new SampleObjectImpl());
// Remove a binding.
ctx.unbind("Name");
// Rename a binding.
ctx.rename("Name", "NewSample");
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.naming/286.html [8/1/2000 7:51:15 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating and Destroying a Subcontext in the Naming
Service
This example creates a subcontext in the naming service.
try {
// Create a subcontext.
Context childCtx = ctx.createSubcontext(
"child");
// Destroy the subcontext.
ctx.destroySubcontext(
"child");
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.naming/287.html (1 of 2) [8/1/2000 7:51:16 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting an Object's Fully Qualified Name
This example gets an object's fully qualified name in its own
namespace.
try {
Context obj = (Context)childCtx.lookup(
"grandChild");
String fullname = obj.getNameInNamespace();
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.naming/288.html [8/1/2000 7:51:16 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Using a URL as a Name to the Initial Context
This example looks up an object from the naming service by using
a URL as a name.
try {
Object obj = new InitialContext().lookup(
"iiop://localhost/Sample");
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.naming/289.html [8/1/2000 7:51:17 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Parsing a Composite Name
In the composite name space, forward-slash (/) separates the
composite components.
try {
CompositeName composite = new CompositeName(
"cn=John,o=hits/report/summary.txt");
String first = composite.get(0);
// summary.txt
String last = composite.get(composite.size()-1);
// cn=John,o=hits
// wiz.com/cn=John,o=hits/report/summary.txt
composite.add(0, "wiz.com");
// wiz.com/cn=John,o=hits/summary.txt
composite.remove(2);
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/javax.naming/290.html (1 of 2) [8/1/2000 7:51:17 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Parsing a Compound Name
This example parses a compound name using a parser from an
LDAP service in which components are arranged from right to left,
delimited by the comma character (",").
try {
NameParser parser = ctx.getNameParser("");
Name dn = parser.parse(
"cn=John, ou=People, o=JNDITutorial");
// ou=People
dn.remove(1);
// cn=John,o=JNDITutorial,c=us
dn.add(0, "c=us");
// cn=fs,cn=John,o=JNDITutorial,c=us
dn.add("cn=fs");
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/javax.naming/291.html (1 of 2) [8/1/2000 7:51:18 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming.directory
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating an Initial Context to a Directory
This example uses the JNDI/LDAP service provider to connect to an
LDAP server on the local machine.
String url = "ldap://localhost/o=JNDITutorial";
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
try {
DirContext ctx = new InitialDirContext(env);
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.naming.directory/292.html [8/1/2000 7:51:18 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming.directory
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Reading an Object's Attributes from the Directory
This example reads some of an object's attributes from the
directory.
try {
// Specify the ids of the attributes to return
String[] attrIDs =
{"sn", "telephonenumber", "golfhandicap",
"mail"};
// Get the attributes requested
Attributes answer =
ctx.getAttributes("cn=Ted Geisel,
ou=People", attrIDs);
NamingEnumeration enum = answer.getAll();
while (enum.hasMore()) {
Attribute attr = (Attribute)enum.next();
process(attr);
}
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/javax.naming.directory/293.html (1 of 2) [8/1/2000 7:51:19 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming.directory
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Modifying an Object's Attributes in the Directory
This example modifies some of an object's attributes from the
directory.
try {
// Specify the changes to make
ModificationItem[] mods =
new ModificationItem[3];
// Replace mail attribute with new value
mods[0] = new ModificationItem(
//The next four lines should be in one line
DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute(
"mail",
"[email protected]"));
// Add additional value to "telephonenumber"
mods[1] = new ModificationItem(
DirContext.ADD_ATTRIBUTE,
//The next two lines should be in one line
new BasicAttribute("telephonenumber",
"+1 555 555 5555"));
// Remove jpegphoto
mods[2] = new ModificationItem(
DirContext.REMOVE_ATTRIBUTE,
new BasicAttribute("jpegphoto"));
// Perform requested modifications on named object
// The next three lines should be in one line
ctx.
modifyAttributes("cn=Ted Geisel,
http://developer.java.sun.com/developer/codesamples/javax.naming.directory/294.html (1 of 2) [8/1/2000 7:51:19 AM]
Code Samples from the Java Developers Almanac 2000
ou=People", mods);
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.naming.directory/294.html (2 of 2) [8/1/2000 7:51:19 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming.directory
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Creating an Directory Entry
This example creates an entry in the directory.
try {
// Create attributes to be associated with the
//new entry
// case-ignore
Attributes attrs = new BasicAttributes(true);
Attribute objclass = new BasicAttribute(
"objectclass");
objclass.add("top");
objclass.add("extensibleObject");
attrs.put(objclass);
// Create the context
Context entry = ctx.createSubcontext(
"cn=Sample", attrs);
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/javax.naming.directory/295.html (1 of 2) [8/1/2000 7:51:20 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming.directory
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Adding a Binding with Attributes to the Directory
This example adds a name-to-object binding along with attributes
to the directory.
try {
// Create attributes to be associated with the
// new entry
// case-ignore
Attributes attrs =
new BasicAttributes(true);
Attribute objclass =
new BasicAttribute(
"objectclass");
objclass.add("top");
objclass.add("extensibleObject");
attrs.put(objclass);
// Create the object to be bound
Object obj = new SampleObjectImpl();
// Create the context
ctx.bind("cn=Sample", obj, attrs);
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
http://developer.java.sun.com/developer/codesamples/javax.naming.directory/296.html (1 of 2) [8/1/2000 7:51:20 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming.directory
Code Samples Index
These code examples and other materials are subject to Sun Microsystems, Inc.
Legal Terms
Performing a Basic Directory Search
This example searches the directory for objects that have certain
specified attributes.
try {
// Specify the ids of the attributes to return
String[] attrIDs = {"sn", "telephonenumber",
"golfhandicap", "mail"};
// Specify the attributes to match
// Ask for objects that have attribute "sn" ==
// Geisel and the "mail" attribute
Attributes matchAttrs = new BasicAttributes(
true); // ignore case
matchAttrs.put(new BasicAttribute(
"sn", "Geisel"));
matchAttrs.put(new BasicAttribute("mail"));
// Search for objects with those matching
// attributes
NamingEnumeration enum = ctx.search(
"ou=People", matchAttrs, attrIDs);
while (enum.hasMore()) {
SearchResult entry =
(SearchResult)enum.next();
process(entry);
}
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
http://developer.java.sun.com/developer/codesamples/javax.naming.directory/297.html (1 of 2) [8/1/2000 7:51:21 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming.directory
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Searching the Directory By Using a Search Filter
This example searches the directory for objects by using a search
filter.
try {
// Specify the ids of the attributes to return
String[] attrIDs = {"sn", "telephonenumber",
"golfhandicap", "mail"};
SearchControls ctls = new SearchControls();
ctls.setReturningAttributes(attrIDs);
// Specify the search filter to match
// Ask for objects that have attribute "sn" ==
// Geisel and the "mail" attribute
String filter = "(&(sn=Geisel)(mail=*))";
// Search for objects using filter
NamingEnumeration enum = ctx.search("ou=People",
filter, ctls);
while (enum.hasMore()) {
SearchResult entry = (SearchResult)enum.next();
process(entry);
}
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
http://developer.java.sun.com/developer/codesamples/javax.naming.directory/298.html (1 of 2) [8/1/2000 7:51:21 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming.directory
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Searching a Subtree in the Directory
This example searches a subtree in the directory for objects by
using a search filter.
try {
SearchControls ctls = new SearchControls();
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
// Specify the search filter to match
// Ask for objects that have attribute "sn" ==
// Geisel and the "mail" attribute
String filter = "(&(sn=Geisel)(mail=*))";
// Search for objects using filter
NamingEnumeration enum = ctx.search("", filter,
ctls);
while (enum.hasMore()) {
SearchResult entry = (SearchResult)enum.next();
process(entry);
}
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
http://developer.java.sun.com/developer/codesamples/javax.naming.directory/299.html (1 of 2) [8/1/2000 7:51:22 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming.directory
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Cancelling a Directory Search
This example searches the directory for objects and abandons the
search before it completes.
try {
// Specify the attributes to match
// Ask for objects that have attribute
// "sn" == Geisel and the "mail" attribute
// ignore case
Attributes matchAttrs = new BasicAttributes(true);
matchAttrs.put(new BasicAttribute("sn", "Geisel"));
matchAttrs.put(new BasicAttribute("mail"));
// Search for objects with those matching
// attributes
NamingEnumeration enum = ctx.search("ou=People",
matchAttrs);
if (enum.hasMore()) {
SearchResult entry =
(SearchResult)enum.next();
// Abandon rest of results
enum.close();
}
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
http://developer.java.sun.com/developer/codesamples/javax.naming.directory/300.html (1 of 2) [8/1/2000 7:51:23 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming.directory
Code Samples Index
These code examples and other materials are subject to Sun Microsystems, Inc.
Legal Terms
Getting an Object's Schema from the Directory
This example reads an object's schema from the directory.
try {
// Get context containing class definitions for
//cn=Ted Geisel entry
DirContext tedClasses = ctx.getSchemaClassDefinition(
"cn=Ted Geisel, ou=People");
// Enumerate class definitions
NamingEnumeration enum =
tedClasses.search("", null);
while (enum.hasMore()) {
DirContext entry = (DirContext)enum.next();
process(entry);
}
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.naming.directory/301.html [8/1/2000 7:51:23 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming.directory
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting an Attribute's Schema from the Directory
This example reads an attribute's schema from the directory.
try {
// Get an attribute of that type
Attributes attrs = ctx.getAttributes("cn=Ted Geisel,
ou=People", new String[]{"cn"});
Attribute cnAttr = attrs.get("cn");
// Get its attribute definition
DirContext cnSchema =
cnAttr.getAttributeDefinition();
// Get cnSchema's attributes
Attributes cnAttrs = cnSchema.getAttributes("");
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.naming.directory/302.html [8/1/2000 7:51:24 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming.directory
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Authenticating to the Directory
This example uses the JNDI/LDAP service provider to create an
authenticated session to an LDAP server on the local machine, by
using "simple" authentication.
String url = "ldap://localhost/o=JNDITutorial";
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "userDN");
env.put(Context.SECURITY_CREDENTIALS, "secret");
try {
DirContext ctx = new InitialDirContext(env);
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.naming.directory/303.html [8/1/2000 7:51:24 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming.event
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Registering for Namespace Changes in the Directory
This example registers with the directory to receive notification
when changes are made to the namespace.
try {
// Get event context for registering listener
EventContext ctx = (EventContext)(new
InitialContext(env).lookup("ou=People"));
// Create listener
NamingListener listener =
new SampleNCListener();
// Register listener for namespace change events
ctx.addNamingListener(
"cn=John", EventContext.ONELEVEL_SCOPE,
listener);
} catch (NamingException e) {
}
public class SampleNCListener implements
NamespaceChan
geListener {
public SampleNCListener() {
}
public void objectAdded(NamingEvent evt) {
process(evt.getNewBinding());
}
public void objectRemoved(NamingEvent evt) {
process(evt.getOldBinding());
}
public void objectRenamed(NamingEvent evt) {
process(evt.getOldBinding());
}
http://developer.java.sun.com/developer/codesamples/javax.naming.event/304.html (1 of 2) [8/1/2000 7:51:25 AM]
Code Samples from the Java Developers Almanac 2000
public void namingExceptionThrown(
NamingExceptionEvent evt) {
processException(evt.getException());
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.naming.event/304.html (2 of 2) [8/1/2000 7:51:25 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming.event
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Registering for Object Changes in the Directory
This example registers with the directory to receive notification
when changes are made to objects that have certain attributes.
try {
// Get event context for registering listener
EventDirContext ctx = (EventDirContext)(
new InitialContext(env).lookup("ou=People"));
// Create listener
NamingListener listener =
new SampleObjListener();
// Specify to search the subtree
SearchControls ctls = new SearchControls();
ctls.setSearchScope(
SearchControls.SUBTREE_SCOPE);
// Specify the search filter of objects in which
// you're interested
// Ask for objects that have "mail" attribute
String filter = "(mail=*)";
// Register listener for object change events
ctx.addNamingListener(
"cn=John", filter,
ctls, listener);
} catch (NamingException e) {
}
public class SampleObjListener implements
ObjectChangeListener {
public SampleObjListener() {
}
public void objectChanged(NamingEvent evt) {
http://developer.java.sun.com/developer/codesamples/javax.naming.event/305.html (1 of 2) [8/1/2000 7:51:26 AM]
Code Samples from the Java Developers Almanac 2000
process(evt.getNewBinding());
process(evt.getOldBinding());
}
public void namingExceptionThrown(
NamingExceptionEvent evt) {
processException(evt.getException());
}
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.naming.event/305.html (2 of 2) [8/1/2000 7:51:26 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming.ldap
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Setting LDAP Connection Request Controls
This example uses the JNDI/LDAP service provider to connect to an
LDAP server on the local machine and initializes its connection
request controls.
try {
// Create connection controls to use
Control[] connectCtls = new Control[]{
new SomeControl()};
LdapContext ctx = new InitialLdapContext(
env, connectCtls);
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.naming.ldap/306.html [8/1/2000 7:51:26 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming.ldap
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Setting LDAP Context Request Controls
This example uses the JNDI/LDAP service provider to connect to an
LDAP server on the local machine. It sets the context's request
controls to be a server-side Sort control and then performs a list().
The results of list() will be sorted.
try {
LdapContext ctx = new InitialLdapContext(
env, null);
// Create critical Sort that sorts based on CN
Control[] ctxCtls = new Control[]{
new SortControl(
new String[]{"cn"}, Control.CRITICAL)
};
// Sets context request controls; effect until
// unset
ctx.setRequestControls(ctxCtls);
// Perform list() with controls in effect
NamingEnumeration answer = ctx.list("");
// Enumerate answers
while (answer.hasMore()) {
NameClassPair item =
(NameClassPair)answer.next();
}
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
http://developer.java.sun.com/developer/codesamples/javax.naming.ldap/307.html (1 of 2) [8/1/2000 7:51:27 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming.ldap
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Getting LDAP Response Controls
This example uses the JNDI/LDAP service provider to connect to an
LDAP server on the local machine. It then performs a search and
looks for controls returned with the search responses.
try {
LdapContext ctx = new InitialLdapContext(
env, null);
// Perform search
NamingEnumeration answer = ctx.search(
"ou=People", "(cn=*)", null);
// Examine the response controls (if any)
process(ctx.getResponseControls());
// Enumerate answers
while (answer.hasMore()) {
SearchResult si =
(SearchResult)answer.next();
// Examine the response controls (if any)
if (si instanceof HasControls) {
process(
((HasControls)si).getControls());
}
}
// Examine the response controls (if any)
process(ctx.getResponseControls());
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
http://developer.java.sun.com/developer/codesamples/javax.naming.ldap/308.html (1 of 2) [8/1/2000 7:51:28 AM]
Code Samples from the Java Developers Almanac 2000
javax.naming.ldap
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Performing an LDAP ``Extended'' Operation
This example performs an "extended" operation on an LDAP
context.
try {
LdapContext ctx = new InitialLdapContext(
env, null);
// Create "extended" operation to use
ExtendedRequest req = new GetTimeRequest();
// Perform the operation
GetTimeResponse response = (
GetTimeResponse) ctx.extendedOperation(req);
} catch (NamingException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.naming.ldap/309.html [8/1/2000 7:51:28 AM]
Code Samples from the Java Developers Almanac 2000
javax.rmi
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Starting the Name Server
If you are using RMI over the Java Remote Method Protocol
(JRMP), start up the RMI registry so that you can create and export
remote objects.
> rmiregistry
If you are using RMI over the Internet Inter-ORB Protocol (IIOP),
start up the CORBA Common Object Services (COS) name server
so that you can create and export remote objects.
> tnameserv
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.rmi/310.html [8/1/2000 7:51:29 AM]
Code Samples from the Java Developers Almanac 2000
javax.rmi
Code Samples Index
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
Defining and Exporting a Portable Remote Object
1. Define the remote interface.
import java.rmi.*;
public interface RObject extends Remote {
void aMethod() throws RemoteException;
}
2. Define the portable remote object implementation.
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class RObjectImpl extends UnicastRemoteObject implements RObject {
public RObjectImpl() throws RemoteException {
super();
}
// All remote methods must throw RemoteException
public void aMethod() throws RemoteException {
}
}
3. Compile the remote object implementation.
> javac RObject.java RObjectImpl.java
4. Generate the skeletons and stubs.
Using RMI over IIOP
> rmic -iiop RObjectImpl
Using RMI over JRMP
> rmic RObjectImpl
5. Create an instance of the remote object and bind it to a name service.
import javax.naming.*;
import java.rmi.RemoteException;
// JRMP: name = "rmi://localhost/RObjectServer";
// IIOP: name = "iiop://localhost/RObjectServer";
try {
RObject robj = new RObjectImpl();
new InitialContext().bind(name, robj);
}
catch (NamingException e) {
e.printStackTrace();
}
catch (RemoteException e) {
http://developer.java.sun.com/developer/codesamples/javax.rmi/311.html (1 of 2) [8/1/2000 7:51:30 AM]
Code Samples from the Java Developers Almanac 2000
e.printStackTrace();
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.rmi/311.html (2 of 2) [8/1/2000 7:51:30 AM]
Code Samples from the Java Developers Almanac 2000
javax.rmi
Code Samples Index
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
Looking Up a Portable Remote Object and Invoking a Method
import javax.naming.*;
import java.rmi.RemoteException;
import javax.rmi.PortableRemoteObject;
// JRMP: name = "rmi://localhost/RObjectServer";
// IIOP: name = "iiop://localhost/RObjectServer";
try {
// Look up remote object
Object obj = new InitialContext().lookup(name);
// Cast to the appropriate type
RObject robj = (RObject)PortableRemoteObject.narrow(obj, RObject.class);
// Invoke method on remote object
robj.aMethod();
}
catch (NamingException e) {
}
catch (RemoteException e) {
}
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.rmi/312.html [8/1/2000 7:51:30 AM]
Code Samples from the Java Developers Almanac 2000
javax.swing.undo
Code Samples Index
These code examples and other materials are subject to Sun Microsystems,
Inc. Legal Terms
Adding Undo and Redo to a Text Component
JTextArea textarea = new JTextArea();
final UndoManager undo = new UndoManager();
Document doc = textarea.getDocument();
//The next two lines should be in one line.
doc.addUndoableEditListener(
new UndoableEditListener() {
The next two lines should be in one line.
public void undoableEditHappened(
UndoableEditEvent evt) {
undo.addEdit(evt.getEdit());
}
});
textarea.getActionMap().put("Undo",
new AbstractAction("Undo") {
public void actionPerformed(ActionEvent evt) {
try {
if (undo.canUndo()) {
undo.undo();
}
} catch (CannotUndoException e) {
}
}
});
textarea.getInputMap().put(KeyStroke.getKeyStroke(
"control Z"), "Undo");
textarea.getActionMap().put("Redo",
new AbstractAction("Redo") {
public void actionPerformed(ActionEvent evt) {
try {
if (undo.canRedo()) {
undo.redo();
http://developer.java.sun.com/developer/codesamples/javax.swing.undo/236.html (1 of 2) [8/1/2000 7:51:31 AM]
Code Samples from the Java Developers Almanac 2000
}
} catch (CannotRedoException e) {
}
}
});
textarea.getInputMap().put(KeyStroke.getKeyStroke(
"control Y"), "Redo");
Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
[ This page was updated: 19-Jul-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World
FAQ | Feedback | Map | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's
AT&T Direct Access Number first.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.
http://developer.java.sun.com/developer/codesamples/javax.swing.undo/236.html (2 of 2) [8/1/2000 7:51:31 AM]