Java Reference
In-Depth Information
By changing the scrollOffset setting, you can control which part of the text field is visible.
To ensure that the beginning of the contents for the text field is visible, set the scrollOffset
setting to zero. To make sure that the end of the contents is visible, you need to ask the
horizontalVisibility property what the extent of the BoundedRangeModel is, to determine the
width of the range, and then set the scrollOffset setting to the extent setting, as follows:
BoundedRangeModel model = textField.getHorizontalVisibility();
int extent = model.getExtent();
textField.setScrollOffset(extent);
By changing the horizontalAlignment property setting, you can right-, left-, or center-justify
the contents of a JTextField . By default, the text alignment is left-justified. The public void
setHorizontalAlignment(int alignment) method takes an argument of JTextField.LEFT ,
JTextField.CENTER , JTextField.RIGHT , JTextField.LEADING (the default), or JTextField.TRAILING
to specify the contents alignment. Figure 15-5 shows how the alignment setting affects the
contents.
Figure 15-5. Text field alignments
Note You can set the document property, inherited from JTextComponent , to any implementation of the
Document interface. If you use a StyledDocument with a JTextField , the UI delegate will ignore all style
attributes. The StyledDocument interface is discussed in Chapter 16.
JTextComponent Operations with a JTextField
Have you ever looked for an easy way to load or save the contents of a text component? The
Swing text components provide such a method. Additionally, the Swing text components have
built-in support to access the system clipboard for cut, copy, and paste operations. These oper-
ations are possible with all JTextComponent subclasses. They're shown here specifically for the
JTextField because they need a specific implementation to be truly demonstrated. You can
perform the same tasks with the JPasswordField , JTextArea , JEditorPane , and JTextPane .
Loading and Saving Content
With the public void read(Reader in, Object description) and public void write(Writer
out) methods from JTextComponent (both throw an IOException ), you can easily load and save
the contents from any text component. With the read() method, the description argument is
added as a property of the Document data model. This allows you to retain information about
where the data came from. The following example demonstrates how to read in the contents of
file name and store it in textComponent . The file name is automatically retained as the description.
 
Search WWH ::




Custom Search