Você está na página 1de 6

http://docs.oracle.com/javase/tutorial/uiswing/components/textfield.

html

How to Use Text Fields


Text field is a basic text control that enables the user to type a small amount of text. When the user indicates that text entry is complete (usually by pressing Enter), the text field fires an action event. If you need to obtain more than one line of input from the user, use a text area. The S ing !"I provides several classes for components that are either varieties of text fields or that include text fields. What this section covers# basic text fields. ! JTextField subclass that allo s you to specify the legal JFormattedTextField set of characters that the user can enter. See $o to %se &ormatted Text &ields. ! JTextField subclass that does not sho the characters JPasswordField that the user types. See $o to %se "ass ord &ields. 'an be edited, and provides a menu of strings to choose JComboBox from. See $o to %se 'ombo (oxes. 'ombines a formatted text field ith a couple of small J pinner buttons that enables the user to choose the previous or next available value. See $o to %se Spinners.
JTextField

The follo ing example displays a basic text field and a text area. The text field is editable. The text area is not editable. When the user presses Enter in the text field, the program copies the text field)s contents to the text area, and then selects all the text in the text field.

'lic* the +aunch button to run Text,emo using -ava. Web Start (do nload -,/ 0 or later). !lternatively, to compile and run the example yourself, consult the example index.

1ou can find the entire code for this program in Text!emo.java. The follo ing code creates and sets up the text field#

textField"#"new"JTextField$%&'(

The integer argument passed to the JTextField constructor, %& in the example, indicates the number of columns in the field. This number is used along ith metrics provided by the field)s current font to calculate the field)s preferred idth. It does not limit the number of characters the user can enter. To do that, you can either use a formatted text field or a document listener, as described in Text 'omponent &eatures. Note: We encourage you to specify the number of columns for each text field. If you do not specify the number of columns or a preferred si2e, then the field)s preferred si2e changes henever the text changes, hich can result in un anted layout updates.

The next line of code registers a Text!emo ob3ect as an action listener for the text field.
textField.add)ction*istener$this'(

The actionPerformed method handles action events from the text field#
private"final"static" tring"newline"#"+,n+( ... public"void"actionPerformed$)ction-vent"evt'". """" tring"text"#"textField.getText$'( """"text)rea.append$text"/"newline'( """"textField.select)ll$'( 0

4otice the use of JTextField)s getText method to retrieve the text currently contained by the text field. The text returned by this method does not include a ne line character for the Enter *ey that fired the action event. 1ou have seen ho a basic text field can be used. (ecause the JTextField class inherits from the JTextComponent class, text fields are very flexible and can be customi2ed almost any ay you li*e. &or example, you can add a document listener or a document filter to be notified hen the text changes, and in the filter case you can modify the text field accordingly. Information on text components can be found in Text 'omponent &eatures. (efore customi2ing a JTextField, ho ever, ma*e sure that one of the other components based on text fields ill not do the 3ob for you. 5ften text fields are paired ith labels that describe the text fields. See Examples That %se Text &ields for pointers on creating these pairs.

Another Example: TextFieldDemo


The TextField!emo example introduces a text field and a text area. 1ou can find the entire code for this program in TextField!emo.java.

!s you type characters in the text field the program searches for the typed text in the text area. If the entry is found it gets highlighted. If the program fails to find the entry then the text field)s bac*ground becomes pin*. ! status bar belo the text area displays a message hether text is found or not. The Escape *ey is used to start a ne search or to finish the current one. $ere is a picture of the TextField!emo application.

'lic* the +aunch button ro run Text&ield,emo using -ava. Web Start (do nload -,/ 0 or later). !lternatively, to compile and run the example yourself, consult the example index.

To highlight text, this example uses a highlighter and a painter. The code belo creates and sets up the highlighter and the painter for the text area.
final"1ighlighter"hilit( final"1ighlighter.1ighlightPainter"painter( ... hilit"#"new"!efault1ighlighter$'( painter"#"new" !efault1ighlighter.!efault1ighlightPainter$12*2T3C4*45'( text)rea.set1ighlighter$hilit'(

This code adds a document listener to the text field)s document.


entr6.get!ocument$'.add!ocument*istener$this'(

,ocument listener)s insert7pdate and remove7pdate methods call the search method, hich not only performs a search in the text area but also handles highlighting. The follo ing code highlights the found text, sets the caret to the end of

the found match, sets the default bac*ground for the text field, and displays a message in the status bar.
hilit.add1ighlight$index8"end8"painter'( text)rea.setCaretPosition$end'( entr6.setBac9ground$entr6Bg'( message$+:+"/"s"/"+:"found."Press"- C"to"end"search+'(

The status bar is a J*abel ob3ect. The code belo sho s ho the message method is implemented.
private"J*abel"status( ... void"message$ tring"msg'". """"status.setText$msg'( 0

If there is no match in the text area, the follo ing code changes the text field)s bac*ground to pin* and displays a proper information message.
entr6.setBac9ground$-55453C4*45'( message$+:+"/"s"/"+:"not"found."Press"- C"to"start"a"new"search+'(

The Cancel)ction class is responsible for handling the Escape *ey as follo s.
"""class"Cancel)ction"extends")bstract)ction". """""""public"void"actionPerformed$)ction-vent"ev'". """""""""""""""hilit.remove)ll1ighlights$'( """""""""""""""entr6.setText$++'( """""""""""""""entr6.setBac9ground$entr6Bg'( """""""""""0 """0

The Text Field API


The follo ing tables list the commonly used JTextField constructors and methods. 5ther methods you are li*ely to call are defined in the JTextComponent class. 6efer to The Text 'omponent !"I. 1ou might also invo*e methods on a text field inherited from the text field)s other ancestors, such as setPreferred i;e, setForeground, setBac9ground, setFont, and so on. See The -'omponent 'lass for tables of commonly used inherited methods. The !"I for using text fields falls into these categories#

Setting or 5btaining the &ield)s 'ontents &ine Tuning the &ield)s !ppearance Implementing the &ield)s &unctionality

Setting or Obtaining the Field's Contents Method or Constr !tor P rpose

-Text&ield() 'reates a text field. When present, the int argument specifies -Text&ield(String) the desired idth in columns. The tring argument contains -Text&ield(String, int) the field)s initial text. -Text&ield(int) void setText(String) String getText() (defined in JTextComponent) Method Sets or obtains the text displayed by the text field. Fine T ning the Field's Appearan!e P rpose void setEditable(boolean) Sets or indicates hether the user can edit the text in boolean isEditable() the text field. (defined in JTextComponent) void set'olumns(int)7 int get'olumns() Sets or obtains the number of columns displayed by the text field. This is really 3ust a hint for computing the field)s preferred idth.

Sets or obtains ho the text is aligned hori2ontally void ithin its area. 1ou can use JTextField.*-)!2<=, set$ori2ontal!lignment(int)7 JTextField.C-<T-5, and JTextField.T5)2*2<= for int get$ori2ontal!lignment() arguments. Implementing the Field's F n!tionalit" Method P rpose void add!ction+istener(!ction+istener) !dds or removes an action listener. void remove!ction+istener(!ction+istener) void select!ll() (defined in JTextComponent) Selects all characters in the text field.

Examples That #se Text Fields


This table sho s a fe of the examples that use text fields and points to here those examples are described. &or examples of code that are similar among all varieties of text fields such as dealing ith layout, loo* at the example lists for related components such as formatted text fields and spinners. Example Text,emo Text&ield,emo $here Des!ribed This section This section Notes !n application that uses a basic text field ith an action listener. !n application that uses a text field and a text area. ! search is made in the text area to find an

entry from the text field. ,ialog,emo $o to 8a*e Custom!ialog.java includes a text field hose ,ialogs value is chec*ed. 1ou can bring up the dialog by clic*ing the 8ore ,ialogs tab, selecting the Input9 validating dialog option, and then clic*ing the Sho it: button. TextSampler,emo %sing Text +ays out label9text field pairs using a 'omponents =ridBag*a6out and a convenience method#
add*abelText5ows$J*abel>?"labels8 """""""""""""""""JTextField>?" textFields8 """""""""""""""""=ridBag*a6out"gridbag8 """""""""""""""""Container"container'

TextInput,emo

$o to %se &ormatted Text &ields

+ays out label9text field pairs using a pring*a6out and a pring7tilities convenience method#

ma9eCompact=rid$Container"parent8 """"""""""""""""int"rows8"int"cols8 """"""""""""""""int"initialX8"int" initialY8 """"""""""""""""int"xPad8"int"yPad'

Você também pode gostar