Tải bản đầy đủ - 0 (trang)
Hack 22. Add Column Selection to JTables

Hack 22. Add Column Selection to JTables

Tải bản đầy đủ - 0trang

























































});



finalJTableHeaderheader=getTableHea

header.addMouseListener(newMouseAdapt

publicvoidmouseReleased(MouseEvente



if(!e.isShiftDown())



clearSelection();



intpick=header.columnAtPoint



addColumnSelectionInterval(pic

}

















}



}



Theconstructorisdeliberatelysimple,takingonlyatwodimensionalarrayofcontentsandaone-dimensionalarrayof

headers.Ofcourse,JTablehasmanymoreconstructor

signaturesthanthis,butthisistheonethatwillbeeasiestto

exposetoatestclass(doIhavetomentionthatbuildingout

theotherconstructorsislefttothereaderasanexercise?).

Thenextstepischangingthedefaultsformulti-cellselection.

Thedefaultistoallowrowselectionexactlywhatyoudon't

want.So,enablecolumnselectionanddisablerowselection.

Next,youwanttocatchclicksontheheaderssoyoucanselect

columnsinresponsetothem.Unfortunately,theJTableHeader

componentdoesn'thaveanaddActionListener()method,sothe

bestyoucandoisaddaMouseListenerinstead.Ofitsvarious

methods,youonlyneedtooverridemouseReleased(),whichsignals

theendofaclick-and-release.

Toimplementthecolumnselection,checktheeventtoseeif

theShiftkeyisdown.Ifitis,thentheuserwantstodoa

multipleselection,meaningthatheintendstoaddtheclicked

columntoanythatarealreadyselected.Ifnot,thenyoucan

clearoutanyexistingselection.Next,youneedtofigureout



justwhichcolumnwasclicked.Youcandothisbyaskingthe

eventforthePointatwhichtheclickoccurred.Thiswillbein

thecoordinatespaceoftheJTableHeader,makingitsuitedfor

callingJTableHeader.columnAtPoint().Thatreturnsanindex,which

youcanselectbycallingJTable.addColumnSelectionInterval(),

specifyingaone-columnrangethatbeginsandendsatthe

selectedcolumn.

Torunthiscode,I'veputtogetheraclassthatsendssome

trivialtabledatatoaColumnSelectableJTableandshowsthewhole

thinginaJFrame.ThistestisshowninExample3-4



Example3-4.Testingthecolumn-selectable

JTable

















publicclassTestColumnSelectableJTableextendsObject



privatestaticfinalObject[][]items={





{"Monday","Cheeseburgers","FrenchFri





{"Tuesday","Catfish","Rice","Starfru





{"Wednesday","Tortellini","GarlicBre





{"Thursday","Chicken","Potatoes","St





{"Friday","Pizza",null,"FruitCockta























};

privatestaticfinalObject[]headers={



"Day","Maincourse","Sidedish","Fru

};



















publicstaticvoidmain(String[]args){



JFramef=newJFrame("Selectablecolu



ColumnSelectableJTabletable=















newColumnSelectableJTable(items,headers);



JScrollPanescroller=











newJScrollPane(table,































ScrollPaneConstants.VERTICAL_S





ScrollPaneConstants.HORIZONTAL

f.getContentPane().add(scroller);

f.pack();

f.setVisible(true);

















}



}



Whenrun,thistable'scolumnsareselectableeitherbyclicking

onacellinthecolumnoronaheaderofanyofthecolumns,as

seeninFigure3-4.



Figure3-4.SelectingJTablecolumnsbyclicking

onheaders



Hack23.LetYourJTablesDotheSorting



Whydoesn'tSwingalreadyofferthis?Ohwell,here's

howtodoityourself.

It'shardtoimagineyou'lldomuchseriousworkwithJTables

withoutneedingtosortthecontentsbyoneofthecolumns,or

supportchangingbetweencolumnstouseasthesortcriteria.

Infact,givenhowgeneroustheSwingAPIusuallyis,it'skindof

surprisingthatitdoesn'talreadyofferit.Ohwell,it'snotthat

hardtodoforyourself.

Thereareacoupleofapproachesyoucouldtaketosolvethis

problem.YoucouldcreateasubclassofTableModel,onethat

keepsaninternalComparatortodothesortingandresortsevery

timeanadd()orremove()typemethodiscalled.Thedrawbackto

thisapproachischoosingwhichofthemodelclassesto

subclass.Ifyougotoohighupthehierarchybyimplementing

TableModelorsubclassingDefaultTableModel,youwouldmisssome

typicalSwingfunctionalitythatdevelopersexpect,likethe

abilitytoaddandremoverowsprovidedby

DefaultMutableTableModel.Ontheotherhand,ifyousubclass

DefaultMutableTableModel,otherdeveloperswillbeunhappy

becausesubclassingyourclassrequiresthemtopickuppublic

add()anddelete()typemethodsthatexposetheirdatainways

theydon'twant.

So,consideranalternative:twotablemodels,onethatthe

JTableseesandanotherthatthedevelopersees.Specifically,the

developerwillpassherTableModeltotheconstructorofthe

sortingmodel,whichwillwireupforeventsonthemodel.

Then,thedeveloperwillsetthesortingmodelastheJTable's

model.Changesinthebasemodelwillforcethesortingmodel



toresortitscontentsandthenfireoffeventstoJTabletodrive

updatestotheonscreenrepresentation.

Therearemoredetailsintheactualimplementationofcourse,

particularlywhenitcomestodoingthesorting.Example3-5

showsthecodefortheSortableTableModel.



Example3-5.Self-sortingTableModel



















publicclassSortableTableModelimplementsTableModel,



TableModelListener{



EventListenerListlistenerList=newEventListe



TableModeldelegatedModel;



int[]sortedIndicies;



intsortColumn;



Comparatorcomparator;



Comparator[]comparators;































publicSortableTableModel(TableModeltm){



delegatedModel=tm;



delegatedModel.addTableModelListener(t



comparators=newComparator[tm.getCol



sortedIndicies=newint[0];



setSortColumn(0);



























}

//listenerstuff

publicvoidaddTableModelListener(TableModelLi



listenerList.add(TableModelListener.cl

}



















publicvoidremoveTableModelListener(TableMode



listenerList.remove(TableModelListener

}











publicvoidfireTableModelEvent(TableModelEven



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hack 22. Add Column Selection to JTables

Tải bản đầy đủ ngay(0 tr)

×