Text Components
Optional Reading
We will be using the Creating a GUI with JFC/Swing tutorial from Sun as a Reference source. You are not required to read the entire tutorial, I suggest you skim through it though to use a a supplement to what I give you here.
Swing Text Components
We begin to leave the land of simple components and start to enter the world of more complex components. Not that they are necessarily hard to use, but that they offer more customization than the components you have seen so far.
All of Swing's text components inherit from JTextComponent. This means they all share a basic structure. One of the key elements to this structure is the "model" of the Model-View-Controller. The text component model is implemented by the Document (or its subclasses) object. The Document contains the text that the text component displays.
One of the BIG things added to Java in JDK 1.6 is that the print() command has been upgraded for text components. You can now print the contents of a JTextArea or JEditorPane by calling print and the contents of the component will be printed to the screen, with optional headers and footers as well! This is a major enhancement to the text components usability.
All JTextComponents support basic editing (cut-copy-paset and their accelerator keys).
As we leave our simple JLabels and JButtons, you'll notice that few of the components we will show now (like a JTextField) have a caption. That is because you are supposed to use JLabels for all captions. You use your layout managers (like GridBagLayout) to align your labels and other GUI components within your window.
Again, I have to make the point that I am going to skim the functionality of these components, giving you the most commonly used options. Use the Swing Tutorial in the Optional Reading to get more information. The idea is to give you a brief understanding of some of the features of these components.
JTextField and it's siblings
JTextField holds a single line of text. It only supports a single font and a single color for the text in the JTextField. Three of the common constructors are:
If you pass some text to an JTextField constructor, that text will appear in the JTextField when shown. The third constructor shown lets you set the number of columns in a JTextField.
For any type of text component, a "column" is actually the number of pixels that a lower case "m" takes up when shown in the font assigned to that object. If you make a JTextField with 2 columns, it will not hold the state abbreviation "MD" in any font other than monospaced because "MD" is wider than "mm" in variable spaced fonts.
You can get the text from a JTextField by calling it's getText() method.
JPasswordField is just a JTextField that doesn't echo it's characters out, instead it shows a masking character.
JTextField allows you to type any text in the field, and has no limit on size. JFormattedTextField was introduced in JDK 1.4 to allow you to have more control over what a user can type in a JTextField. JFormattedTextField allows:
If you pass a Date object to JFormatted TextField, you will get a text field that will only allow a valid date to be entered. If you want to have more control, you can use a MaskFormatter to specify a mask that the JTextField will use. The mask can include:
Character |
Description |
---|---|
# | Any valid number, uses Character.isDigit . |
' | Escape character, used to escape any of the special formatting characters. |
U | Any character (Character.isLetter ). All
lowercase letters are mapped to upper case. |
L | Any character (Character.isLetter ). All
upper case letters are mapped to lower case. |
A | Any character or number (Character.isLetter
or Character.isDigit ) |
? | Any character
(Character.isLetter ). |
* | Anything. |
H | Any hex character (0-9, a-f or A-F). |
The code
MaskFormatter formatter = new MaskFormatter("###-####"); formatter.setPlaceholderCharacter('_') JTextField jtf = new JTextField(formatter)
Will result in a JFormattedTextField which will only accept 7 digits. "Empty" spaces will have the "_" character and there will be a hyphen "-" after the third character.
Download and open the Netbeans project textfields. This shows some running examples of the text fields described above.
The window first appears like this
When you type in data, it looks like this
JTextArea
JTextArea is a multi-line text component. You can't embed graphics, and you are still stuck with a single font and a single color. The more typical constructors are:
JTextArea()
JTextArea(String text)
JTextArea(int rows, int columns)
JTextArea(String text, int rows, int columns)
As with JTextFields, rows are based on the width of the lower case "m" character.
JTextArea obviously has a little more functionality than JTextField. First, it can wrap text and optionally break the text at blank space. The two methods that give you this functionality are.
public void setLineWrap (boolean wrap)
Sets the ability to line wrap within the JTextAreapublic void setWrapStyleWord(boolean word)
Sets the ability to line wrap at word boundaries
As with all text components, you can disable the user's ability to modify the contents of the object by turning of the editing function.
public void setEditable(boolean canEdit)
Makes the JTextArea read-only (the user can't modify the contents).
Text area also supports loading in a file directly with the read() method (as shown in the example below.
Remember, components don't have scrolling built in, so if you want your JTextArea to scroll, you have to pass it to a JScrollPane and add the JScrollPane to the container
JTextArea area = new JTextArea(25, 80);
JScrollPane jsp = new JScrollPane(area);
JFrame jf = new JFrame();
jf.add(jsp, BorderLayout.CENTER);
Download and open the Netbeans project jtextarea. Not only does this show how to load in a file directly into the JTextArea, but I've implemented a Print... button that prints the contents of the JTextArea out to your printer.
JEditorPane
Our next step is to look at JEditorPane. JEditorPane is a text component to edit various kinds of content. This component uses different implementations of an internal EditorKit to accomplish its behavior.
However JEditorPane is primarily used as a read only tool. It effectively morphs into the proper kind of text editor for the kind of content it is given. By default, the following types of content are known:
Event though JEditorPane will show the three types of text above, it is primarily used as a read-only viewer of HTML. JEditorPane can load a URL in its constructor or its setPage(URL) method. If you have put your JEditorPane in read-only mode and load HTML, it will even generate HyperlinkEvents which can be listened to by a....wait for it...HyperlinkEventListener! You can user the listener to load in the new page into your JEditorPane.
Now, the above may sound like a browser...and in many ways you could implement an HTML browser with JEditorPane. Notice I said HTML browser, not web browser. The problem is, how many web sites do you know that only display HTML, and don't include javascript, flash, etc... into their web pages. JEditorPane only understands HTML.
This can still be helpful for displaying documentation...but in Java 6 even that ability has been superceded by the Desktop integration behavior of Java. You can pass a URI to the native browser with one line of code:
Desktop.getDesktop().browse(URI)
Download and open the Netbeans project jeditorpane. This is a single JEditorFrame with setEditable(false) called to put it in read-only mode and then listened to with a HyperlinkEventListener.
Since this isn't a browser, if you click on the link, you don't have a "back" button so you are stuck there.
One interesting thing to note, if you call the print() method on a JEditorPane showing HTML, it prints out just fine, graphics, layout, the whole bit.
JTextPane
I'm only going to mention JTextPane very briefly. If you want to learn how to use it, you need to really learn swing better.
JTextPane is a multi-line text component that can contain text with different fonts and colors, images, even embedded Swing components!
One good use for it is to make a log file that shows system messages, with different types of messages in different colors. With the upgraded print() method in Java 6, this is quite useful.
However, JTextPane finally crosses the line for what we should cover in this class. I just mention it so you know that you can create multi-line text documents with colors and fonts that aren't just read-only.