Professional Documents
Culture Documents
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
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
(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)
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
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)
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)
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
(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
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
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
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
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]
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.
javax.accessibility
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.accessibility
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.accessibility
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.accessibility
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.accessibility
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.accessibility
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.accessibility
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.applet
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.applet
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.applet
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.applet
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.applet
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.applet
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.applet
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
// 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
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
java.awt.datatransfer
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
// 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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
java.awt.datatransfer
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.dnd
// 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.
} 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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.dnd
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.dnd
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.event
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.event
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.event
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.event
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.event
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.event
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.event
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.font
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.font
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Copyright 1995-2000 Sun Microsystems, Inc. All Rights Reserved. Terms of Use. Privacy Policy.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.font
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.font
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.geom
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.geom
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.geom
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.geom
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util.zip
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
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util.zip
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
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util.zip
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util.zip
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util.jar
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.sql
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.sql
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.sql
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.sql
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.sql
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.sql
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.sql
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
// 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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
// 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
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
// 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
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.util
// 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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.io
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.io
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.io
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.io
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.io
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.io
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.io
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.io
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.io
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.io
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.io
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.io
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.io
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.io
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.io
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.io
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.io
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.io
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.io
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.image
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.image
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.image
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.image
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.image
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.image
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.image
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.image
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.image
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.text
// 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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.text
// 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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.text
// 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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.text
// 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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.text
// 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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.text
// 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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.text
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.text
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.text
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.text
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.text
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.text
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.beans
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.beans
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); }
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan. Order this book from Amazon
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.beans
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.beans
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.beans
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.beans
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.math
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan. Order this book from Amazon
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.math
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan. Order this book from Amazon
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.math
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.net
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.net
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.net
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.net
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.net
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.net
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.net
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.net
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.net
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.net
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.net
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.net
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.net
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.net
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.print
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.print
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.print
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.print
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.print
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.awt.print
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang.ref
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang.ref
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang.ref
java.lang.reflect
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
java.lang.reflect
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
java.lang.reflect
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
java.lang.reflect
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang.reflect
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
java.lang.reflect
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
java.lang.reflect
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang.reflect
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
java.lang.reflect
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
java.lang.reflect
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
java.lang.reflect
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
java.lang.reflect
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
java.lang.reflect
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
java.lang.reflect
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
java.lang.reflect
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
java.lang.reflect
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
java.lang.reflect
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
java.lang.reflect
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
java.lang.reflect
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.rmi
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.rmi
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.rmi
} } } } }
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan. Order this book from Amazon
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.rmi
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());
} } } } }
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan. Order this book from Amazon
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.rmi
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.rmi
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.sound.sampled
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.sound.sampled
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.sound.sampled
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
javax.sound.sampled
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.sound.sampled
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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()));
//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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.sound.sampled
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.sound.sampled
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.sound.sampled
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.sound.sampled
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
// 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
javax.sound.midi
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan. Order this book from Amazon
javax.sound.midi
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.sound.midi
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.sound.midi
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan. Order this book from Amazon
javax.sound.midi
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.sound.midi
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.sound.midi
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.security
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.security
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.security
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.security
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.security
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.security
} } } } }
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan. Order this book from Amazon
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.security
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.security
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.security
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
//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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
// 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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
Creating a Button
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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]
} } }
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan. Order this book from Amazon
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
// 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]); } } } }
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan. Order this book from Amazon
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
// 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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
// 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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
// 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
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
// 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
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
component.setToolTipText("aString");
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan. Order this book from Amazon
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
// 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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
// 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
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.swing
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
javax.swing.event
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
javax.swing.event
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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. } }
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan. Order this book from Amazon
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.swing.filechooser
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
javax.swing.tree
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.swing.tree
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.swing.text
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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) { }
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan. Order this book from Amazon
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.swing.text
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.swing.text
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
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
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan. Order this book from Amazon
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
// Str
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan. Order this book from Amazon
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
Searching a String
String string = "aString"; // First occurrence. int index = string.indexOf('S'); // Last occurrence. index = string.lastIndexOf('i'); // Not found. index = string.lastIndexOf('z');
// 1
// 4
// -1
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan. Order this book from Amazon
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
java.lang
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.naming
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.naming
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.naming
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.naming
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.naming
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.naming
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.naming
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.naming
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
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.naming
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
javax.naming.directory
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.naming.directory
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
javax.naming.directory
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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", "geisel@wizards.com")); // 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,
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.naming.directory
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
javax.naming.directory
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
javax.naming.directory
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
javax.naming.directory
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
javax.naming.directory
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
javax.naming.directory
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
javax.naming.directory
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.naming.directory
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.naming.directory
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.naming.event
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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()); }
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.naming.event
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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) {
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.naming.ldap
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.naming.ldap
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
javax.naming.ldap
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
javax.naming.ldap
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.rmi
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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.rmi
e.printStackTrace(); }
Examplets TM provided by permission of the publisher, Addision-Wesley, and Author Patrick Chan. Order this book from Amazon
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Code Samples Index These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
javax.rmi
// 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
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
javax.swing.undo
These code examples and other materials are subject to Sun Microsystems, Inc. Legal Terms
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]
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.