Sie sind auf Seite 1von 8

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

html

How to Use Text Area


Kelas JTextArea class menyediakan komponen yang menampilkan multibaris teks dan bila perlu user juga dapat diijinkan mengedit teks. Contoh, lihat lagi contoh project TextDemo,yang bisa menambahkan teks dari text ield ke text area.

Kode pada method actionPerformed pada Text!ield t "


private void tfActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handlin code here! "trin te#t $ tf. etTe#t()% ta.append(te#t & newline)% tf.'electAll()% //(a)e 'ure the new te#t i' vi'i*le+ even if there //wa' a 'election in the te#t area. ta.'et,aretPo'ition(ta. etDocument(). et-en th())% .

Kode untuk menciptakan dan inisialisasi text area adalah"


// ver'i 0et1ean'! tf $ new java#.'win .2Te#t3ield()% j"crollPane4 $ new java#.'win .2"crollPane()% ta $ new java#.'win .2Te#tArea()% ta.'et,olumn'(56)% ta.'etEdita*le(fal'e)% ta.'et7ow'(8)% j"crollPane4.'et9iewport9iew(ta)% //

Tanpa penciptaan scroll pane, text area tidak secara otomatis bisa scroll. Text area secara de ault adalah editable. Kode set#ditable$ alse% menjadikan tidak dapat diedit. Kode berikut menambah teks ke text area. &ebagai catatan sistem teks menggunakan karakter '(n' secara internal untuk me)akili ne)lines*
private final 'tatic "trin newline $ :;n:% ... te#tArea.append(te#t & newline)%

Anda dapat menjadikan text area untuk scroll ke ba)ah dengan memindahkan caret ke akhir text area setelah pemanggilan append.
te#tArea.'et,aretPo'ition(te#tArea. etDocument(). et-en th())%

Another Example: TextAreaDemo


The Te#tAreaDemo example introduces an editable text area with a special feature a word completion function. As the user types in words, the program suggests hints to complete the word whenever the program s vocabulary contains a word that starts with what has been typed. !ere is a picture of the Te#tAreaDemo application.

"ode :
Te#tAreaDemo.java

pac)a e component'% // / Te#tAreaDemo.java re<uire' no other file'. // import java#.'win ./% import java.util./% import java#.'win .event.DocumentEvent%

import import import import

java#.'win .event.Document-i'tener% java.awt.event.ActionEvent% java#.'win .te#t.1ad-ocationE#ception% java#.'win .=roup-ayout./%

pu*lic cla'' Te#tAreaDemo e#tend' 23rame implement' Document-i'tener { private 2-a*el j-a*el4% private 2"crollPane j"crollPane4% private 2Te#tArea te#tArea% private private private private 'tatic final "trin ,O((>T?A,T>O0 $ :commit:% 'tatic enum (ode { >0"E7T+ ,O(P-ET>O0 .% final -i't@"trin A word'% (ode mode $ (ode.>0"E7T%

pu*lic Te#tAreaDemo() { 'uper(:Te#tAreaDemo:)% init,omponent'()% te#tArea. etDocument().addDocument-i'tener(thi')% >nput(ap im $ te#tArea. et>nput(ap()% Action(ap am $ te#tArea. etAction(ap()% im.put(Bey"tro)e. etBey"tro)e(:E0TE7:)+ ,O((>T?A,T>O0)% am.put(,O((>T?A,T>O0+ new ,ommitAction())% word' $ new Array-i't@"trin A(8)% word'.add(:'par):)% word'.add(:'pecial:)% word'.add(:'pectacle':)% word'.add(:'pectacular:)% word'.add(:'win :)% . private void init,omponent'() { j-a*el4 $ new 2-a*el(:Try typin C"win C...:)%

C'pectacularC or

te#tArea $ new 2Te#tArea()% 'etDefault,lo'eOperation(Dindow,on'tant'.EE>T?O0?,-O"E)% te#tArea.'et,olumn'(56)% te#tArea.'et-ineDrap(true)% te#tArea.'et7ow'(8)% te#tArea.'etDrap"tyleDord(true)% j"crollPane4 $ new 2"crollPane(te#tArea)% =roup-ayout layout $ new =roup-ayout( et,ontentPane())% et,ontentPane().'et-ayout(layout)% //,reate a parallel roup for the horiFontal a#i'

Parallel=roup h=roup $ layout.createParallel=roup(=roup-ayout.Ali nment.-EAD>0=)% //,reate a 'e<uential and a parallel roup' "e<uential=roup h4 $ layout.create"e<uential=roup()% Parallel=roup h5 $ layout.createParallel=roup(=roup-ayout.Ali nment.T7A>->0=)% //Add a 'croll panel and a la*el to the parallel roup h5 h5.add,omponent(j"crollPane4+ =roup-ayout.Ali nment.-EAD>0=+ =roup-ayout.DE3AG-T?">HE+ 545+ "hort.(AE?9A-GE)% h5.add,omponent(j-a*el4+ =roup-ayout.Ali nment.-EAD>0=+ =roup-ayout.DE3AG-T?">HE+ 545+ "hort.(AE?9A-GE)% //Add a container ap to the 'e<uential h4.add,ontainer=ap()% // Add the roup h5 to the roup h4 h4.add=roup(h5)% h4.add,ontainer=ap()% //Add the roup h4 to h=roup h=roup.add=roup(Ali nment.T7A>->0=+h4)% //,reate the horiFontal roup layout.'etIoriFontal=roup(h=roup)% roup h4

//,reate a parallel roup for the vertical a#i' Parallel=roup v=roup $ layout.createParallel=roup(=roup-ayout.Ali nment.-EAD>0=)% //,reate a 'e<uential roup "e<uential=roup v4 $ layout.create"e<uential=roup()% //Add a container ap to the 'e<uential roup v4 v4.add,ontainer=ap()% //Add a la*el to the 'e<uential roup v4 v4.add,omponent(j-a*el4)% v4.addPreferred=ap(-ayout"tyle.,omponentPlacement.7E-ATED)% //Add 'croll panel to the 'e<uential roup v4 v4.add,omponent(j"crollPane4+ =roup-ayout.DE3AG-T?">HE+ 466+ "hort.(AE?9A-GE)% v4.add,ontainer=ap()% //Add the roup v4 to v=roup v=roup.add=roup(v4)% //,reate the vertical roup layout.'et9ertical=roup(v=roup)% pac)()% . // -i'tener method' pu*lic void chan edGpdate(DocumentEvent ev) { . pu*lic void removeGpdate(DocumentEvent ev) { . pu*lic void in'ertGpdate(DocumentEvent ev) { if (ev. et-en th() J$ 4) { return% . int po' $ ev. etOff'et()% "trin content $ null%

try { content $ te#tArea. etTe#t(6+ po' & 4)% . catch (1ad-ocationE#ception e) { e.print"tac)Trace()% . // 3ind where the word 'tart' int w% for (w $ po'% w A$ 6% wKK) { if (J ,haracter.i'-etter(content.charAt(w))) { *rea)% . . if (po' K w @ 5) { // Too few char' return% . "trin prefi# $ content.'u*'trin (w & 4).to-ower,a'e()% int n $ ,ollection'.*inary"earch(word'+ prefi#)% if (n @ 6 LL Kn @$ word'.'iFe()) { "trin match $ word'. et(Kn K 4)% if (match.'tart'Dith(prefi#)) { // A completion i' found "trin completion $ match.'u*'trin (po' K w)% // De cannot modify Document from within notification+ // 'o we 'u*mit a ta') that doe' the chan e later "win Gtilitie'.invo)e-ater( new ,ompletionTa')(completion+ po' & 4))% . . el'e { // 0othin found mode $ (ode.>0"E7T% . . private cla'' ,ompletionTa') implement' 7unna*le { "trin completion% int po'ition% ,ompletionTa')("trin completion+ int po'ition) { thi'.completion $ completion% thi'.po'ition $ po'ition% . pu*lic void run() { te#tArea.in'ert(completion+ po'ition)% te#tArea.'et,aretPo'ition(po'ition & completion.len th())% te#tArea.move,aretPo'ition(po'ition)% mode $ (ode.,O(P-ET>O0% . . private cla'' ,ommitAction e#tend' A*'tractAction { pu*lic void actionPerformed(ActionEvent ev) { if (mode $$ (ode.,O(P-ET>O0) {

int po' $ te#tArea. et"electionEnd()% te#tArea.in'ert(: :+ po')% te#tArea.'et,aretPo'ition(po' & 4)% mode $ (ode.>0"E7T% . el'e { te#tArea.replace"election(:;n:)% . . .

pu*lic 'tatic void main("trin ar 'MN) { "win Gtilitie'.invo)e-ater(new 7unna*le() { pu*lic void run() { //Turn off metalC' u'e of *old font' G>(ana er.put(:'win .*old(etal:+ 1oolean.3A-"E)% new Te#tAreaDemo().'et9i'i*le(true)% . .)% . .

This example provides a scrolling capacity for the text area with the default scroll bar policy. #y default, the vertical scroll bar only appears when the display area is entirely filled with text and there is no room to append new words. $ou can provide a scroll pane of this type with the following code:
te#tArea.'etDrap"tyleDord(true)% j"crollPane4 $ new 2"crollPane(te#tArea)%

As mentioned above, the text area is editable. $ou can play with the text area by typing and pasting text, or by deleting some parts of text or the entire content. Also try using standard %ey bindings for editing text within the text area. &ow explore how the word completion function is implemented. Type in a word li%e '(wing' or 'special'. As soon as you have typed 'sw' the program shows a possible completion 'ing' highlighted in light)blue. *ress +nter to accept the completion or continue typing. The following code adds a document listener to the text area s document:
te#tArea. etDocument().addDocument-i'tener(thi')%

,hen you started typing a word, the in'ertGpdate method chec%s whether the program s vocabulary contains the typed prefix. -nce a completion for the prefix is found, a call to the invo)e-ater method submits a tas% for changing the document later. .t is important to remember that you cannot modify the document from within the document event notification, otherwise you will get an exception. +xamine the following code below.
"trin prefi# $ content.'u*'trin (w & 4).to-ower,a'e()% int n $ ,ollection'.*inary"earch(word'+ prefi#)% if (n @ 6 LL Kn @$ word'.'iFe()) { "trin match $ word'. et(Kn K 4)%

if (match.'tart'Dith(prefi#)) { // A completion i' found "trin completion $ match.'u*'trin (po' K w)% // De cannot modify Document from within notification+ // 'o we 'u*mit a ta') that doe' the chan e later "win Gtilitie'.invo)e-ater( new ,ompletionTa')(completion+ po' & 4))% . . el'e { // 0othin found mode $ (ode.>0"E7T% .

The code shown in bold illustrates how the selection is created. The caret is first set to the end of the complete word, then moved bac% to a position after the last character typed. The move,aretPo'ition method not only moves the caret to a new position but also selects the text between the two positions. The completion tas% is implemented with the following code:
private cla'' ,ompletionTa') implement' 7unna*le { "trin completion% int po'ition% ,ompletionTa')("trin completion+ int po'ition) { thi'.completion $ completion% thi'.po'ition $ po'ition% . pu*lic void run() { te#tArea.in'ert(completion+ po'ition)% textArea.setCaretPosition(position + completion.length()); textArea.moveCaretPosition(position); mode $ (ode.,O(P-ET>O0% . .

Text Area API


Setting or Obtaining Contents Method or Constr !tor P rpose

/TextArea01 2reates a text area. ,hen present, the "trin argument /TextArea0(tring1 /TextArea0(tring, int, contains the initial text. The int arguments specify the desired int1 width in columns and height in rows, respectively. /TextArea0int, int1 void setText0(tring1 (tring getText01 (defined in JTextComponent) (ets or obtains the text displayed by the text area.

"ine T ning the Text Area#s Appearan!e Method P rpose void set+ditable0boolean1 (ets or indicates whether the user can edit the text in boolean is+ditable01 the text area. (defined in JTextComponent) void set2olumns0int13 int get2olumns01 void set4ows0int13 int get4ows01 int setTab(i5e0int1 int set7ine,rap0boolean1 (ets or obtains the number of columns displayed by the text area. This is really just a hint for computing the area s preferred width. (ets or obtains the number of rows displayed by the text area. This is a hint for computing the area s preferred height. (ets the number of characters a tab is e6uivalent to. (ets whether lines are wrapped if they are too long to fit within the allocated width. #y default this property is false and lines are not wrapped.

(ets whether lines can be wrapped at white space int 0word boundaries1 or at any character. #y default this set,rap(tyle,ord0boolean1 property is false, and lines can be wrapped 0if line wrapping is turned on1 at any character. Implementing the Text Area#s " n!tionalit$ Method void selectAll01 (defined in
JTextComponent)

P rpose (elects all characters in the text area. Adds the specified text to the end of the text area. .nserts the specified text at the specified position. 4eplaces the text between the indicated positions with the specified string. 8tilities for finding a line number or the position of the beginning or end of the specified line.

void append0(tring1 void insert0(tring, int1 void replace4ange0(tring, int, int1 int get7ine2ount01 int get7ine-f-ffset0int1 int get7ine(tart-ffset0int1 int get7ine+nd-ffset0int1

Das könnte Ihnen auch gefallen