|
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/ Please do not reply to the mailed version of the newsletter, this alias is not monitored. Feedback options are listed in the footer for both content and delivery issues. |
![]() |
||||||
|
||||||
|
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 in this issue of Fundamentals to compile, you need to use the JDK 5.0 software. http://java.sun.com/j2se/1.5.0/download.jsp |
||
| Contents | ||
| Java Programming Language Basics | ||
|
Understanding the Caret and Highlighter Interfaces of Text Components
The Caret and Highlighter interfaces are two aspects of text
components that control the view of the current text. The Caret
interface describes what's usually referred to as the cursor: the
location in the document where you can insert text. The Highlighter
interface provides the basis for painting selected text. These two
interfaces, their related interfaces, and their implementations are
rarely altered. The text components simply use their default
implementations with the DefaultCaret and DefaultHighlighter
classes.Although you probably won't alter the caret and highlighter behavior for a text component, you should know that many interrelated classes are working together. For the Highlighter interface, the predefined
implementation is called DefaultHighlighter, which extends another
implementation called LayeredHighlighter. The Highlighter also
manages a collection of Highlighter.Highlight objects to designate
highlighted sections.The DefaultHighlighter creates a DefaultHighlighter.HighlightPainter
to paint highlighted sections of text. The HighlightPainter is an
implementation of the Highlighter.HighlightPainter interface and
extends the LayeredHighlighter.LayerPainter class. Each section to
be painted is described by a Highlighter.Highlight, where the
Highlighter manages the set. The actual HighlightPainter is created
by the DefaultCaret implementation.To return to the concrete from the abstract, the Highlighter
interface describes how to paint selected text within a text
component.
public interface Highlighter {
// Properties
public Highlighter.Highlight[ ] getHighlights()
// Other Methods
public Object addHighlight(
int p0, int p1, Highlighter.HighlightPainter p)
throws BadLocationException
public void changeHighlight(Object tag, int p0, int p1)
throws BadLocationException
public void deinstall(JTextComponent component)
public void install(JTextComponent component)
public void paint(Graphics g)
public void removeAllHighlights()
public void removeHighlight(Object tag)
}
If you don't like the color of the highlighted text, call either the
setSelectionColor() or setSelectedTextColor() methods of
JTextComponent.The Caret interface describes the current cursor, as well as several
selection attributes. Of the Highlighter and Caret interfaces, the
latter is the one that you'd actually use, although subclassing it
isn't necessary.
public interface Caret {
// Properties
public int getBlinkRate()
public void setBlinkRate(int newValue)
public int getDot()
public void setDot(int newValue)
public Point getMagicCaretPosition()
public void setMagicCaretPosition(Point newValue)
public int getMark()
public boolean isSelectionVisible()
public void setSelectionVisible(boolean newValue)
public boolean isVisible()
public void setVisible(boolean newValue)
// Listeners
public void addChangeListener(ChangeListener l)
public void removeChangeListener(ChangeListener l)
// Other Methods
public void deinstall(JTextComponent c)
public void install(JTextComponent c)
public void moveDot(int dot)
public void paint(Graphics g)
}
The blinkRate represents the millisecond delay between the flashes
of the caret. The dot property represents the cursor's current
position within the text component. To move the cursor to another
position so that some text will be highlighted, call the moveDot(int
newPosition) method. This sets the mark property to the old dot
position and sets the new dot setting to the new position.Other than the self-explanatory visibility properties, the one remaining property is the magicCaretPosition property. This property
deals with moving up and down lines of different lengths. For
instance, in the three lines of text that follow this paragraph,
imagine that the current cursor position is between the n and g on
the first line. If you pressed the down arrow twice, you'd want the
cursor to stay at the same horizontal position, instead of moving to
the end of the shorter second line. It's the magicCursorPosition
property that retains this information, such that the cursor ends up
being between the D and the o in the third line. Without the magic
position retained, the cursor would fall in between the p and the
word space of the last line.Friz Freleng Mel Blanc What's up Doc?One useful instance of using the caret is finding the current screen location in response to a keystroke. That way, you can pop up a menu at the current cursor position. Given the current dot location in the model, map it to the position in the view with the public Rectangle modelToView(int position)
method of JTextComponent (which can throw a BadLocationException).
Then, use the top-left corner of the Rectangle returned as the
location to pop up the menu.The following program shows a JPopupMenu at the location where the
period (".") key is pressed in the text field.
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.plaf.*;
import java.awt.*;
import java.awt.event.*;
public class PopupSample {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("Popup Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPopupMenu popup = new JPopupMenu();
JMenuItem menuItem1 = new JMenuItem("Option 1");
popup.add(menuItem1);
JMenuItem menuItem2 = new JMenuItem("Option 2");
popup.add(menuItem2);
final JTextField textField = new JTextField();
frame.add(textField, BorderLayout.NORTH);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
try {
int dotPosition = textField.getCaretPosition();
Rectangle popupLocation =
textField.modelToView(dotPosition);
popup.show(textField, popupLocation.x, popupLocation.y);
} catch (BadLocationException badLocationException) {
System.err.println("Oops");
}
}
};
KeyStroke keystroke =
KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, 0, false);
textField.registerKeyboardAction(actionListener, keystroke,
JComponent.WHEN_FOCUSED);
frame.setSize(250, 150);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
When you run the code, it should look something like this:![]() Two support bits of working with carets are the CaretListener
interface and its related CaretEvent class. If you want to listen
for cursor movements, you have two ways to do so. You can associate
either a ChangeListener with the Caret or a CaretListener with the
JTextComponent. Working directly with the JTextComponent is the
easier approach, though both will function equally well.In the case of the CaretListener, a single method is defined by the
interface:
public interface CaretListener implements EventListener {
public void caretUpdate(CaretEvent caretEvent)
}
When the listener is notified, a CaretEvent is sent, which reports
on the new dot and mark locations.
public abstract class CaretEvent extends EventObject {
public CaretEvent(Object source)
public abstract int getDot()
public abstract int getMark()
}
To demonstrate, the following program has a CaretListener attached
to the inner JTextArea. When the CaretEvent happens, the current
dot value is sent toJTextArea the top text field, and the current mark
setting is sent to the bottom.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
public class CaretSample {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("Caret Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
frame.add(scrollPane, BorderLayout.CENTER);
final JTextField dot = new JTextField();
dot.setEditable(false);
JPanel dotPanel = new JPanel(new BorderLayout());
dotPanel.add(new JLabel("Dot: "), BorderLayout.WEST);
dotPanel.add(dot, BorderLayout.CENTER);
frame.add(dotPanel, BorderLayout.NORTH);
final JTextField mark = new JTextField();
mark.setEditable(false);
JPanel markPanel = new JPanel(new BorderLayout());
markPanel.add(new JLabel("Mark: "), BorderLayout.WEST);
markPanel.add(mark, BorderLayout.CENTER);
frame.add(markPanel, BorderLayout.SOUTH);
CaretListener listener = new CaretListener() {
public void caretUpdate(CaretEvent caretEvent) {
dot.setText(Integer.toString(caretEvent.getDot()));
mark.setText(Integer.toString(caretEvent.getMark()));
}
};
textArea.addCaretListener(listener);
frame.setSize(250, 150);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
When you run the code, it should look something like this:![]() You can limit where the caret can go by associating a NavigationFilter with a JTextComponent. The class has three methods:
JTextArea.Imagine this being like the title of a
report. If you try to set or move the caret (dot) to the reserved
area, the filter rejects the change and moves the caret to after the
area.
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import java.awt.*;
public class NavigationSample {
private static final String START_STRING = "Start\n";
private static final int START_STRING_LENGTH =
START_STRING.length();
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("Navigation Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea textArea = new JTextArea(START_STRING);
textArea.setCaretPosition(START_STRING_LENGTH);
JScrollPane scrollPane = new JScrollPane(textArea);
frame.add(scrollPane, BorderLayout.CENTER);
NavigationFilter filter = new NavigationFilter() {
public void setDot(
NavigationFilter.FilterBypass fb, int dot,
Position.Bias bias) {
if (dot < START_STRING_LENGTH) {
fb.setDot(START_STRING_LENGTH, bias);
} else {
fb.setDot(dot, bias);
}
}
public void moveDot(
NavigationFilter.FilterBypass fb, int dot,
Position.Bias bias) {
if (dot < START_STRING_LENGTH) {
fb.setDot(START_STRING_LENGTH, bias);
} else {
fb.setDot(dot, bias);
}
}
};
textArea.setNavigationFilter(filter);
frame.setSize(250, 150);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
The following screen shot shows the screen after typing some information into the text component:![]() And that's all there is to do with carets and highlighters. For more information, see the Text Component Features lesson of The Java Tutorial. |
||
| Making Sense of the Java Classes & Tools | ||
|
Lesson: Accessing System Resources Sometimes a program requires access to system resources such as system properties, standard input and output, or the current time. Your program could make system calls directly to the window or operating system, but then your program would be able to run only in that particular environment. Each time you wanted to run the program in a new environment, you'd have to port your program by rewriting the system-dependent sections of code. The Java platform lets your program access system resources through a (relatively) system-independent API implemented by the System class and through a system-dependent API implemented by the Runtime class. Purity Tip: Some of the system resources available through theMost system programming needs are met through the System class.
However, in rare cases, a program might have to access the system
through the Runtime object that represents the current runtime
environment. The last section of this lesson, The Runtime Object,
explains how to do this and talks about the trade-offs of accessing
the system directly through the Runtime object.The following diagram shows that the System class allows your Java
programs to use system resources but insulates them from system-
specific details.
Read more about using the System class. |
||
| Java Bits | ||
|
Creating and Deriving Fonts - Java Tutorial You can display a text string with any font available on your system in any size and style that you choose. To determine what fonts are available on your system, you can call the GraphicsEnvironment.getAvailableFontFamilyNames method. This method
returns an array of strings that contains the family names of the
available fonts. Any of the strings, along with a size and style
argument, can be used to create a new Font object. After creating a
Font object, you can reset its font family name, size, or style to
create a custom font.The following live applet in this tutorial allows you to change the font, size, and style of the displayed text. Read how it was created |
||
| What's New on java.net | ||
|
Java Tech: Generics and You, by Jeff Friesen How much do you know about generics? Based on your amount of generics knowledge, are you comfortable with having to maintain another developer's generified code, should your project manager tell you to do so? Perhaps you have not taken the time to determine how much you know about generics and how much you still have to learn. If you would like to assess your generics I.Q., you might find this article a helpful test of your generics knowledge. Note: This article bases its content on a very useful and extensive generics FAQ that I discovered a couple of months ago. After you finish this article, do yourself a favor by checking out the FAQ, listed in the Resources section at the end of the article. Take the test |
||
| Program Challenge | ||
|
The Toolkit class allows you to get and set the current status of
the Num Lock, Caps Lock, and Scroll Lock keys (Kana Lock, too, if
you have a kanji keyboard). Create a program with text input that
shows the current status of these keys along a status bar along the
bottom of the frame.
See a possible solution |
||
| Customize Your JList Display, by John O'Conner | ||
|
The Java platform's Java Foundation Classes/Swing (JFC/Swing) components are a complete package of graphical user interface (GUI) widgets. By using Swing components, you can create rich, easy-to-use GUIs in your applications. Using these components can greatly improve your application's user-friendliness. This article focuses on one component, the javax.swing.JList object, and shows you how to customize what it displays to the user. The Problem A javax.swing.JList object displays a list of objects in a GUI. It
doesn't display everything about those objects. Instead, by default,
it displays the returned value of the object's toString method.
Imagine that your application displays a list of java.util.Locale
objects to your customer. In a sophisticated application, selecting
from this list could change the application's user interface
language.Consider how JList displays a data model containing Locale objects.
The JList delegates the display of these objects to a
javax.swing.ListCellRenderer. As expected, the ListCellRenderer will
display the text returned from the object's toString method.
However, Locale objects return ISO codes, and these codes aren't
especially user-friendly. The default behavior of JList displays
something that most customers will not understand, as Figure 1
shows.![]() Here is another example of how the default behavior of JList doesn't
provide anything of significant value to the end user in its
display. Imagine that your drawing application provides a list of
colors. Presumably, you can use this color list to fill shapes or
draw colored lines. Although putting java.awt.Color objects into a
JList is a perfectly reasonable use of JList, most people will not
find the displayed results helpful. In Figure 2, a list of Color
objects is in the right (BorderLayout.EAST) side of the
javax.swing.JFrame.![]() A Color object's toString method reports the red, green, and blue
(RGB) color intensities of whatever color it represents. Unless your
customers know that the third line's values -- 255, 200, 0 -- are
the RGB values of the color orange, you should display something
different here. The color name or the color itself seems appropriate
in a color list, but you won't get that by default.Sure, you could place java.lang.String objects into the list instead
of the actual Color objects themselves. However, this defeats the
purpose of the JList: You want your user to pick a color -- not just
a string of text -- from the list.Using a Color object, your list returns an actual Color to your list
change listeners. If you use a String instead, the list would return
a String to listeners, and then the listeners would have to map that
value to an actual Color in order to fill a shape or draw a colored
line.If the user is selecting colors, then it makes sense to put actual Color objects in the list. However, as you can see, we have to do
something about the display of those colors. The default behavior
isn't acceptable for Color or Locale objects, nor will it be useful
for most other objects.
Read the rest of this article |
||
| Sun's Java Technology CD-ROM Courses | ||
|
Web Component Development With Servlet and JSP Technology (CDJ-314) The Web Component Development With Java Servlet and JavaServer Pages (JSP) Technology course provides students with a way to quickly obtain the skills necessary to build Java Server Pages and their accompanying Java Servlet code rapidly and effectively. Experienced Java programming language developers will benefit from the optional real-world lab exercises that can be downloaded into the workplace. This course also provides an alternative method of preparing for the Sun Certified Web Component Developer certification examination. The training provided is accurate and up-to-date, providing new insights into not only Java technology but also into how to best apply them in enterprise environments. As an additional value, students of this web bundle will have access for the duration of this course to the following Quick Reference Guides: HTML, HTTP, the Tomcat Server, the ANT Tool, XML, and UML. Learn more about this course |
||
| Sun's Java Technology Web Courses | ||
|
Fundamentals of the Java Programming Language (WJB-110A) The Fundamentals of the Java Programming Language course provides students who have little or no programming experience with the basics of programming using the Java programming language. This course teaches the significance of object-oriented programming, the keywords and constructs of the Java programming language, and the steps required to create simple Java technology programs. Students taking this course receive a solid basis in the Java programming language upon which to base continued work and training. Learn more about this course |
||
| Free Developers Tools | ||
|
Sun is offering the award-winning Sun Java Studio Enterprise and Sun Java Studio Creator IDEs at no cost to all developers worldwide who join Sun Developer Network (SDN). Get your free tools |
||
| 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 |