Sie sind auf Seite 1von 9

http://docs.oracle.com/javase/tutorial/uiswing/components/list.html A JList presents the user with a group of items, displayed in one or more columns, to choose from.

Lists can have many items, so they are often put in scroll panes. In addition to lists, the following Swing components present multiple selectable items to the user: combo bo es, menus, tables, and groups of chec! bo es or radio buttons. "o display hierarchical data, use a tree. "he following figures shows two applications that use lists. "his section uses these e amples as a basis for the discussions that follow.

ListDialog ListDemo (used by ListDialogRunner) "his rest of this section discusses the following topics: #reating a $odel Initiali%ing a List Selecting Items in a List Adding Items to and &emoving Items from a List 'riting a #ustom #ell &enderer "he List A(I ) amples that *se Lists

Creating a Model

+efaultList$odel , everything is pretty much ta!en care of for you. "he e amples in this page use DefaultListModel.
private DefaultListModel listModel; listModel = new DefaultListModel(); listModel.addElement("Agus Su ag!o"); listModel.addElement("Susi Susanti"); listModel.addElement("Amir "am#a$");

Initializing a List
-ere is the code that creates and sets up its list:
private %ava&.swing.JList list; list = new %ava&.swing.JList(); %S'roll(ane) = new %ava&.swing.JS'roll(ane(); %S'roll(ane).set*iewport*iew(list); list.setModel(listModel); ++ mengisi model (data+isi dari list)

"o create a list whose items can be changed individually, set the list.s model to an instance of a mutable list model class, such as an instance of DefaultListModel. /ou can set a list.s model when you create the list or by calling the setModel method. See Adding Items to and &emoving Items from a List for an e ample. "he call to setSele'tionMode specifies how many items the user can select, and whether they must be contiguous0 the ne t section tells you more about selection modes. "he call to setLa!out,rientation lets the list display its data in multiple columns. "he value JList.",-./,01AL23-A( specifies that the list should display its items from left to right before wrapping to a new row. Another possible value is JList.*E-1.4AL23-A(, which specifies that the data be displayed from top to bottom 1as usual2 before wrapping to a new column. "he following figures show these two wrapping possibilities, together with the default, JList.*E-1.4AL.

",-./,01AL23-A(

*E-1.4AL23-A(

*E-1.4AL

In combination with the call to setLa!out,rientation, invo!ing set*isi le-ow4ount(5)) ma!es the list display the ma imum number of items possible in the available space onscreen. Another common use of set*isi le-ow4ount is to specify to the lists.s scroll pane how many rows the list prefers to display.

Selecting Items in a List


A list uses an instance of ListSele'tionModel to manage its selection. 3y default, a list selection model allows any combination of items to be selected at a time. /ou can specify a different selection mode by calling the setSele'tionMode method on

the list. 4or e ample, both ListDialog and ListDemo set the selection mode to S.06LE2SELE41.,0 1a constant defined by ListSele'tionModel2 so that only one item in the list can be selected. "he following table describes the three list selection modes: Mode
S.06LE2SELE41.,0

Description 5nly one item can be selected at a time. 'hen the user selects an item, any previously selected item is deselected first.

S.06LE2.01E-*AL2SELE41.,0

$ultiple, contiguous items can be selected. 'hen the user begins a new selection range, any previously selected items are deselected first.

M7L1.(LE2.01E-*AL2SELE41.,0

"he default. Any combination of items can be selected. "he user must e plicitly deselect items.

6o matter which selection mode your list uses, the list fires list selection events whenever the selection changes. /ou can process these events by adding a list selection listener to the list with the addListSele'tionListener method. A list selection listener must implement one method: value4$anged. -ere is the value4$anged method for the listener in ListDemo:
pu li' void value4$anged(ListSele'tionEvent e) 8 if (e.get*alue.sAd%usting() == false) 8 if (list.getSele'ted.nde&() == 5)) 8 ++0o sele'tion9 disa le fire utton. fire:utton.setEna led(false); ; else 8 ++Sele'tion9 ena le t$e fire utton. fire:utton.setEna led(true); ; ; ;

$any list selection events can be generated from a single user action such as a mouse clic!. "he get*alue.sAd%usting method returns true if the user is still manipulating the selection. "his particular program is interested only in the final

result of the user.s action, so the value4$anged method does something only if get*alue.sAd%usting returns false. 3ecause the list is in single7selection mode, this code can use getSele'ted.nde& to get the inde of the just7selected item. JList provides other methods for setting or getting the selection when the selection mode allows more than one item to be selected. If you want, you can listen for events on the list.s list selection model rather than on the list itself. ListSelection+emo is an e ample that shows how to listen for list selection events on the list selection model and lets you change the selection mode of a list dynamically.

Adding Items to and Removing Items from a List


"he List+emo e ample that we showed previously features a list whose contents can change. /ou can find the source code for List+emo in ListDemo.%ava. -ere is the List+emo code that creates a mutable list model object, puts the initial items in it, and uses the list model to create a list:
listModel = new DefaultListModel(); listModel.addElement("Jane Doe"); listModel.addElement("Jo$n Smit$"); listModel.addElement("<at$! 6reen"); list = new JList(listModel);

"his particular program uses an instance of DefaultListModel, a class provided by Swing. In spite of the class name, a list does not have a DefaultListModel unless your program e plicitly ma!es it so. If DefaultListModel does not suit your needs, you can write a custom list model, which must adhere to the ListModel interface. "he following code snippet shows the a'tion(erformed method for the action listener registered on the ire button. "he bold line of code removes the selected item in the list. "he remaining lines in the method disable the fire button if the list is now empty, and ma!e another selection if it is not.
pu li' void a'tion(erformed(A'tionEvent e) 8 int inde& = list.getSele'ted.nde&(); listModel.remove(index); int si#e = listModel.getSi#e(); if (si#e == =) 8 ++0o od!>s left9 disa le firing. fire:utton.setEna led(false); ; else 8 ++Sele't an inde&. if (inde& == listModel.getSi#e()) 8 ++removed item in last position inde&55; ;

; ;

list.setSele'ted.nde&(inde&); list.ensure.nde&.s*isi le(inde&);

-ere is the a'tion(erformed method for the action listener shared by the !ire button and the te t field:
pu li' void a'tion(erformed(A'tionEvent e) 8 String name = emplo!ee0ame.get1e&t(); ++7ser did not t!pe in a uni?ue name... if (name.e?uals("") @@ alread!.nList(name)) 8 1oolAit.getDefault1oolAit(). eep(); emplo!ee0ame.re?uestBo'us.n3indow(); emplo!ee0ame.sele'tAll(); return; ; int inde& = list.getSele'ted.nde&(); ++get sele'ted inde& if (inde& == 5)) 8 ++no sele'tion9 so insert at eginning inde& = =; ; else 8 ++add after t$e sele'ted item inde&CC; ; listModel.insertElementAt(employeeName.getText(), index); ++-eset t$e te&t field. emplo!ee0ame.re?uestBo'us.n3indow(); emplo!ee0ame.set1e&t(""); ++Sele't t$e new item and maAe it visi le. list.setSele'ted.nde&(inde&); list.ensure.nde&.s*isi le(inde&); ;

"his code uses the list model.s insertElementAt method to insert the new name after the current selection or, if no selection e ists, at the beginning of the list. If you just wish to add to the end of the list, you can use DefaultListModel.s addElement method instead. 'henever items are added to, removed from, or modified in a list, the list model fires list data events. &efer to -ow to 'rite a List +ata Listener for information about listening for these events. "hat section contains an e ample that is similar to ListDemo, but adds buttons that move items up or down in the list.

"riting a Custom Cell Renderer


A list uses an object called a cell renderer to display each of its items. "he default cell renderer !nows how to display strings and icons and it displays , %e'ts by invo!ing toString. If you want to change the way the default renderer display icons or strings, or if you want behavior different than what is provided by toString, you

can implement a custom cell renderer. "a!e these steps to provide a custom cell renderer for a list:

'rite a class that implements the List4ell-enderer interface. #reate an instance of your class and call the list.s set4ell-enderer using the instance as an argument.

'e do not provide an e ample of a list with a custom cell renderer, but we do have an e ample of a combo bo with a custom renderer , and combo bo es use the same type of renderer as lists. See the e ample described in (roviding a #ustom &enderer.

#$e List A%I


"he following tables list the commonly used JList constructors and methods. 5ther methods you are most li!ely to invo!e on a JList object are those such as set(referredSi#e that its superclasses provide. See "he 8#omponent A(I for tables of commonly used inherited methods. $uch of the operation of a list is managed by other objects. "he items in the list are managed by a list model object, the selection is managed by a list selection model object, and most programs put a list in a scroll pane to handle scrolling. 4or the most part, you do not need to worry about the models because JList creates them as necessary and you interact with them implicitly with JList.s convenience methods. "hat said, the A(I for using lists falls into these categories:

Initiali%ing List +ata +isplaying the List $anaging the List.s Selection $anaging List +ata Initiali%ing List +ata Met$od or Constructor %urpose #reate a list with the initial list items specified. "he second and third constructors implicitly create an immutable ListModel0 you should not subse<uently modify the passed7 in array or *e'tor.

8List1List$odel2 8List15bject9:2 8List1;ector2 8List12

void set$odel1List$odel2 Set or get the model that contains the contents of the list. List$odel get$odel12 void setList+ata15bject9:2 void Set the items in the list. "hese methods implicitly create an immutable ListModel.

setList+ata1;ector2 +isplaying the List Met$od %urpose Set or get the visi le-ow4ount property. 4or a *E-1.4AL layout orientation, this sets or gets the preferred number of rows to display without re<uiring scrolling. 4or the void set;isible&ow#ount1int2 ",-./,01AL23-A( or *E-1.4AL23-A( layout orientations, int get;isible&ow#ount12 it defines how the cells wrap. See the setLayout5rientation1int2 for more information. "he default value of this property is *E-1.4AL. Set or get the way list cells are laid out. "he possible layout formats are specified by the JList7defined values *E-1.4AL 1a single column of cells0 the default2, void setLayout5rientation1int2 ",-./,01AL23-A( 1=newspaper= style with the content int getLayout5rientation12 flowing hori%ontally then vertically2, and *E-1.4AL23-A( 1=newspaper= style with the content flowing vertically then hori%ontally2. int get4irst;isibleInde 12 >et the inde of the first or last visible item. int getLast;isibleInde 12 void Scroll so that the specified inde is visible within the ensureInde Is;isible1int2 viewport that this list is in. $anaging the List.s Selection Met$od %urpose void &egister to receive notification of addListSelectionListener1ListSelectionListener2 selection changes. void setSelectedInde 1int2 void setSelectedIndices1int9:2 void setSelected;alue15bject, boolean2 void setSelectionInterval1int, int2 int getAnchorSelectionInde 12 int getLeadSelectionInde 12 int getSelectedInde 12 int get$inSelectionInde 12 int get$a SelectionInde 12 int9: getSelectedIndices12 5bject getSelected;alue12 5bject9: getSelected;alues12 void setSelection$ode1int2 int getSelection$ode12 Set the current selection as indicated. *se setSele'tionMode to set what ranges of selections are acceptable. "he boolean argument specifies whether the list should attempt to scroll itself so that the selected item is visible.

>et information about the current selection as indicated.

Set or get the selection mode. Acceptable values are: S.06LE2SELE41.,0,

S.06LE2.01E-*AL2SELE41.,0, or M7L1.(LE2.01E-*AL2SELE41.,0

1the default2, which are defined in ListSele'tionModel. void clearSelection12 boolean isSelection)mpty12 boolean isSelectedInde 1int2 Set or get whether any items are selected. +etermine whether the specified inde is selected. $anaging List +ata Class or Met$od %urpose >iven the starting inde , search through the list for an item that starts with the specified string and return that inde 1or 7? if the string is not found2. "he third argument, which specifies the search direction, can int get6e t$atch1String, int, be either (osition.:ias.Borward or java .swing.te t.(osition.3ias2 (osition.:ias.:a'Award. 4or e ample, if you have a @7item list, get0e&tMat'$("Matisse"9 D9
%ava&.swing.te&t.(osition.:ias.Borward)

searches for the string =$atisse= in the item at inde A, then 1if necessary2 at inde B, inde ?, and so on. Set or get the property that determines whether void set+rag)nabled1boolean2 automatic drag handling is enabled. See +rag and boolean get+rag)nabled12 +rop and +ata "ransfer for more details.

&'amples t$at (se Lists


"his table shows the e amples that use JList and where those e amples are described. &'ample
Split(aneDemo ListDemo ListDialog

"$ere Described -ow to *se Split (anes "his section

)otes #ontains a single7selection, immutable list. +emonstrates how to add and remove items from a list at runtime. Implements a modal dialog with a single7 selection list. +emonstrates listening for list data events on a list model. #ontains a list and a table that share the same selection model. /ou can dynamically choose the selection mode.

"his section, -ow to *se 3o Layout ListDataEventDemo -ow to 'rite a List +ata Listener ListSele'tionDemo -ow to 'rite a List Selection Listener

S$aredModelDemo

*sing $odels $odifies ListSele'tionDemo so that the list and table share the same data model. 4ustom4om o:o&Demo (roviding a Shows how to provide a custom renderer for a #ustom combo bo . 3ecause lists and combo bo es use &enderer the same type of renderer, you can use what you learn there an apply it to lists. In fact, a list and a combo bo can share a renderer.

Das könnte Ihnen auch gefallen