19.3 The JTextField Class


JTextField allows the user to enter a single line of text, scrolling the text if its size exceeds the physical size of the field. A JTextField fires an ActionEvent to any registered ActionListeners (including the Action set via the setAction( ) method, if any) when the user presses the Enter key.

JTextFields (and all JTextComponents) are automatically installed with a number of behaviors appropriate to the L&F, so cut/copy/paste, special cursor movement keys, and text-selection gestures should work without any extra intervention on your part.

The following program presents a JTextField for the user to edit (shown in Figure 19-3). The JTextField is initially right-justified, but the justification changes each time the Enter key is pressed.

// JTextFieldExample.java // import javax.swing.*; import java.awt.event.*; public class JTextFieldExample {   public static void main(String[] args) {     final JTextField tf = new JTextField("press <enter>", 20);     tf.setHorizontalAlignment(JTextField.RIGHT);     tf.addActionListener(new ActionListener( ) {         public void actionPerformed(ActionEvent e) {           int old = tf.getHorizontalAlignment( );           if (old == JTextField.LEFT) tf.setHorizontalAlignment(JTextField.RIGHT);           if (old == JTextField.RIGHT) tf.setHorizontalAlignment(JTextField.CENTER);           if (old == JTextField.CENTER) tf.setHorizontalAlignment(JTextField.LEFT);         }       });     JFrame frame = new JFrame("JTextFieldExample");     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     frame.getContentPane( ).setLayout(new java.awt.FlowLayout( ));     frame.getContentPane( ).add(tf);     frame.setSize(275, 75);     frame.setVisible(true);     tf.requestFocus( );   } }
Figure 19-3. JTextFields shown with different alignments
figs/swng2.1903.gif

19.3.1 Properties

Table 19-3 shows the properties defined by JTextField. The document property defaults to a new instance of PlainDocument, and the UIClassID is TextFieldUI.

Table 19-3. JTextField properties

Property

Data type

get

is

set

Default value

accessibleContexto

AccessibleContext

·

   

AccessibleJTextField

action1.3

Action

·

 

·

null

actionCommand

String

   

·

null

actionso

Action[]

·

   

From superclass plus NotifyAction

columns

int

·

 

·

0

documentb, o

Document

·

 

·

PlainDocument( )

fontb, o

Font

·

 

·

From superclass

horizontalAlignmentb

int

·

 

·

LEADING

horizontalVisibility

BoundedRangeModel

·

   

DefaultBoundedRangeModel

preferredSizeb, o

Dimension

·

 

·

Width based on columns and font

scrollOffset

int

·

 

·

From horizontal visibility

UIClassIDo

String

·

   

"TextFieldUI"

validateRooto

boolean

 

·

 

true

1.3since 1.3, bbound, ooverridden

See also properties from the JTextComponent class (Table 19-1).

The value of the accessibleContext property is an AccessibleJTextField, which extends JTextComponent.AccessibleJTextComponent.

The actionCommand string is used in ActionEvents fired by the text field. If a non-null value has not been explicitly set, the current contents of the field are used as the ActionEvent's action command.

action keeps track of an Action associated with this field. The field keeps its enabled and toolTipText properties synchronized with the Action. Also, the Action receives any ActionEvents fired by the field.

The actions property appears here because JTextField adds NotifyAction to the array of utility actions inherited from its superclass. NotifyAction is used to indicate that the contents of the field have been "accepted" by the user, typically by pressing Enter.

The columns property specifies the displayed width of the field, which is unrelated to the length of the field's content (which is generally unbounded). If the value of columns is 0, the width returned by getPreferredSize( ) (unless set explicitly with setPreferredSize( )) is just long enough to display the field's content text and changes when the user adds or deletes characters, which means the displayed field dynamically resizes when it is revalidated under FlowLayout or any other layout manager that respects getPreferredSize( ).[2] If columns is not 0, the width returned by getPreferredSize( ) defaults to columns times the pixel width of the lowercase character m in the field's font. (Unfortunately, it doesn't quite work as it should. The width returned represents the width of the entire component, including the rectangle drawn around the text, so it is often not quite wide enough for the designated number of m characters to fit without scrolling.) The font property is listed in the table because setFont( ) is overridden to update the preferredSize calculation (if necessary) and revalidate the component (so the new font is drawn).

[2] This is actually up to the UI delegate, but existing L&Fs behave as described.

horizontalAlignment indicates where text appears in the field. Valid values are LEFT, CENTER, RIGHT, LEADING, and TRAILING (defined in SwingConstants). LEADING has the same effect as LEFT (and TRAILING as RIGHT) unless the field is in an environment where text reads from right to left.

horizontalVisibility is a BoundedRangeModel (see Chapter 6) that defines the portion of the text displayed if the text is too long for the field. Its minimum is 0, and its maximum is equal to the size of the text field or the total length of the text, whichever is bigger (in pixels). Its extent is the width of the text field (in pixels), and its value is the offset from the beginning of the text currently showing at the left edge of the field. shiftOffset simply provides direct access to horizontalVisibility's value property.

When validateRoot is true, calling revalidate( ) on the JTextField does not revalidate its parent. isValidateRoot( ) is true unless JTextField is contained within a JViewPort.

19.3.2 Events

JTextField objects fire ActionEvents any time the Enter key is pressed, indicating that the user is finished with the field.

The JTextField class contains the following standard methods for working with ActionEvents:

public void addActionListener(ActionListener l)
public void removeActionListener(ActionListener l)
public ActionListener[] getActionListeners( )

Additionally, the following method is provided:

public void postActionEvent( )

Fire an ActionEvent to all registered listeners.

In addition to firing ActionEvents, a JTextField fires a PropertyChangeEvent whenever the horizontalAlignment or action properties are updated.

19.3.3 Constant

JTextField defines the constant shown in Table 19-4.

Table 19-4. JTextField constant

Constant

Type

Description

notifyAction

String

The name of the action used to send notification that the field's contents have been accepted

This action name is used by TextFieldUI implementations to map a keystroke (typically Enter) to the Action provided by JTextField, which notifies listeners that something has been entered in the field.

19.3.4 Constructors

public JTextField( )

Create a new text field with no content. The columns property defaults to 0.

public JTextField(String text)

Create a new text field with the given text. The columns property defaults to 0.

public JTextField(int columns)

Create a new text field with the specified number of columns.

public JTextField(String text, int columns)

Create a new text field with the specified number of columns, displaying the given text.

public JTextField(Document doc, String text, int columns)

Create a new text field that uses the specified document model (covered in detail in Chapter 22) and number of columns. If the string is null, the Document's text is displayed. Otherwise, the string replaces the Document's content and is displayed.

19.3.5 Methods

Almost all the public methods are property accessors or event management methods that have already been covered. The only exception is listed below:

public void scrollRectToVisible(Rectangle r)

Adjust the field's visibility based on the x value of the Rectangle parameter. The other three values of the rectangle (y, width, height) are ignored. It ensures that the specified x-coordinate in pixels (not characters), relative to the leftmost text position, is visible. If the specified x-coordinate is already visible, no scrolling occurs.



Java Swing
Graphic Java 2: Mastering the Jfc, By Geary, 3Rd Edition, Volume 2: Swing
ISBN: 0130796670
EAN: 2147483647
Year: 2001
Pages: 289
Authors: David Geary

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net