|
Welcome to the Java Technology Fundamentals Newsletter.
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 Programming 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.
Java Programming Language Basics
Getting Started with Tool Tips
The Swing components support the ability to display brief popup messages when the user rests the mouse cursor over them. While the class used to display popup messages is JToolTip, you never create instances directly. Instead, you call the setToolTipText(String text) JComponent, which triggers the text to be displayed at the appropriate time.
To demonstrate, here's a simple program with two buttons that displays different text over each:
import javax.swing.*;
import java.awt.*;
public class ToolTipSample {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("JToolTip Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button1 = new JButton("Hello, World");
button1.setToolTipText("Hello, World");
frame.add(button1, BorderLayout.NORTH);
JButton button2 = new JButton("Goodbye, World");
button2.setToolTipText("Goodbye, World");
frame.add(button2, BorderLayout.SOUTH);
frame.setSize(300, 150);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
Tooltip text is normally one line long. However, if the text string begins with <html> then the contents can be any HTML 3.2 formatted text.
import javax.swing.*;
import java.awt.*;
public class ToolTipSample {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("JToolTip Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button1 = new JButton("Hello, World");
button1.setToolTipText("<HTML><H1>Hello, World</H1>");
frame.add(button1, BorderLayout.NORTH);
JButton button2 = new JButton("Goodbye, World");
button2.setToolTipText("<html><i>Goodbye," +
"<strong>World</strong></i>");
frame.add(button2, BorderLayout.SOUTH);
frame.setSize(300, 150);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
There are various ways to customize the popup tooltip appearance. When the tooltip is defined for a specific component, prior to it being displayed, that component's createToolTip method is called. By overriding this method, you can modify settings like colors and fonts:
By overriding the contains (int x, int y) method of the component, you can also display position-sensitive tool tip text. Combining these two options, gives you the following button component:
JButton button1 = new JButton("Hello, World") {
public JToolTip createToolTip() {
JToolTip tip = super.createToolTip();
tip.setBackground(Color.YELLOW);
tip.setForeground(Color.RED);
return tip;
}
public boolean contains(int x, int y) {
if (x < 50) {
setToolTipText("Got Green Eggs?");
} else {
setToolTipText("Got Ham?");
}
return super.contains(x, y);
}
};
Although the JToolTip is something of a passive object, in the sense that the JComponent creates and shows the JToolTip on its own, there are many more configurable aspects of its usage. However, these configurable aspects are the responsibility of the class that manages tooltips, and not the JToolTip itself. The class that manages tooltip usage is aptly named ToolTipManager.
With the Singleton design pattern, no constructor for ToolTipManager exists. Instead, you have access to the current manager through the static sharedInstance() method of ToolTipManager.
Once you have accessed the shared instance of ToolTipManager, you can customize when and if the tooltip text appears. There are five configurable properties:
dismissDelay
enabled
initialDelay
lightWeightPopupEnabled
reshowDelay
Initially, tooltips are enabled, but you can disable them with ToolTipManager.sharedInstance().setEnabled(false). This allows you to always associate tooltips with components, while letting the end user enable/disable them when desired.
There are three timing-oriented properties: initialDelay, dismissDelay, and reshowDelay. They all measure time in milliseconds. The initialDelay property is the number of milliseconds the user must rest the mouse inside the component before the appropriate tooltip text appears. The dismissDelay specifies the length of time the text appears while the mouse remains motionless; if the user moves the mouse, it also causes the text to disappear. The reshowDelay determines how long a user must remain outside a component before reentry would cause the popup text to reappear.
The remaining, property, lightWeightPopupEnabled is used to determine the popup window type to hold the tooltip text. If the property is true and the popup text fits entirely within the bounds of the top-level window, the text appears within a Swing JPanel. If this property is false and the popup text fits entirely within the bounds of the top-level window, the text appears within an AWT Panel. If part of the text wouldn't appear within the top-level window no matter what the property setting is, the popup text would appear within a Window.
Through careful use of the tooltips, your programs can be made more user-friendly. Don't abuse customizations though. While it is nice to be able to be creative and have custom behaviors and timings, once you move outside the norms of expectations, a user experience can suffer greatly.
Test what you learned with this online quiz.
Making Sense of the Java Classes
Code Conventions & Basic Tools
Code Conventions for the Java Programming Language contain the standard conventions that we at Sun follow and recommend that others follow. It covers filenames, file organization, indentation, comments, declarations, statements, white space, naming conventions, programming practices, and code examples.
Why have code conventions? Code conventions are important to programmers for a number of reasons:
- 80% of the lifetime cost of a piece of software goes to maintenance.
- Hardly any software is maintained for its whole life by the original author.
- Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.
Read the Code Conventions for the Java Programming Language.
These tools are the foundation of the JDK. They are the tools you use to create and build applications.
javac -- The compiler for the Java programming language.
java -- The launcher for Java applications. In this release, a single launcher is used both for development and deployment. The old deployment launcher, jre, is no longer provided.
javadoc -- API documentation generator. Javadoc is a tool that parses the declarations and documentation comments in a set of source files and produces a set of HTML pages describing the classes, interfaces, constructors, methods, and fields.
apt -- Annotation processing tool. apt is a command-line utility for annotation processing. It includes a set of reflective APIs and supporting infrastructure to process program annotations (JSR 175). These reflective APIs provide a build-time, source-based, read-only view of program structure.
appletviewer -- Run and debug applets without a web browser.
jar -- Create and manage Java Archive (JAR) files. JAR is a platform-independent file format that aggregates many files into one. Multiple Java applets and their requisite components (.class files, images and sounds) can be bundled in a JAR file and subsequently downloaded to a browser in a single HTTP transaction, greatly improving the download speed. The JAR format also supports compression, which reduces the file size, further improving the download time.
jdb -- The Java Debugger. The Java Platform Debugger Architecture (JPDA) consists of three interfaces designed for use by debuggers in development environments for desktop systems.
javah -- C header and stub generator. Used to write native methods.
javap -- Class file disassembler.
extcheck -- Utility to detect JAR conflicts.
Java Bits
JavaServer Pages Technology - White Paper
The JavaServer Pages (JSP) technology provides a simplified, fast way to create web pages that display dynamically-generated content. JSP technology was designed to make it easier and faster to build web-based applications that work with a wide variety of web servers, application servers, browsers and development tools.
This paper provides an overview of JSP technology, describing the background in which it was developed and the overall goals for the technology. It also describes the key components of a Java technology-based page, in the context of a simple example.
Developing Web-Based Applications: A Background.
In its short history, the World Wide Web (WWW) has evolved from a network of basically static information displays to a mechanism for trading stocks and buying books. There is no limit to the possible uses for web-based clients in diverse applications.
Applications that can make use of browser-based clients have several advantages over traditional client/server based applications. These include nearly unlimited client access and greatly simplified application deployment and management. To update an application, a developer only needs to change one server-based program, not thousands of client-installed applications. As a result, the software industry is moving quickly toward building multi-tiered applications using browser-based clients.
These increasingly sophisticated web-based applications require changes in development technology. Static HTML is fine for displaying relatively static content; the challenge has been creating interactive web-based applications, in which the content of the page is based on user requests or system status, not pre-defined text.
An early solution to this problem was the cgi-bin interface;
developers wrote individual programs to this interface, and web-based applications called the programs through the web server. This solution has significant scalability problems -- each new CGI request launches a new process on the server. If multiple users access the program concurrently, these processes consume all of the web server's available resources and performance slows to a grind.
Individual web server vendors have tried to simplify web application development, providing plug-ins and APIs for their servers. These solutions are web-server specific, and don't address the problem across multiple vendor solutions. For example, Microsoft's Active Server Pages (ASP) technology makes it easier to create dynamic content on a web page, but only works with Microsoft IIS or Personal Web Server.
Other solutions exist, but they are not necessarily easy for the average page designer to deploy. Technologies such as Java Servlets, for example, make it easier to write server-based code using the Java programming language for interactive applications. A Java Servlet is a Java technology-based program that runs on the server (as opposed to an applet, which runs on the browser). Developers can write Servlets that take an HTTP request from the web browser, generate the response dynamically (possibly querying databases to fulfill the request) and then send a response containing an HTML or XML document to the browser.
Using this approach, the entire page must be composed in the Java Servlet. If a developer or web master wanted to tune the appearance of the page, they would have to edit and recompile the Java Servlet, even if the logic were already working. With this approach, generating pages with dynamic content still requires application development expertise.
Read more
Tiger Tips
Sizeof for Java & StringBuilder
From Sundararajan Athijegannathan
Sizeof for Java
The sizeof operator is not available in Java, but sometimes you may want to know the size of Java objects. The size of an object depends on the number of header words in an object, pointer size (32/64 bit), and alignment variations that make object size dependent on VM implementation.
With JDK 5.0, you can get size in two new ways without using profilers or native agents:
- Use
java.lang.instrument.Instrument.getObjectSize API.
- Use
jmap -histo to get object histogram. For each class, jmap prints number of objects and total size in bytes occupied by those objects. Divide total size by number of objects to get size of an individual object.
From Viswadeep Veguru
StringBuilder
If you have a large number of StringBuffer operations, at least 10,000 operations, and don't have heavy thread access to that StringBuffer, consider using the new unsynchronized StringBuilder. StringBuilder is not thread safe, but you can manage locks/monitors access and get better performance.
Program Challenge
Create a JTree that shows custom tooltip text over each tree cell.
See possible solution.
What's New on Java.net
New Online Books & new2java Additions
Unlike an online bookstore, Safari Bookshelf is a fully-searchable virtual library that houses a vast collection of technical books from industry-leading publishers.
Visit the new2java project to read the new additions. One of our members has added to the Favorite Java Educational Resources area in Documents & Files.
In addition, a new section, called Code Challenges, and online quizzes has been added to challenge your Java programming knowledge and expertise.
Register and add to the new2java project by sharing your favorite Java information resources, your coding projects, and conversation to the forums.
Sun's Online Java Sessions: Java Online
Learn what's on the horizon for J2SE technology development from the Java technology engineers themselves.
Read more
Sun's Instructor-Led Java Courses: GUI Construction With Java Foundation Classes (SL-320)
Designing a human interface for computer systems is an essential part of creating applications. This course provides a technical introduction to the Java technology interface controls that implement effective user interfaces.
Read more
For More Information
Downloading the Java 2 Platform
For most Java development, you need the class libraries, compiler, tools, and runtime environment provided with the J2SE development kit.
As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform.
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:
- Core Java Technologies Newsletter. Learn about new products, tools, resources, and events of interest to developers working with core Java technologies.
- Mobility Developer Newsletter. Learn about the latest releases, tools, and resources for developers working on wireless and Java Card technologies and applications.
- Core Java Technologies Tech Tips (formerly JDC Tech Tips) Get expert tips, sample code solutions, and techniques for developing in the Java 2 Platform, Standard Edition (J2SE)
You can subscribe to these and other JDC publications on the JDC Newsletters and Publications page
PRIVACY STATEMENT:
Sun respects your online time and privacy. You have received this based on your e-mail 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
Copyright 2004 Sun Microsystems, Inc.
All rights reserved. Sun Microsystems, Inc. 10 Network Circle, MPK10-209 Menlo Park, CA 94025 US
FEEDBACK
Comments? Send your feedback on the Java Technology Fundamentals Newsletter to: dana.nourie@sun.com
SUBSCRIBE/UNSUBSCRIBE
- To subscribe, go to the subscriptions page, choose the newsletters you want to subscribe to and click Update
- To unsubscribe, go to the subscriptions page, uncheck the appropriate check box, and click Update
Trademark Information: http://www.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.
|