| You are receiving this e-mail {e-mail address} because you elected to receive e-mail from Sun Microsystems, Inc. To update your communications preferences, please see the link at the bottom of this message. We respect your privacy and post our privacy policy prominently on our Web site http://sun.com/privacy/ |
![]() |
||||||
|
||||||
|
This monthly newsletter provides a way for you to learn the basics of the Java programming language, discover new resources, and keep up-to-date on the latest additions to Sun Developer Network's New to Java Center. You can receive future issues of this newsletter in HTML or text: http://developer.java.sun.com/subscription/ Note: For the code to compile in this issue of Fundamentals, you need to use the JDK 5.0 software. http://java.sun.com/j2se/1.5.0/download.jsp |
||
| Contents | ||
| Java Programming Language Basics | ||
|
Transferring Text Through the Clipboard When you work with the Java Foundation Classes/Swing (JFC/Swing) text components, the cut, copy, and paste operations are automatically handled for you with the help of the EditorKit.
Normally, you do not have to worry about creating code to access the
clipboard. Instead, you ask the EditorKit for its support. To
demonstrate text transfer capabilities, you'll create a program that
manually copies and pastes with a JTextArea and then changes that
program to use EditorKit.
Given a JTextArea (or any JTextComponent), the code to do a copy
operation involves getting the selected text from the component and
placing it on the clipboard:
String selection = jt.getSelectedText();
StringSelection data = new StringSelection(selection);
Clipboard clipboard =
Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(data, data);
The related classes here, StringSelection and Clipboard, are found
in the java.awt.datatransfer package.
Code to do the pasting operation is a little more involved, due to the necessary exceptions you need to handle. First, you get a Transferable object from the clipboard; then, you have fun with flavors. A DataFlavor is a format for transferring data across the
clipboard. If, for instance, the current data on the clipboard is an
image, you won't be able to paste it into a JTextArea as a string.
Provided the format is correct, you get the data and put it into the
text component.
Transferable clipData = clipboard.getContents(clipboard);
if (clipData != null) {
try {
if (clipData.isDataFlavorSupported(DataFlavor.stringFlavor)) {
String s = (String)(clipData.getTransferData(
DataFlavor.stringFlavor));
jt.replaceSelection(s);
}
} catch (UnsupportedFlavorException ufe) {
System.err.println("Flavor unsupported: " + ufe);
} catch (IOException ioe) {
System.err.println("Data not available: " + ioe);
}
}
Putting all this together gives you the following program:
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import javax.swing.*;
import java.io.*;
public class Clip {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("Clip");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Clipboard clipboard =
frame.getToolkit().getSystemClipboard();
final JTextArea jt = new JTextArea();
JScrollPane pane = new JScrollPane(jt);
frame.add(pane, BorderLayout.CENTER);
JButton copy = new JButton("Copy");
copy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selection = jt.getSelectedText();
StringSelection data = new StringSelection(selection);
clipboard.setContents(data, data);
}
});
JButton paste = new JButton("Paste");
paste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
Transferable clipData = clipboard.getContents(clipboard);
if (clipData != null) {
try {
if
(clipData.isDataFlavorSupported
(DataFlavor.stringFlavor)) {
String s = (String)(clipData.getTransferData(
DataFlavor.stringFlavor));
jt.replaceSelection(s);
}
} catch (UnsupportedFlavorException ufe) {
System.err.println("Flavor unsupported: " + ufe);
} catch (IOException ioe) {
System.err.println("Data not available: " + ioe);
}
}
}
});
JPanel p = new JPanel();
p.add(copy);
p.add(paste);
frame.add(p, BorderLayout.SOUTH);
frame.setSize(300, 300);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
You should see an application similar to the image below:
Although the work in this program demonstrates how to transfer text through the clipboard, the custom ActionListener implementations
were unnecessary. You can swap out the two new ActionListener()
calls with something much simpler. Each Swing text component uses an
EditorKit to define the set of actions that can be done with the
component. By default, the kit used is the DefaultEditorKit, which
defines behaviors for copy-and-paste support, as well as cursor
movement and many others.
Behaviors like copy and paste are special Action objects called TextAction. They work by automatically finding the last focused
text component and performing the designated action against them.
To use the actions associated with a text component, you get the list of actions from the text component and find the specific one you are looking for based on keys provided by the EditorKit. This
gives you an ActionListener that you can associate with the JButton
component in this case or with a JMenuItem if there are menus. When
the component is activated, the action is then automatically done
against the last focused text component.
To replace the action handlers in the previous example with the built-in handlers, you would use the following code to get the specific ActionListener objects. Basically, you first create a table
of all the handlers and then look for the specific two of interest.
import javax.swing.text.*; ... // get command table ActionMap actionMap = jt.getActionMap(); // Find specific commands Action copyAction = actionMap.get(DefaultEditorKit.copyAction); Action pasteAction = actionMap.get(DefaultEditorKit.pasteAction);Once you have the handlers, you just attach them to the buttons, and you're done. You don't have to programmatically access the clipboard at all. copy.addActionListener(copyAction); paste.addActionListener(pasteAction);Functionally, the two programs are identical. With the changes, the second version takes advantage of the code already written to do operations on text components. Be sure to see the DefaultEditorKit
class for a list of all the different predefined operations you can
perform.
|
||
| Making Sense of the Java Classes & Tools | ||
|
Class JTextComponent
JTextComponent is the base class for Swing text components. It tries
to be compatible with the java.awt.TextComponent class where it can
reasonably do so. Also provided are other services for additional
flexibility (beyond the pluggable user interface [UI] and bean
support).
Caret Changes The caret is a pluggable object in Swing text components. Notification of changes to the caret position and the selection are sent to implementations of the CaretListener interface that have
been registered with the text component. The UI will install a
default caret unless a customized caret has been set.
By default, the caret tracks all the document changes performed on the Event Dispatching Thread and updates its position accordingly if an insertion occurs before or at the caret position or a removal occurs before the caret position. DefaultCaret tries to make itself
visible, which may lead to scrolling of a text component within
JScrollPane. The default caret behavior can be changed by the
DefaultCaret.setUpdatePolicy(int) method.
Note: Noneditable text components also have a caret, though it may not be painted. Commands Text components provide a number of commands that can be used to manipulate the component. This is essentially the way that the component expresses its capabilities. These are expressed in terms of the swing Action interface, using the TextAction implementation.
The set of commands supported by the text component can be found
with the getActions() method. These actions can be bound to key
events, fired from buttons, and so forth.
Text Input The text components support flexible and internationalized text input, using keymaps and the input method framework, while maintaining compatibility with the AWT listener model. A keymap lets an application bind keystrokes to actions. In order to allow keymaps to be shared across multiple text components, they can use actions that extend TextAction. TextAction can determine which
JTextComponent most recently has or had focus and therefore is the
subject of the action (in the case that the ActionEvent sent to the
action doesn't contain the target text component as its source).
The input method framework lets text components interact with input methods, separate software components that preprocess events to let users enter thousands of different characters using keyboards with far fewer keys. JTextComponent is an active client of the framework, so it
implements the preferred UI for interacting with input methods. As a
consequence, some key events do not reach the text component because
they are handled by an input method; and some text input reaches the
text component as committed text within an InputMethodEvent instead
of as a key event. The complete text input is the combination of the
characters in keyTyped key events and committed text in input method
events.
The AWT listener model lets applications attach event listeners to components in order to bind events to actions. Swing encourages the use of keymaps instead of listeners, but it maintains compatibility with listeners by giving the listeners a chance to steal an event by consuming it. Keyboard events and input method events are handled in the following stages, with each stage capable of consuming the event:
To maintain compatibility with applications that listen to key events but are not aware of input method events, the input method handling in Stage 4 provides a compatibility mode for components that do not process input method events. For these components, the committed text is converted to keyTyped key events and processed in
the key event pipeline starting at Stage 3 instead of in the input
method event pipeline.
By default, the component will create a keymap (named DEFAULT_KEYMAP) that all JTextComponent instances share as the
default keymap. Typically a look-and-feel implementation will
install a different keymap that resolves to the default keymap for
those bindings not found in the different keymap. The minimal
bindings include the following:
The text components have a model-view split. A text component pulls together the objects used to represent the model, view, and controller. The text document model may be shared by other views that act as observers of the model. For example, a document may be shared by multiple components. Read more |
||||||||||||||||||||||
| Java Bits | ||
|
Regular Expressions -- Java Tutorial What Are Regular Expressions? Regular expressions are a way to describe a set of strings based on common characteristics shared by each string in the set. They can be used as a tool to search, edit, or manipulate text or data. You must learn a specific syntax to create regular expressions -- one that goes beyond the normal syntax of the Java programming language. Regular expressions range from simple to quite complex, but once you understand the basics of how they're constructed, you'll be able to understand any regular expression. This tutorial will teach you the regular expression syntax supported by the java.util.regex API (in the API reference documentation), and it will present plenty of working examples to illustrate how the various objects interact. In the world of regular expressions, there are many different flavors to choose from, such as grep, Perl, Tcl, Python, PHP, and awk. The regular expressions in the java.util.regex
API are most similar to Perl.
How Are Regular Expressions Represented in This Package? The java.util.regex package consists of three classes, all of which
are in the API reference documentation: Pattern, Matcher, and
PatternSyntaxException.
In the last few sections in this lesson, we'll explore each class in detail with a separate section devoted to each class. But first, let's learn the details of how regular expressions are created. The next section introduces a simple test harness that we'll use repeatedly to explore how regular expressions are constructed. Test Harness This section defines a reusable test harness to explore the regular expression constructs that the regex API supports. You can run this code with the command java RegexTestHarness. No command-line
arguments are accepted. At runtime, it loads the regular expression
and input data from a plain text file, regex.txt, which resides in
the same directory. This file contains a simple format: the regular
expression appears on the first line, and the input string appears
on the second line. To update the test, simply edit those two lines,
save the file, and run the test again. There is no need to recompile
any code.
The output provides some useful information including the regular expression, the input string, the matched text (if found), and the start and end indices of where the match has occurred. Here's the code:
import java.io.*;
import java.util.regex.*;
public final class RegexTestHarness {
private static String REGEX;
private static String INPUT;
private static BufferedReader br;
private static Pattern pattern;
private static Matcher matcher;
private static boolean found;
public static void main(String[] argv) {
initResources();
processTest();
closeResources();
}
private static void initResources() {
try {
br = new BufferedReader(new FileReader("regex.txt"));
}
catch (FileNotFoundException fnfe) {
System.out.println("Cannot locate input file! "
+fnfe.getMessage());
System.exit(0);
}
try {
REGEX = br.readLine();
INPUT = br.readLine();
} catch (IOException ioe) {}
pattern = Pattern.compile(REGEX);
matcher = pattern.matcher(INPUT);
System.out.println("Current REGEX is: "+REGEX);
System.out.println("Current INPUT is: "+INPUT);
}
private static void processTest() {
while(matcher.find()) {
System.out.println("I found the text \"" + matcher.group() +
"\" starting at index " + matcher.start() +
" and ending at index " + matcher.end() + ".");
found = true;
}
if(!found){
System.out.println("No match found.");
}
}
private static void closeResources() {
try{
br.close();
}catch(IOException ioe){}
}
}
Before continuing with the next section, save and compile this code
to ensure that your development environment supports the
java.util.regex package.
Read more |
||
| Using Assertions in Java Technology | ||
|
By Qusay H. Mahmoud Finding bugs in programs is not an easy task, especially when they are subtle bugs. The process of finding bugs is not exciting, and you may have gone through your program wasting your time trying to find bugs that should not have existed in the first place. Such bugs may exist because you did not understand the specifications correctly. And as Barry Boehm, the father of software economics, put it: If it costs $1 to find and fix a requirement-based problem during the requirements definition process, it can cost $5 to repair it during design, $10 during coding, $20 during unit testing, and as much as $200 after delivery of the system. Thus, finding bugs early on in the software life cycle pays off. You can use assertions to detect errors that may otherwise go unnoticed. Assertions contain Boolean expressions that define the correct state of your program at specific points in the program source code. The designers of the Java platform, however, didn't include support for assertions. Perhaps they viewed exceptions as a superior feature, allowing you to use try/catch/finally to throw an exception instead of aborting the program as in assertions. But the Java 2 Platform, Standard Edition (J2SE) release 1.4 has introduced a built-in assertion facility. This article does the following:
|
||
| What's New on java.net | ||
|
Earth Animations for Education From NASA, by Tom Gaskins You've seen the beautiful images of Earth from space taken by NASA astronauts and satellites. By viewing a series of images one after another like frames of a movie, we can watch changes to the Earth as they happened. You can follow hurricanes moving toward land and observe ice caps contracting. You can replay and study changes due to weather, natural events, and human activities. NASA has assembled dozens of such animations, all free. This article describes how to write Java software that uses the OpenGL graphics interface to display these images on a 3D globe. The Scientific Visualization Studio A team of expert scientists, engineers, and artists at NASA's Scientific Visualization Studio (SVS) carefully compose these animations. This group performs its magic at NASA's Goddard Space Flight Center in Maryland. They have been creating animated visualizations of Earth and space science data for over 15 years. They select images from a seemingly infinite collection of NASA imagery. They design each animation to illustrate a particular phenomenon or event. Here are two examples:
Recently, SVS established an image server to make some of the best earth science animations available programmatically over the Internet to software applications. Currently, about 80 are available; that will grow to over 130 by October 2005. You can see the growing list at the SVS server site. The full SVS catalog contains over 2500 animations and is at the SVS home page. SVS animations dynamically illustrate the formation of what's shown in these static images: The fires in Africa progress southward with the season. The vapor and rain (yellow) flow across the globe as the days progress. You can see more single shots like those shown above at the SVS web site, but they're really meant to be seen in motion, wrapped around a 3D Earth. The SVS web site doesn't do that. You need a software program running on a local computer to get the full effect. You also need the ability to interact with the model by turning the world around and zooming in and out. In this article, I describe a bare-bones program, in order to keep the code easily understandable. The best program for viewing SVS animations is the free and open source program NASA World Wind. SVS Animations in Your Software SVS imagery is designed to be used in educational software. The web service responds to HTTP requests by returning an image. There's a strict protocol and request language, with the request parameters tacked on to what we'd consider a conventional URL. Four steps are required to retrieve and display SVS animations in 3D:
EarthFlicks, the Example Application
The code I'll use to demonstrate and explain all this is a small Java application called EarthFlicks, which is available for download
at the end of this article. EarthFlicks creates two windows: one for
selecting and retrieving animations from SVS, the other for showing
and playing them. Figure 3 shows what it looks like:
Selecting an animation in the table and clicking the Import button causes EarthFlicks to retrieve and cache locally all the images for
that animation. When they are subsequently played, EarthFlicks
recognizes them in the cache and draws the images from there rather
than from the SVS server.
Read the rest of this article |
||
| Live Virtual Course | ||
|
Java Programming Language Workshop (VC-SL-285) The Java Programming Language Workshop course provides students with practical experience in designing a vertical solution for a distributed, multitier application. Students use graphical user interface (GUI) design principles and network communications capabilities to code a functional Java technology application that interacts with a networked database server. The significant amount of lab time illustrates the workshop nature of this course. FORMAT: This course is presented using Sun's web-based Live Virtual Classroom (LVC). The LVC is a dynamic and fully interactive online learning environment that features live teaching, collaboration, and instructor-assisted activities. Sign up |
||
| Sun's Java Technology CD-ROM Courses | ||
|
Java Programming Language (CDJ-275) The Java Programming Language course provides students with a self- paced CD-ROM course that can help experienced programmers learn how to write, compile, and run Java technology applications. This course provides fundamental knowledge about the Java programming language and its runtime environment, object-oriented programming with the Java programming language, creating programs with graphical user interface (GUI) components, handling exceptions, using threads, creating applets, and how input/output and networking work in the Java programming language. Learn more about this course |
||
| Sun's Java Technology Web Courses | ||
|
The Complete Java Technology Bundle (WJB-000) The Complete Java Technology Web Bundle provides you with access to all of Sun's web-based courses concerning Java technology. This series describes a spectrum of technologies including the Java programming language, object-oriented analysis and design, distributed computing with Java technologies, servlets, and Enterprise JavaBeans technology. More specialized technologies include wireless applications using the Java Platform, Micro Edition (Java ME) and the Mobile Information Device (MID) Profile, Java Card technology, and Jini technology. This bundle also allows you to access any new Java technology courses that become available during your subscription period. Learn more |
||
| For More Information | ||
|
The terms "Java Virtual Machine" and "JVM" mean a virtual machine for the Java platform. |
||
| Downloading the Java Platform, Standard Edition (Java SE, formerly known as J2SE) | ||
|
For most Java technology development, you need the class libraries, compiler, tools, and runtime environment provided with the Java SE development kit. Download Java SE Platform Bookmark the Specifications New to Java Center |
||
|
Comments? Send your feedback on the Java Technology Fundamentals Newsletter to: fundamentals_newsletter@sun.com
Find archived issues of the following Java technology developer newsletters or manage your current newsletter subscriptions: https://softwarereg.sun.com/registration/developer/en_US/subscriptions Subscribe to the following newsletters for the latest information about technologies and products in other Java platforms:
PRIVACY STATEMENT Sun respects your online time and privacy. You have received this based on your email preferences. If you would prefer not to receive this information, please follow the steps at the bottom of this message to unsubscribe. IMPORTANT: Please read our Terms of Use, Privacy, and Licensing policies: http://www.sun.com/share/text/termsofuse.html http://www.sun.com/privacy/ http://developer.java.sun.com/berkeley_license.html © 2005 Sun Microsystems, Inc. All Rights Reserved. For information on Sun's trademarks see: http://sun.com/suntrademarks Java, J2EE, J2SE, J2ME, and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. To update your Sun subscription preferences or unsubscribe to Sun news services, click here or use this link https://softwarereg.sun.com/registration/developer/en_US/subscriptions FEEDBACK Comments? Send your feedback on the Java Technology Fundamentals Newsletter to dana.nourie@sun.com Sun Microsystems, Inc. 10 Network Circle, MPK10-209 Menlo Park, CA 94025 US |