swingx-1.0-src/0000755000175000017500000000000011210513513012212 5ustar tonytonyswingx-1.0-src/docs/0000755000175000017500000000000011210401732013141 5ustar tonytonyswingx-1.0-src/docs/images/0000755000175000017500000000000011210401734014410 5ustar tonytonyswingx-1.0-src/docs/images/footer.png0000644000175000017500000003106111210401722016412 0ustar tonytonyPNG  IHDR4^ pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_F'NIDATxy|UU՝N!u8^`Q0ettqwT`t#^YqA8(qF eQ!@0'޻?j`'sN9z\xt&I q PDD ,+_AAA[3-Ȳ p2xdXxX-<y`HTEatuu!CEi  ; Άn :\/NF8vjjjp1aj  ;nQTT{a[DQ{MÚK@AA1$a'u~jE^^Zh p8Z  #20C^^V

1ΝK0\<^+><o?mh[;:O{gS|񽇿<.+^}{X>W D=o{Z s.Eiô@yY{oOG ۄ2'f/>nմxP Oqunj(-r`u'e'JPٗ!h*ޢU<oijxN+<%~<6OE}QS_͕K$4$R4 z|yXCxUTJ<6ՋW ļGQ^ܼ HECcYŠX85jf>fx Ko@C[ eN|yq]V<M_NeԆHZQ_iץ˜X PZМI1u縱|o`S cKf cJYDO؝5A9Pnonoc6 s1Ю{ 1 ԷưPP iX2kVV7ˊXqCnN5A,yޗv ̉gmƤNC"%`X;k7хSAHu 7х5AdL>'7뮴(SKCVP}~> UX8?faDV?̛2=oe>|֥]+A@inl+n(о9PX8?0YXSW8 8c~Kt ]<oڭm==[(׏Qm[Y%bT]Vd;<+<3d;.\Vb̻ͨ|;k|ˊI3.Ly19u|6oUO|YTPa:_%ٖϺ&+C}k ϼیSÓg5=o Eڸ{%HbbرH&Z;5H 1ա5uKG`,lOo8olaS| W+:qNWO9n~ 7=ъ7tŔ2 mFak+ޮ&Z)/}Ђ7Ž?QvWoj{q(%չ$fż.}9ny0c끯%]كG.u6lǡ2 e9q(!JtbӞΔ_Ր%wWkl~ s{d{v侹̽Ѕ{_7I;|l3+MVˢި?T۵ZxXyPlvvᎿ$~+*RZ,G/ڭ-~ևFԧtvY?CU`ΠC&[[ tglZ&{֧B(3oӉS{z_w lxd1T"Y{4fUmN/lj9vki_8y].B0 GH摮n o9rN Q IIpb<F֫b7 Ib(6HG#$a_] l6hG:c@L_ޏ?^Q6̛J)۰M2Ɖ3[˘˰iBQ cpդs6TK?ە+70'6c!5?)clGG @2Ɖ/vwwwb^?&$1L>lj7LHê4⯛[ )I EؼSP62Y6v6GJ Q8i~~Su0Q6mU`POVԷ0(`Cjnǩܼ1'f5񎀘bN`y#֌-t5wK[PQٮ՝@HgZmrG H!ק9}ua|"ݝp: εP+o۪͟Fz2Ӯ#hKS tld&)m6 ,]w7_@$B&վ}al?K7z= F; &AEQ8ОmGR46x(iqKr ہ8粒TlkgqMKq3yz=yj**PQ٪tptm<Qu0[ch@,6ݣ}HUO~#^ /niiQQن`̐zlG}k4%P\p:TTq@yɋM{:pCvY0e70|-̚¢iP 7Y~|gǸ,\=)Pl;gRː@)[~7}Sn݆)] :s?|(I:y8}9I"hR$IBL\tn՞RƻpcѴھ绯._K㊳8QHxs}jmɔoT$gqmZ<`.Gg0=R˰qw;fxlxlk_|]Xmw}۶?6n_ qѹ9Z[F'ظ . /_:3p;l\>c<֓gվKRȏzXn}i|Zh %1ԃFuھ۔1N7Σ3(⋣xlʄ̴> vwnQ{kT??n5Sk6t\uꂸ9S4d;.d[ާ(qc c]5+Yq Igϒꋣ-~\-cN8 )fv2y0~Շ_X~1:͟_wz!]N}G-7_#3L/ w"V ^+fʢśs9$;g;Ӑ5o'du%,[S']eU8r7]Y[> osK(@A~f Fïzƶf/w蚍ǵ]9^4ek3þ n-w/ljRqEc;__ C1Dkh,0;tQ0ƶf[#,[s$%7 Lrl{v!{~oZ2}X]{Ų5r_JI~\*OReR)=-~ʘlM-j~:5#Xv'joEEYUŭnԲ `ٚ!/qc^?:NRUSӗۦIX8n8*W~oAþ@J)їM{_]]*KD%""a]8ad˕bVXC:,lc~Ńp1fjǚWkwGgPCQeA|2 g*L !hƤ1.w.FO) z߰f p8_%  3B16M-?I)G}q2d3xdXyX91XeDQY "p] !a\fb|/V 8r8'  1C1BSQ u»w=슎Y[s\,hۚ pDUX$p غ ]vWJ.ήL!8r+/AAę%yP;b(Pܻp_l]N ’!ZZH8Օ1YEY\b@9X-V({%rx+_G{XXa<8y  3TIxbF̹z)>Uv6wzdU ƘCYCo z7ח,G:gJ~@b "ñ#0ܙ)?*s.P,Eː8'  $M.ţ#q Mޒÿ_ \ v*o?6c(&8ss׵U"҃BA .:ߴQIc/&) s8 m!  j\[G ; 4"C-'ڭpx8lV V^Q*:Q(hEЭ"Jʚ1 -p\+ňs-X,.׶W=CpApBflǝ<AA7B30I#cAvVfJ?W?=V6ڽĮ,L,q%Y+a-I/~ s$qQB,./?8 +[DD(?] wp$__ @pf  G:AAqE8&q01 ) B!E:1bp&necau 5Ñ!!& LyQ9\ֺi*Γ汸X!R}I4}oج%aPFTbeQ%Dy+i^4 e[Üi?6ƛEX!G%D-qCťW`(ą  8"8&7} + ,m(W)ZeQ+{{-̓Ź(Ry4& HL1Q~YT.gAaYB8]0V[&8AAqډEho͇h< k p V 'i_Yar1?(1WO 1XTP6U`w,۽Uh9$Ƭ'ę :ro1#AZ58í,,՗83,<22dr''qL^gx@8XbkG<.!0Q ,2hUY5%gtGo0 L΂Y-, r )(07 sH9/"p9d(E4AsO4 qFtcL|M=@Fa \"ϕc{S~RK' gNp4ns)#|b(q=>Us,/<,"4([fAA7IbD/lAR<'{]h ߭u+j4IB&YNzqqB[@qQPVrх+rԗ?M8TĩmhT7׷zQ |"]!W@W0O@" .1 1N㒤6[" ;Z04,{xiG}UE6ayZӵ8 B\'Uex$r]d x&J)rN"2 KU~>E|=|=b)>A68YM: AWC\ph,_C$ tu<8%TK"pi^( ? o(  (t !}1' i}ي-KAn潿 v g`'{ҵ4yC Ih^0qmiH_eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_F:IDATxbhXLbc?߿L?cf 4Y"IENDB`swingx-1.0-src/docs/images/background.png0000644000175000017500000000565111210401722017241 0ustar tonytonyPNG  IHDRe) pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FIDATxڔAnD1C~5Rw=o<=BO ll'~ +aZukfFVn+XQ{5ұީz7Jum_?ap4Xݳg 9 bvcys X%9eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_F]IDATxi$Wu&{c=+k.0$!!U,6x `0c1 30`6mlUlBZV]{F~̬̈'+խw}{s O%ڽvkw۽vkwuqEᔠ޽R_'>K~,::+Oǻo}cg2Y3KX47t@Z<'(,y?/Ind1Dȓָq TҬHrt?˘y)Gk}fe{H"'zرs%I쒰ٲR#=2L>"|LF׮L~r~QdeͭQ!K)QgpۑL9q1b_$Մwa+K1Y/Yaz.%"LF=4 7X *5 Kj*g1`T9'4K^I@,@f#́Fa^ *,Hē߳;Pg H}s-xpȁ݁%Ԁ a-SWG)O6b.›HxhĒ  QFLr`K,i9W1w,Cу΢H kG&LCHHlz'*%@I|%Cb3oC8G 6<}i:9Ȉ;d̜gJȄ> wbzC=hYtM辔:I 2VšaX.ÖbL6)d;2 ta&5 =@iQNjv{/#28X>YErh>c)cLffq3RZYu͢HIpq olL ,fсo}^+L@"'In%e14ux]ck`IH2b2:k%A,a1k; d1F7CN_5dha!#AFMs!& R>Gdz,u. BB c$ő<<2Y%)$'y"H@0"#Y7 @QT02] &c}:tKDεB3{ٻ0ˁu4s`h}^&y #Xs7xYUfQghxX(dK=8` ='K$Og9@D6$iI c$,D BSxoq)51!;$CG1.x4ųac(A k2Lz(?tF d]|H"/luF<@!JMK1eh0¥BîۑŻXxS MB 't ,l (4>Xs& T-CAcаw2{TC຀d q?E9( :,nԛ?G0>Ι#daIggxiݔF3dIqGU2mMK8Lb [nrPDL10:͑v% $ \R#@},c4[Clv IdMQF/6LF]IKntA ӁQЁaBC6 '!{F8P50wi{QH[Z&衡Z8#a4Ԑ6aQ֑xIaT((tZt4MgHq{-/-XF]:/Кf:&,E{om:\ꌁ8P!A#sYϪ7-.x2)N c=0G6Yԫ#yXXAa4߳THaiGx ʶ47]j8}a>#eLDFk,L1hBb"GG p 6!THtpx#j0&5czR JRg 1X=j02:}LBD"fN8=n½d5dHq=4sQF]7˄{+IʭLdP($Ag[ܾ#H&г]u4 AM`d:0^N6~Di?wr?ZF0*t"(z~&#HAYc$)c!sSw!xNzlt`1:RGk[dž'8HX:8pM=;*m"_ ZK$YE%h2GxH~!5qdU56Ⰻ[I x3df*GlI)bŀ@dR^ E*x} a P==Y:W`a1bH=潌 fF˘MWIK 52e!&/="t#C2 y'*bXZw:5 8dDc>ϒ 垎`%dQ2ܺ4oLp&vՠ%11,ipEXAOǤ0 #)igtdL*8IU^+)c&FR !%{3qIpVk\OݿGi8nE_WŃøTyڱb} I*b&PqCZcɘx Lhd1Eb@];s'ɫF8#w1"9rƭsl,fhcH8/2b_"Jt#ctX|19Pka(f,|_9g,K):X50V2~N[gpsʼFI?eE?v3D@ 1G%ˍ/5gr6ў,Ye13TxIe[")#IGLǍdKؠAki-rڍ79`уM!tRı1  F`bk21F(.W`-I? Yو?%"-Ij-d#EG4'S\VR&_ED= Q}AyNd#V+b۸$X3Fml>p1Côq$+bXQD8n1S I}ZZKCE^ ! ˆV؃Χ 9b 恋k'/ʤuF#Gw&io%-̑oFOX-=ʻG36"lĤ#{6ߒ6UG)}y~7f&=/egeF;at3hڒ0&}سg*@q ItAk's>bgLIcGՄ2t$K@ IΚ-$ YPty2~2#ɸg Y~Wd S}Kp!)9R҉i*!ƑP%h\jo'ib-%f&'O,|,'qSe&EzW6NBJ2LSz,m9Ĕf'/qUzO +]>쑢AF7I(D:'gѱq)N c&eNx`p!h'/ɭIA87Fޱ9EeYHڰIR^bƜ'I`7* HKefHb tlbX>7Q4Ln2i#hB`]oۨ~WLRo Q,& N8YxԵ7֐`NʭΤfzb672Rj'@dTT"zp#442\hu +.PL7Ù&q$_`> PPfD>+N$U K\JY 38H9g-ݍ,n]SwФ۟4_$J>^ڼVHax-#Ϣ'i 5Z!C\Cd†SƝC}X"&w1}>@L`#>Pl IX*_C\A<؛g288T-8_MT52jxCHͼ}odԤasǜ,X3|E+b< Tx,·?3e 얦(:d)1i YM ,\ Ta!0(c@PU gѬLhpc 8CU/DGh-sЧ_b:'TITZAG!Ҁ@,%yb؄q  !s<;eQ%Ia %Ȥtz$h1 z aq\jOqqR9gݡ=D5„n_F3 ϺL:P }&1"#9[Vd v-=˒y vP1-NbFܫq^ټ㪠&%Q\7F^9MH#>maHO꙾O<2҈Jߠ#  ȳgMKXRƳa~ӕI8i~&m A¢3CW%EyH[ƍE WR_ǓukaT(!ariqY[>ёB{_Q98R$Pcj!G$ MV սN&ji$  q$KN.2]cXg@ɬH7^=kxH7qcԘ@9o3= x`dջ ^j$i\#=)Kl\.d` `nj8?P YW~3`LsDa{^{^o}'m[~<=\].@͘yf\MjgfӰ=] c}_Yg?~'{^{^ ZU(G 9 Pl;=\fd5?+=,y0RqOWwš{^{^{^꟠sˠwf]F좑56}<Ƈ@pg{ǡ+o+%<vV v}A;{^{^i8B0 X۶aY c Wiƣ08`vYtm҇2"=uL`XK~t| {3]-}V Fj[[[&j&6|߇rw^{^{^bA˲8,  uL 6mb{ApNlo j-IsɰդϡPkƌ1 pZy .G- 2=/>9 R4c3r)6yz- ωð^HRpبƌ3jl,QkI򘕳͎$Y)U\:yApdldX[ :2l9[T*a||(d20 =7o6>fh[ E%Q TQ^{'\jd/ t:VX^^Ɖ'V 152jm{@Ǘ݃\b0w1:ڧٜE X)@9%󮻌z6 /E{1 'I}? @BΎOti H`t2@妡ECx`e24Z1\z6fðޖyͺѡAahyts<ާY[B*(jr'16yl^$qN24f1cPkMI^c9e$Pu9IKY ‚!8F96Vb: K9Qp,nui Jcy'j@Zg TI`l(Pk1(p=A%!%Z 2{Fe0Q>LpN㘚8rLӌaFЀ%9y?H4~;l+^t C'YjX\\<Wԩj̡]X-O@m~ fvqO&G P)rڳ\gr,)j{;iHtYN X`9S!~@35n=tƞvLҚ)XcznTX) jDjdПw9MȠZ(2Q,f8:$H:̻ tL(CƦHd( ˛4o O3j- - dQB:,T[yL8Z:观rV-Z :0]k>yN8@e0L9Cp`,"RܘVCǬz䓒0ئ:7 u^o=qsSarrl6"q?rhs!| w;a)0_N. _(^!Pjy?qYԚDS|+ sB*mħh %gt&>- ʹҏ5Kjfl> g,@Ak) 8.觲ƶ@?ěk!ͱѠ.VՖ$A9X`mOH1du: l۲ʜ، 8r,m4o0eӁV@ڋk5:* TyLIy?)OeL }eC'0z'NøÝQkscԠ\)@<g1hu PW>?=[SeAkч3 @ч[Yi?cԀ V>9G~j?E`VcL`dtTi SަPR/e9kt_ql6c1+i]&DGJ*ƌ3`vO=cuҔ/--ciGjƹ˒ǽNW ޛtzAFԀ; l{tޱTP+w<z9bTƖdot5"~jAUR3-OǬQYB2t޶R~%KJ^`e' JME=KdAޖu0W,0r K9Hg[ [Hcl%Yؠ.觎ٞN@0j3JGޙd40 LMMq0y2rO-4n<6PpK|epc`gW[EL}PtEܱ0G*|Ԛ]-.6ݽ(tY,>fAyOeKYSˑsgmrr.a"/0!퍦`) _H{#g /mAފZj3ٕYz~`ۋmJi1ɗ)4LI[y013~ FvL|uum_G,SʧKϸTQ`di2<˻PmJJKs" d Ef 2yz)6Uj@:Kt3Ag-`} :3zjY[T9@eۢ΁RcF@?j@ZO|,CZ~.)7]_nS}ҟk3.p3-,,A1S H ^ ܰOSuj^"@3)<XδAi<ޛ^tA=hI.#"@ OSgGwyGI?Ej6gmEzzEdp,2z FkU:?SWY?h鹥r>*g9IŌJ H ;EF1k|b^hu&80]R*Sm,PmtIա3 :)+qx#C*5mn=>}c7av_27a"aJ+8Ә% 9\y/5OngZGʨ]kd4{N?O 1 He᧟4񍻽'-/m&wlO>:`kVu{)LC'EgڠдAAv<:s6(6{.Jz<pRM6d6ҏQmdПs8j- 2*cPp9T$*IU ⳎJ He32V螁,oz9w97=2/e9Vk>ޛj)Z$V RA|)!w#Y0]!&C+u gJAskU:SéSE@ܧ]8S%8n9ZT\.˲ 5y/@ rV p l;bP4,d`O˘=Ah*pb?@#;GoyaM?|YPӳo"&Jx^\yJTtV46tZ D)UV͆򧟲g@bF4?^jn$HI]0HYt߫A ҆GNXqly*V~Pl(PkdDAl<N*[EYrĵ?IQS齩n†򧁕*]޳b` 7͎hGJ ;LD=C+  ~eP(^Xk[ T## d< NvU4.F{8jsw~]@eL0^ko}/ncڰ8W1ȶZ5n)HtAH'OJ] ̻Hjtp 5bN>M>Pz{CЋBmzO JI[.Q*L @ ]Kj O+cti)\^j2;٤^?ʟZߛ9*`0M~1 )Tqj&T?)*NN8F# 8]^ʪʟG鞁KxAG/T_I*'։L?SA+[tCm$bmO#Y?FӁit0)_*AXs KY ,}FRn3p~םnL>~(ڔ_'ʧ /=ݑ+gg`Le2O9sW]}Yӥ_?aܶq_ ?=Y9MAേhGEwn1Hў1H0?9 RevI^y2@!zEyB9*?-!Af ߵTIAc<ᵓ@ᮥ=iBMۤҖX4`rFz@{+ ZtYΪ@*Xr@2[t@?=(4c3 *.{ʟy /EOW4Vg )*Eu 퀬W?AJNsj<\\B@?N o`~aϸ &=-T :A9ǣt7.gh  A<ٳ1]S`.%~"G{8_GQp89Uq m*w};{DB|HXa^>r.nxh!@qϓf<-4&ZB(u><)2tiC-vuh4AiH٥񃔕??tAR*ȓZe< [tot=y/ȳə`\G:9GeWT :A&Si6jtVt}HnѥycJc Pr|2U?rς~PA%BR H2s_xUⳎBONӲ\7? l)*ʟDw@`}6ܧ]9dpݜ(f8.xAb[IRt3f&|n@mnEx.nk㜩wo/m0Vn`\R1߆תS_CedLy[npsj[BJ"S33p9fN* <|i++rnɰEO΂BXۢ^PF ?Q6xA~:E'Q`IyNևPAZ^$N>;f`eA ޻ޒX`dK\g 8==XNQ97Z]*AU[C=)K57<6(); \z~Y!Cx&M~\X~̃Z&L؅i0a]_ |vV.`ay@ew;S`Pџ$w/3mѠN"tP6(tEvjc 1Ci>^ ۦԃWsAm;)+*6頿Q"SUХ"ʟZʟUzZ7AʟtGΡKKzA˛"@a,/O W}lh`AE5/RTXN1A|)+T "ϻ Iro`~C.4[6pb#WS1I{MUn@%N3eupdEaA`L} 0ep 0̘;1U FT$<> Y2s 0]@'33>i;̀{o'nnWў_ՓM|sj???sg,|#pYΝ0S6PmxX?|S:sg,<UG&rvoپ_c#G7! gD4w=A'. aP|A1#QRTlT9S`U੩KY%\IUaipL rXW?6' O Tg9VGQATP?ސ^O>|,'` GWhbF 0^nD9'phMW&?+37vqtyS8;Зa}9o,v.IÑA:_|E߽gtVٛvto]Mw97l==&|>/"gODlZBpN#>%`+7vM_Pqc-_:Ab;~eLU2K8ڶ6 |w'c(562jP3.9Lt@C;iw<#B%1s]$v\|kx%2xX,Ykup#M \s{Z.q]GQmy~E_ZV3w|EeuFK+E~އ t8~'>%`LoL@?ϙx#^W]Zp戅$L! ϛu[/տ[S h` ϛq%y<پ3g=> ;i7nɀ4M% ~e.Z %/` ߹Fd n ~Ú,Ι(d xSys (TP'7GJBZƗ;y{c7?o{X/减3_ Pȹ>|Gqv,mS|0y;c⃿5yg{ >󽍓zW]97l?_\5W .~뛵J1MP(c%fjaݢAʟmn%OrgT?m|L-'N[Sp%٬+r Tt_p\)+*GER9RTT6 Ua(пLtU 'HWTn& RSdVR T33*KҏBFkqT=5tU:蟫XX(db9S1ޙ1v ZM 8Rb%A21}'7OsÆῼ ؟b")x ]^M 㖻#n|$RxYPkD?wqn0^|4jß&׃q{x_'يgoUgp94/ß\X`]IG>m|/;q(P.eV}^ 6^$]RlV۸`A9[>ڗTng"@.J Nׇsu> M%堶wLv$ $pV5R  `6TWE86\%堂bFcPuBɕ?E'O@dU]SU #cs2@E蠿X萌kTdyK*L^P??+t釪&ϡbyK4o %)@q߸M ب]B!>[a7iKoRKje/9z9~8 N"0TEmkp׻.9;Kwqu-C ?p"fp?.=a{l0\rNܹ> Οٯ~^}c;(%'koB>Nlno(>7cl%sߋRgc@wW[Fm}I]I={fR&,e:^q6N/p|-=I|7G̔9˧v|߻8.+)*"D/``  @6t#@8lѦK?\+}V' ^ Oϧ36G UH`t@?#KKTONn5:/e6jt?3٠J@Ig9VGǠUbF\ڠK?,36G֦K9Fg+yRM:)XALYI?? \dр9VKE9ǤKE@1qpE[d?S6qtM)? ȡ]Ag)yWl߱ JTINNqh ^{>%llI~/ޟNl0g/=k.p||꺡czAE>C0n -!gL_%|o>-Go/%P9Kў3 H}*8m۔18{T{=])e36G #;gmhr{?P=}T1`/ǵx&GX1 %X̹RF`u#k*9%S3Pm1 4ڒܧc9ڧF)eD;YĚGQʊ4cT{(()eT)x'<ҺanL%XX`l c0S6 E JCsypdCCŌ6iDģ mޘ9L\h3$A ➡,=Z] 5LdwOcqVnRO_s+~;z[wYc9 K{v_~ԹÚ?; f8qv=Νxxuϛ˿`:}y[Ef}v0"7p}z`7Z@x,m~>Idφ x$`)ߍÓ[s'E$6nįq 3.fHO\_\T_~~a TΕ~p?n~3.=?0x>u%_J?zC&Sf+x.9W]' y3d'S \rS3*%̰af'.=WooVaS k-50Ob3E7򵷂i.̂0 ᵛe|3_5y lT VMw> U] x˞ٹqL-/ \YBC`J$Nl8vA|Oȱi+.JiB:w̔A;K\g'=ȓ13*VOWO[ :9[M49W齩cP̪TʟY%BF{T9MQW6UJK!r,%P ,oA%/E\תy̦J* 5dQyp' 3H,4WtIk_p'KK6G)'pd&pL+-Һ4̘kmZOXXREA3]kH%IY=0!n0(ya?fVvEkç<oxw^4۝ Ϸie}^0\Rők;~|ˣ`k߻ɃuPNYHMef0bg3toDѧ#W1:A@wafqFxNi/ -Oڇ ,cDss.2|\[/)ae!^skog\z~/>ƃ -5;͑?\}!|? ^y h0D P?3EP(gPXG3ePh+w-U'MPs]KIEcXJ*BeS÷RجӃ<ӃB҇o<W7t_ T>y T KʟyZ xz*2swUj@*W? ޱT>p*+m A4xAɢ*.جӳLL٘(*\ܗs*5 /fr.'Yc,g[SEGP6犹_\3&-nI|5⃺sC&4,vj`ELvt!4:Ut+8-oǯg?Ƨo- N _š4}@ J-*D9M!#'֟o O&rǫ]AήőwM6D҆ k7+[,!3eU\sLu}8~r>`8F~tA?ď XƶTO:;~ 9cyC/-WK,iaOUk%F~l(te`\s -on][BskZr9.>uZ q. ,{4*p_[^4 7 op¿lwLgd9||k!;BթqTLwԮf`sҏD #Y}^8_X.3N9+du.M0Bm7G~9Ho 0߅wkvoh )|5|k]@Rp*SԒf'i( 8M#]&^f.0#~ѭIQg 4tП' s*IY֦W $]vЫQBxi@cr8j;kԀ7m/g1Q4oQ?sI|ga5><O=7wf <AL)tC,5SBu@$0rݽ=ϸTxEoE JS3Mau:BO)wP"S0sW]:+6GKgQ**w\S~%!?_r~nPTXrl)w>p![[nUP(x^I?(c0QPҏQtVL Ԛ5>w/"@Uj~ozoC0~(yp|F齩,xJ+.u)MC?NQ҆cbai㽧baAV[%VeADр)}9g 0<||3%[a.YY@FGCa &8~Y!koYyys!=iPě~t̀T;FO=a3|;aZ20A~(E^~AwKf\tg&N)( Ns-;Obߗ`#Sj￿b Fl{VahýAiBw٥C'8T]8M5?ܞKi"@[uz~od)JVݣ~ך~ʟaHR,P1#sx%U2gVep6O+cvm=iOM;< L3 ƀ6V:COzWoYQk嗗֟Xh,@tلf<9džPĮ|\1暜˒Cyd0㰚zkdDCYCTį~0`Vݏ;%0c!ngI{qY(`tckp٩ ZS]`hT4`8]. ãBw&JCx͕+߽O2#=9CˇLfyxK̭4 >W̓Wf/Rr .s0ʤrbݍO̎)'}e|U8ZFGᶳc&~ic-بyh||'c61U2pt[b@A+p|;K}3y8>*z b-bߑw9JC͡uF6>~*^q<9޻ \huwm SUTMX8BAMXXkwѕ?{UdHºO/r)b/rͫ䀝\MwN jfv*6dH[kpgϟw*eR~\Rp_mLfn{*rv٧]ʒ&+K 6.$o.)LaB+y33雛%K՟vp `܀5:/߆_|W=IHg M 8r8)#$U)]Zb ̽)y2F]m%ҽ z F`1-hљ{sA>}ۣó@ Ko= NM5kuww옉6Οs`JIӓ!X#3^o@WEaiVCoT>* ` y1b=o9\wFJ,krˁ2˽s`[{{o # <f&ڞ dq۫bl&Wh(eqVXG>ng _ikcΟSv6hTM;fgl`rD|)Ҫ޽w?ѐNf s7}Wᆴ5}b \4#u̯qEE|fEH^~~_#'}hhuQX1gCt?Zs9KI/'yxs'q]8p?PGU,5k%U-,Ý{2po2`XYxI+Uԛ5߾|&o7 +QA *2]g2 ?pZC KSQ2zngI7T\?2GEʟ"UϴAyWɑY:u M/+ರց`,?wnwp @Ja\469'916::{*5oPぶ"2?!+EKK/}ͺ}}+ ~x(h`khϞ~ɮp,8W̪|Vڤ3Yw@2r^SIo-:DZʟyW]wUs5s`h^R)J^e^ѥͻz(PYß>C3e <ǝɟy}$rk߼sUyA$V0x/(`j]H)`Z6T^p2y9pV7hO9>|l4خɸnp]ސ{?Zۂ[0>=s)#zzOi 9饳x+\7DKEt::{_ҥ8|mVwF3|l z=-2d}FM/ï=o֑w.ܛ!}St^ pM/uw#uwp < UXů#} <67= i*vBOg4A=&(6UQOJ^2T']mgSU#Qm1U+6/}7DOyw>J?^Xمso{0`끜0XJ?4af›^2_ruxݢ3q~e~C`Ueεj'bxp`m5|dw;}}h>s gX@M/Uhu1sd|E!Eu fݏegRVaTd^[9]\+OlzNGe wFu^11)%MXzXD|;S5G] OgQ`@|0J߆ @. ,?#>½.^7@v 1%Uį\ӈ݃ 7{4n ?FLY!<- o\ƛ^2ep7k8cn\e77 LIfWTWTM_r\3&AH%MP(O[B zPhg;:^gڠP?gRA|/ȓ -SLjo q;"{o?DbVU"f )d8WT;ׇ'CxѥD':[7TqD\Ǎn[x^ڕZlQ-^_^v^WߴCOI$ S%`~[9QbwN6Ȕ%w=М _shE gBF1:6~d\/`. ZlG;zׁu\~~{-^j!$.;/BF;ꮥ~p+ɲcm` Clyq攃խNr:Gv(#At&O=tҠkcw}* [꧟T ՎPnﳐY_~ }*?gy?O?zϧpI̛͗[ 6 G3/ś_:K ΄EԷqlsK){m\~ɯO_sMb5.;()B9Cg 1౗c-bP($SݟGAiB[G< iBA!Qm}[(d{k{ x3ci<-ܧ@%V_p66CAXꛖYi68TJbF@p`yc8aePȈ@W)%.R7.ꛖ~ Qm;nѭob~W\Q6rO;??|s! ɢ+.ϝHl/UvA ]zoZ\+h옉խnM|*ci{lh"'ڱ( [xKxޓsO[Ϲqh_=z1 yb ry-zfXC׮D`롉[ɰw—\<%\}r>!TrpH8A"412՛>_yѓ,@n:]m.0 fe aqe|oo HCMp+(JwkxBz<ƥ, |Q7|L>+b 3f`gс#w ;ġ==yʟƏ!SA)<V OBmo:("(5y6]ޛ:YGvOY[@BbN e بyZW}z-/õz"6>i߼s yWĮ7p|鲅xl}~e[ z2a{s1VhnPfgߔ\o~k}q?ƕ9Q|^ԗ*\}2yT &_z8vZJ^øv p{Gտ<y?~ |mJHoGqˁDOMIa\}rgȠCc"@>_ދ?e-|e}a{}=߷ Ɵs%-3Me/X?#W{~qC\̘V'>N|9o.߿I-O/{zπxǧ^6>|L.e 3h1 [o5]J}bOV|H6倮b ַg>y.OgM T 7|_1߽m?/㻷= GeCIN8,e,߹QENƻ ~{?|.$2U ||o"WtLUYt'})g WAzgd(]Q G bFD)FDtrsh]Ǫ]fs Wbҷ܁Jw|CCcEAF΍=6>6ig,:+m̯½ 7L"@'~h28]r@xsCLn{ǝsS] n8Qg#!@jn1& 0aA%81 bp#uyx87lzAyoo]`‚]ڇg8V~Kb?)&|dQepajnNeJ\)8ǏUxrÆ#K;~gM?z"0ƁF4Z}܁Vo}84w}.0*2e^qfS{_LJ>s>)pQ}-ht=6ctϙ:;) )??ǯ'`_!_ ߏ/Gj1Ɂ9%SL%X=eK9iCy%Z/3aτpJ\R*ԍwƵ: |8cnph~?:p?:p_]VVqN`)2s *Q [䜁3eە??U >HTAcq>=c.’ʹ?Fip2ivAFIB[5 GƞwBt_5|r YT? Rbmf]η)2)=celX>~@ϖvAM7g2X#% 2\Jf9ՆGZ'A9gIrr|^詘5^ KyFc"@i@O-,S1`vV g+666̘F+ Ϛ,YI6 &WZsTXB@)+pxEESKM(8SǬ3o.|'_ y Xk2\%&`.KY2=U?gf`66W0w pw>p |~'9-dT%80f '崠|crNQg5O\8EssÅYW77t6c`7-Cex-0hB%91.NB VVS U0+}]7mpƣ9nlUᷫ]Fk}YXOMA8E;n`B<}PhХ"F7ȓj0DȔ)+'5(TpӠr`Wl 9JMYG3sЌ]C6ky4M>Tsw mɕ?K9#6hll%򛉢CMsLGOŬR91Q2:pnsY]*Tf;QO-0߽cgr`he/bwԷLrn>`t){ Mp+]g` "3nЊ6ph6<n8=v28Y"6l0sإP^ &,p .=@v{@@BJhMua)Hwݧ 4 zI 2(TyZě됃BTA)ە?=2؂gLz'+doI\򛜣h*: Ļ6mp>\UXhP1c`eV`aN{O-l6RF+ K PQW9gsQ5`Mu+]R[7pt'K[13옍kmR= T6V¾ ύۨ7},-c6:~@ɒ3$yV &2#L-jη)Y4'{= X3n1_x$.7q= N8x{6ȞP;L02cjf:3z1,p0 %0,`)Pg\$>G?ȓGa@@XՍzWPGi@<=OY3HUTAA OJgm+I 27 2vL0ٔ?lVOm#k*n@yMzfuMƌEzOo.c>Zr 5^֗ p9ò=;x-7ԂQ{<-SOcP(cBY`T<=A-mPj&Hd69 Ȭi0&'ZUS+yD1Pm9-:/e 4WTr+` g8YkX*cRZ &7:4JV:bla=XSe V:]r'oypdgYZ*8@cUG i1LI km9be, t<',ks\J;]b0h E mrtfMbj15џju3U$N3LT∣KtepZlP5@#D}ksLlZh֥ep왰qt9Ҙa.~1 xwO{M|?o8c_D5; ) U3bs]QA9뺶>>w<ւBeʟiBKKTPh OҒ~Ph3EPJlӳ :JIQ%jz.lV7k OᎩ@? _ݢe 1C!.ȳ7QƬZmAȱ`Srbրϻ- >c YZ*:*8"ي6wEO gf#{fnOZM,H,/LNևs&r#'9Q)Xx[3lBc-i,w+ksx9xeI3& 3s}84— N37M{bi (O۞ z tW ^ }Fejs=@)#T`699K/(gloW UHϗu 2u触[tm%YK ƵD*ПsU{*/e UiL 5^됳,l=:/-ObGcyR32N1^"?T9Z3im,>пwF*6퀜-gz̆ $DтeЃB&rC6_KYR])O p#7{nKĖ6dO^efVyf~[3lH;R!?E{tAis.SpF xtqU@J2x a -Cy+yB? zl ^PhEׇ$ȳKTc*J2Ϲ53cqdmzmr36ZʟC9gbeMU:,ZبATBI/4QdCjSNeYM̻Dik LL^Nm̯ppbE&\,ocoF#-Gic<3d*PʟL*!tIa@E-n~߂AwaL"PEvAןڽp~Oz{Ji@69:^g dq'īP: `d4S(3dz0 T^ʟM,I϶'hу<? U%-N{"@ DXu:-,mAdf 6֪|3c6|SeUse6f](ٮ$Qd}x!c1pp&% "@3c6.7E&[mƌ3)tƔjG$WGǍpC qA%7 6dٮJ90Y9{W#J= #ePi  e*rNBOWf^Ph;EO̽kTA- ]OT^pFfUOzfp,~*Pګՠz^3Х"'=K!cs`XE2"@Ti)ȬiZXS_Uƀيvʟ[ufl4>Vic0YL)@:/e $c L,\hʟgN_i,Lzbn>`pce#KwK?j?yWZP&(TZzbPh2S N_PN2F:}eSAm 4[|%j2;tHxt}xVҏ4?`N,cqrfR-; \sN_OƀJV-Ԛi+Vi)gv+ޖq|^HUwmrHWhJ\hl91wYhr61/]OC02s_)p,GArޤWt&9^KWS"y 풟uzc1(4 otA*c+(APh 6Hʙ$gEgs@iA~xت'5=kqX&=mrdlAfMC1)@9ob-EJA齩`hڠf'xBr^OjbyfA[30籕?+6N9`iM:XKQhnAfl}:U2 7%KT JsdYux {^WzPL- )Zbʟm?MfF@/d"(hxG $-5w0ltE}8 i ak OXk9L1ƀ1 !A!kak#1>RZhoA& q pcaZӀ%J?2cG9Z8~E3! Nkƌ3ɲ-r,TR<Seu[DoDAg+R64 >-mXG9 rl @Ύm)%Zm3l6R34ebF/!:&Hc&8G>kc8 yޕ .x+4[D)GE}-@اŜ*Hq Cjc:xy o4f!011azcV`vG7R"6A'|otGZX1 c7s.skRX%K119Q?\%퍦)oz ݽJ8g8k8 {'p5q̘`e=a `)B.H>IENDB`swingx-1.0-src/docs/images/shadow.png0000644000175000017500000000550611210401722016406 0ustar tonytonyPNG  IHDRGk@ pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FcIDATx0E'S!PqDveVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_F IDATxM%WЈ[Y-'vJ$da] _nL xPOWߍ%#"~׈_ok9s=/8"E/_"GD~߾VqEx=8?G"ZF}b^5̈|+L:Wy-Z||a%qOk'eu⹅C[5fuGֹ9y6[,Y29<71Okt]a/׎ؖb* a^pbO$A|\u8*Yp?E{ΞQHPw33>"~_h3ne<,/wg?P]׀"ցy U_67?d[ Ȩ'_)Ƥ(s 9^WZ28yf,5S<H:<@M[Ɉ8#8eHl73yP&#f?<\[2p d2쵖c9| 8+썕?^/U3'ByFsX_%Y.SNɷي 59|Mg8jzlEseϜyKbM,pK最XQi?\q#`7s-?,2|1/:YqZ^>15yJ02zeK?Z%C-nǢsJbG3KpO7@su3G|LDXzQJns=ph^5S1%|kkH?HOx.P%^&d,Nf(F'VֳEZۈ p'o?91Ng۷|V{l|uk91׃:-*9y?ϥB5|%k_\?C_g7U>3ڙ_=rtkrZʉ9<#^Z9K.yBZ/k96Cyn?6qճ|#wr><טB[D:$v0Ywgl̈zQeip33v?9`h[(4j+wf.ߺ 1Vna~ 9pu-U1'kjv\8Z/@ jM?1p% 97֗2#Ύ\$a#rπm,۝v2xSYr{#%[@36{Cx?:_r?கs+9iy3uI#C5Cq|'/n. <{ޮ6[+-!ZsxtjO%8sx; fZ~ԾVַ m]컄3"h gfS!E[\wTr+ΝBmlmnyJ0eBy8~ڨD eCp?缿Y={,TD皡,Dc6hQk|ss3*߽G-q/Ȩ1zX{Y+m6TMDr˅p~N?eϼm"pC5sg"b[ z$zr2vkјƲWYGcܓ|K_C듕k`\\BycK\s-h\9W~vs1e{a^*-p@TZb`9 ` 9`9 /`HOIENDB`swingx-1.0-src/docs/README0000644000175000017500000000377611210401722014035 0ustar tonytonyReadme - SwingLabs SwingX Project - http://swingx.dev.java.net SwingX is a library of components and utilities extending the Java Swing library; read more at our website, http://swingx.dev.java.net, and Wiki page, http://wiki.java.net/bin/view/Javadesktop/SwingLabsSwingX Getting the Latest Source ========================= 1) Check out the lastest code Download the latest release from our CVS repository; full instructions are at https://swingx.dev.java.net/servlets/ProjectSource but you can check out using the generic account "guest", with these settings cvs -d :pserver:guest@cvs.dev.java.net:/cvs login followed by cvs -d :pserver:guest@cvs.dev.java.net:/cvs checkout swingx Building the Source =================== SwingX relies on Ant and Ant build files for controlling compilation, building docs, testing, etc. You can use our Ant build scripts or use your own--some IDEs make this easy to do. To compile from the command line, you'll need to have Apache Ant installed; see http://ant.apache.org. IMPORTANT: our default task in Ant also runs our unit tests, which are written using jUnit. You need to have Ant be aware of jUnit *before* compiling SwingX. We can't help you with this--it's an Ant configuration issue. If jUnit is not properly configured, you may get an error like this: BUILD FAILED c:\swingx\nbproject\build-impl.xml:407: Following error occured while executing this line c:\\swingx\nbproject\build-impl.xml:127: Could not create task or type of type: junit. Ant could not find the task or a class this task relies upon. Suggestions: - for Ant 1.5.x and previous, make sure optional.jar is in your ANT_HOME\lib directory. - for Ant 1.6.x and above, make sure ant-junit.jar is in your ANT_HOME\lib directory, and that jUnit.jar is either in that directory as well OR listed on your CLASSPATH. You can build SwingX by going to the command line and typing ant That should be it--this will test and build swingx.jar in the dist directory. swingx-1.0-src/docs/README.html0000644000175000017500000001065611210401722014773 0ustar tonytony Readme - SwingLabs SwingX Project - http://swingx.dev.java.net

SwingX is a library of components and utilities extending the Java Swing library; read more at our website, http://swingx.dev.java.net, and Wiki page, http://wiki.java.net/bin/view/Javadesktop/SwingLabsSwingX

Getting the Latest Source

Download the latest release from our CVS repository; full instructions are at https://swingx.dev.java.net/servlets/ProjectSource. But you can check out using the generic account "guest", with these settings

            cvs -d :pserver:guest@cvs.dev.java.net:/cvs login
                        
followed by
            cvs -d :pserver:guest@cvs.dev.java.net:/cvs checkout swingx 
                        

Building the Source

SwingX relies on Ant and Ant build files for controlling compilation, building docs, testing, etc. You can use our Ant build scripts or use your own--some IDEs make this easy to do.

To compile from the command line, you'll need to have Apache Ant installed; see http://ant.apache.org.

IMPORTANT: our default task in Ant also runs our unit tests, which are written using jUnit. You need to have Ant be aware of jUnit before compiling SwingX. We can't help you with this--it's an Ant configuration issue.

If jUnit is not properly configured, you may get an error like this:

            BUILD FAILED
            c:\swingx\nbproject\build-impl.xml:407: Following error occured while executing this line
            c:\\swingx\nbproject\build-impl.xml:127: Could not create task or type of type: junit.

            Ant could not find the task or a class this task relies upon.
                        

Suggestions:

  • for Ant 1.5.x and previous, make sure optional.jar is in your ANT_HOME\lib directory.
  • for Ant 1.6.x and above, make sure ant-junit.jar is in your ANT_HOME\lib directory, and that jUnit.jar is either in that directory as well OR listed on your CLASSPATH.
You can build SwingX by going to the command line and typing

            ant
                        
That should be it--this will test and build swingx.jar in the dist directory.

swingx-1.0-src/docs/swinglabs.css0000644000175000017500000001423011210401722015643 0ustar tonytony/* Document : swinglabs Created on : October 11, 2005, 10:10 AM Author : rb156199 Description: Purpose of the stylesheet follows. */ /* TODO customize this sample style Syntax recommendation http://www.w3.org/TR/REC-CSS2/ */ body { background-color: #F8C04B; background-image: url(./images/background.png); background-repeat: repeat-x; margin: 0px 0px 0px 0px; } a { color: #3470D0; text-decoration: none; } a:visited { color: #F37700; } a:hover { text-decoration: underline; } /*====================================================*/ /* CONTAINER */ /*====================================================*/ #container { width: 742px; margin-left: auto; margin-right: auto; background-image: url(./images/shadow.png); background-repeat: repeat-y; } #stitch-hack { background-image: url(./images/stitch.png); background-repeat: no-repeat; background-position: 0px 89px; } /*====================================================*/ /* HEADER */ /*====================================================*/ #banner { height: 89px; width: 742px; background-image: url(./images/banner.png); background-repeat: repeat-x; } /*====================================================*/ /* MENU */ /*====================================================*/ #menu { width: 714px; margin-left: 14px; margin-right: 9px; padding-left: 0px; padding-right: 0px; height: 19px; text-align: left; background-image: url(./images/menu-background.png); background-repeat: repeat-x; } #menu a { vertical-align: top; font-family: Verdana, Arial, sans-serif; font-size: small; text-decoration: none; color: white; padding-left: 4px; padding-right: 4px; padding-bottom: 4px; } #menu a:hover { text-decoration: none; background-image: url(./images/menu-background-hover.png); background-repeat: repeat-x; } /*====================================================*/ /* CONTENT */ /*====================================================*/ #content { color: black; background-color: #FFFFFF; font-family: Verdana, Arial, sans-serif; font-size: small; width: 684px; margin-left: 14px; margin-right: 14px; padding-bottom: 25px; padding-left: 15px; padding-right: 15px; } #content p { text-align: justify; } #content h2 { margin-top: 0px; font-variant: small-caps; font-weight: bold; font-size: large; } #content span.arrow-left { background-image: url(./images/arrow-left.png); background-repeat: no-repeat; background-position: right; padding-right: 50px; } #content span.arrow-right { background-image: url(./images/arrow-right.png); background-repeat: no-repeat; padding-left: 50px; } #content h2.left { text-align: left; } #content h2.right { text-align: right; } div.section { padding-top: 25px; clear: left; } /*====================================================*/ /* NEWS ITEMS */ /*====================================================*/ #newsimg { float: left; } #news-title { font-size: small; } /*====================================================*/ /* CORE PROJECTS */ /*====================================================*/ .title-row { margin-top: -10px; } .first-col { padding-right: 5px; } .second-col { padding-left: 5px; } .odd-row { background: #E0E0E0; valign: top; } .even-row { valign: top; } /*====================================================*/ /* BOXES */ /*====================================================*/ #box { background-image: url(./images/box-background.png); background-repeat: repeat-y; width: 240px; color: white; float: right; margin-left: 15px; margin-right: -8px; } #box-2 { background-image: url(./images/box-background.png); background-repeat: repeat-y; width: 240px; color: white; float: left; margin-right: 15px; margin-left: -8px; } div.box-top { background-image: url(./images/box-top.png); background-repeat: no-repeat; background-position: top; padding-top: 8px; } div.box-content { background-image: url(./images/box-bottom.png); background-repeat: no-repeat; background-position: bottom; padding-top: 10px; padding-bottom: 18px; padding-left: 16px; padding-right: 8px; } div.title { font-size: large; font-variant: small-caps; font-weight: bold; padding-left: 16px; padding-right: 8px; } div.subtitle { padding-left: 16px; padding-right: 8px; font-weight: bold; font-size: normal; } /*====================================================*/ /* FOOTER */ /*====================================================*/ #footer { background-image: url(./images/footer.png); background-repeat: repeat-x; height: 51px; width: 740px; } /*====================================================*/ /* MISCELLANEOUS */ /*====================================================*/ .code { background-color: #FFFFCC; padding: 10px; border: 1px solid #000000; margin: 10px; font-family: "Courier New", Courier, mono; } /*====================================================*/ /* SCREENSHOTS */ /*====================================================*/ .screenshot-caption { clear: left; } /*====================================================*/ /* STORE */ /*====================================================*/ span.component-title { font-weight: bold; font-size: normal; } span.description-title { font-size: small; } img.component-icon { float: left; margin-right: 6px; } span.components-links { margin-left: 38px; } p.component { padding-bottom: 12px; } img.component-small-icon { margin-right: 3px; vertical-align: bottom; } #catalog { margin-bottom: 6px; } #selected-components { padding-left: 8px; padding-right: 8px; margin-right: 8px; margin-bottom: 8px; overflow: auto; height: 216px; border: 2px solid #FFFFFF; } #download-buttons { text-align: right; margin-right: 8px; }swingx-1.0-src/header.regex0000644000175000017500000000177211210401722014503 0ustar tonytony^/\*\s*$ ^ \* \$.*\s*$ ^ \*\s*$ ^ \* Copyright 20\d\d Sun Microsystems, Inc\., 4150 Network Circle,\s*$ ^ \* Santa Clara, California 95054, U\.S\.A\. All rights reserved\.\s*$ ^ \*\s*$ ^ \* This library is free software; you can redistribute it and/or\s*$ ^ \* modify it under the terms of the GNU Lesser General Public\s*$ ^ \* License as published by the Free Software Foundation; either\s*$ ^ \* version 2\.1 of the License, or \(at your option\) any later version\.\s*$ ^ \*\s*$ ^ \* This library is distributed in the hope that it will be useful,\s*$ ^ \* but WITHOUT ANY WARRANTY; without even the implied warranty of\s*$ ^ \* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE\. See the GNU\s*$ ^ \* Lesser General Public License for more details\.\s*$ ^ \*\s*$ ^ \* You should have received a copy of the GNU Lesser General Public\s*$ ^ \* License along with this library; if not, write to the Free Software\s*$ ^ \* Foundation, Inc\., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\s*$ ^ \*/\s*$ swingx-1.0-src/swinglabs-build-impl.xml0000644000175000017500000003267011210401722016767 0ustar tonytony ${build.branch} ${RELEASE_DSTAMP_LONG} ${projectname} Using custom javadoc target: core src: ${javadoc.core.src} core external: ${javadoc.core.linkexternal} core packagelist: ${javadoc.core.packagelist} importing to CVS... swingx-1.0-src/styles/0000755000175000017500000000000011210401734013536 5ustar tonytonyswingx-1.0-src/styles/eclipse_formatter_jw.xml0000644000175000017500000006706311210401722020500 0ustar tonytony swingx-1.0-src/COPYING0000644000175000017500000006456511210401722013263 0ustar tonytonyCopyright (c) 2005-2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved. Use is subject to license terms below. Sun, Sun Microsystems and the Sun logo are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries. Notice: This product is covered by U.S. export control laws and may be subject to the export or import laws in other countries. These laws may restrict the fields of use for this software and may require you to secure government authorization. GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice swingx-1.0-src/swingx-beaninfo/0000755000175000017500000000000011210401734015311 5ustar tonytonyswingx-1.0-src/swingx-beaninfo/pom.xml0000644000175000017500000000353011210401722016624 0ustar tonytony swingx-project org.swinglabs 0.9.3-SNAPSHOT ../pom.xml 4.0.0 swingx-beaninfo jar SwingX Beaninfo org.swinglabs swingx-core ${parent.version} com.jhlabs filters org.swinglabs swing-worker org.swinglabs multiplegradientpaint ../src/beaninfo org.apache.maven.plugins maven-jar-plugin test-jar swingx-1.0-src/nbproject/0000755000175000017500000000000011210401736014203 5ustar tonytonyswingx-1.0-src/nbproject/project.xml0000644000175000017500000000126211210401722016367 0ustar tonytony org.netbeans.modules.java.j2seproject swingx 1.6.5 swingx-1.0-src/nbproject/project.properties0000644000175000017500000001174611210401722017773 0ustar tonytony########################################################## # General Build Related Directories # ########################################################## # This directory is removed when the project is cleaned: build.dir=build build.generated.dir=${build.dir}/generated build.classes.dir=${build.dir}/classes build.beaninfo.classes.dir=${build.dir}/beaninfo/classes build.test.classes.dir=${build.dir}/test/classes build.test.results.dir=${build.dir}/test/results # This directory is removed when the project is cleaned: dist.dir=dist dist.jar=${dist.dir}/swingx.jar dist.beaninfo.jar=${dist.dir}/swingx-beaninfo.jar dist.javadoc.dir=${dist.dir}/javadoc ########################h################################## # Source and test directories # ########################################################## java.dir=${file.reference.src-java} # Property libs.swing-layout.classpath is set here just to make sharing of project simpler. # The library definition has always preference over this property. libs.swing-layout.classpath=../../../../../Applications/NetBeans 6.app/Contents/Resources/NetBeans/platform7/modules/ext/swing-layout-1.0.1.jar src.beaninfo.dir=src/beaninfo src.demo.dir=src/demo test.test.dir=src/test ########################################################## # Library references # ########################################################## file.reference.jmock-1.1.0RC1.jar=lib/jmock-1.1.0RC1.jar file.reference.MultipleGradientPaint.jar=lib/optional/MultipleGradientPaint.jar file.reference.src-java=src/java file.reference.src-test=src/test file.reference.swing-worker.jar=lib/optional/swing-worker.jar file.reference.Filters.jar=lib/optional/Filters.jar file.reference.commons.lang.jar=lib/build-only/commons-lang-2.4.jar file.reference.commons.collections.jar=lib/build-only/commons-collections-3.2.1.jar ########################################################## # Build, test, debug, etc Classpaths # ########################################################## debug.classpath=\ ${run.classpath} debug.test.classpath=\ ${run.test.classpath} javac.classpath=\ ${file.reference.MultipleGradientPaint.jar}:\ ${file.reference.swing-worker.jar}:\ ${file.reference.Filters.jar} javac.test.classpath=\ ${javac.classpath}:\ ${build.classes.dir}:\ ${libs.junit.classpath}:\ ${file.reference.jmock-1.1.0RC1.jar}:\ ${file.reference.commons.collections.jar}:\ ${file.reference.commons.lang.jar} run.classpath=\ ${javac.classpath}:\ ${build.classes.dir} run.test.classpath=\ ${javac.test.classpath}:\ ${build.test.classes.dir}:\ ${file.reference.commons.collections.jar}:\ ${file.reference.commons.lang.jar} javadoc.srcpath=\ ${src.beaninfo.dir}:\ ${java.dir}:\ ${javadoc.core.src} ########################################################## # General Properties and Command Switches # ########################################################## ##### # Build Related Properties ##### build.classes.excludes=**/*.java,**/*.form # Only compile against the classpath explicitly listed here: build.sysclasspath=ignore jar.compress=true manifest.file=manifest.mf meta.inf.dir=${src.dir}/META-INF platform.active=default_platform ##### # Javac Options ##### # Space-separated list of extra javac options javac.compilerargs= javac.deprecation=false javac.source=1.5 javac.target=1.5 ##### # Javadoc Options ##### javadoc.additionalparam= javadoc.author=false javadoc.encoding= javadoc.noindex=false javadoc.nonavbar=false javadoc.notree=false javadoc.private=false javadoc.splitindex=true javadoc.use=true javadoc.version=false javadoc.verbose=false javadoc.windowtitle=SwingLabs JavaDoc javadoc.compress=true ##### # Properties for a "main class" and running that class. # These are generally not used in SwingX ##### main.class=org.jdesktop.swingx.painter.demo.PainterDemoSet application.args= # Space-separated list of JVM arguments used when running the project # (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value # or test-sys-prop.name=value to set system properties for unit tests): run.jvmargs= ########################################################## # Properties for the swinglabs-build-impl ANT script # ########################################################## # directory that contains emma.jar and emma_ant.jar emma.dir=lib/build-only emma.report.srcpath=\ ${src.beaninfo.dir}:\ ${java.dir} # directory to place the built bundles dist.bundles.dir=${dist.dir}/bundles # scratch directory to use for building the bundles build.bundles.dir=${build.dir}/bundles # Colon separated list of directories to include as the "docs" (readme, etc) for the bundle bundles.doc.dir=docs # The name of the project, used when creating the bundles projectname=swingx # Info for updating the posted.txt file posted.txt= build.branch=MAIN # Location of the demo-taglet jar file demo.taglet.jar=lib/build-only/demo-taglet.jar swingx-1.0-src/nbproject/genfiles.properties0000644000175000017500000000067711210401722020122 0ustar tonytonybuild.xml.data.CRC32=f1851f45 build.xml.script.CRC32=58c7d933 build.xml.stylesheet.CRC32=e2435cb5 # This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. # Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. nbproject/build-impl.xml.data.CRC32=5747d8ab nbproject/build-impl.xml.script.CRC32=d3f68530 nbproject/build-impl.xml.stylesheet.CRC32=61d6088b swingx-1.0-src/nbproject/build-impl.xml0000644000175000017500000006567011210401722016774 0ustar tonytony Must set src.beaninfo.dir Must set java.dir Must set test.test.dir Must set build.dir Must set dist.dir Must set build.classes.dir Must set dist.javadoc.dir Must set build.test.classes.dir Must set build.test.results.dir Must set build.classes.excludes Must set dist.jar Must select some files in the IDE or set javac.includes To run this application from the command line without Ant, try: java -cp "${run.classpath.with.dist.jar}" ${main.class} To run this application from the command line without Ant, try: java -jar "${dist.jar.resolved}" Must select one file in the IDE or set run.class Must select one file in the IDE or set debug.class Must set fix.includes Must select some files in the IDE or set javac.includes Some tests failed; see details above. Must select some files in the IDE or set test.includes Some tests failed; see details above. Must select one file in the IDE or set test.class Must select one file in the IDE or set applet.url Must select one file in the IDE or set applet.url swingx-1.0-src/swingx.pom0000644000175000017500000000607011210401722014247 0ustar tonytony 3 swinglabs swingx @VERSION@ SwingLabs Swing Component Extensions Extensions to the Swing GUI toolkit Contains extensions to the Swing GUI toolkit, including new and enhanced components that provide functionality commonly required by rich client applications. https://swingx.dev.java.net/ https://swingx.dev.java.net/servlets/ProjectIssues 2003 swingx.dev.java.net / discussion list jdnc-subscribe@jdnc.dev.java.net jdnc-unsubscribe@jdnc.dev.java.net https://jdnc.dev.java.net/servlets/SummarizeList?listName=jdnc Lesser General Public License (LGPL) http://www.gnu.org/copyleft/lesser.html repo scm:cvs:pserver:guest@cvs.dev.java.net:/cvs:swingx https://swingx.dev.java.net/source/browse/swingx/ http://www.java.net/ https://dalma.dev.java.net/maven/images/java.net-logo.png org.jdesktop.swingx src/java src/test src/test **/*.xml **/*.xsl **/*.rng **/*.dtd **/*Test.java src/java **/*.properties swingx-1.0-src/README0000644000175000017500000000371511210401722013076 0ustar tonytonyReadme - SwingLabs SwingX Project - http://swingx.dev.java.net SwingX is a library of components and utilities extending the Java Swing library; read more at our website, http://swingx.dev.java.net, and Wiki page, http://wiki.java.net/bin/view/Javadesktop/SwingLabsSwingX Getting the Latest Source ========================= 1) Check out the lastest code Download the latest release from our CVS repository; full instructions are at https://swingx.dev.java.net/servlets/ProjectSource but you can check out using the generic account "guest", with these settings cvs -d :pserver:guest@cvs.dev.java.net:/cvs login followed by cvs -d :pserver:guest@cvs.dev.java.net:/cvs checkout swingx Building the Source =================== SwingX relies on Ant and Ant build files for controlling compilation, building docs, testing, etc. You can use our Ant build scripts or use your own--some IDEs make this easy to do. To compile from the command line, you'll need to have Apache Ant installed; see http://ant.apache.org. IMPORTANT: our default task in Ant also runs our unit tests, which are written using jUnit. You need to have Ant be aware of jUnit *before* compiling SwingX. We can't help you with this--it's an Ant configuration issue. If jUnit is not properly configured, you may get an error like this: BUILD FAILED c:\swingx\nbproject\build-impl.xml:407: Following error occured while executing this line c:\\swingx\nbproject\build-impl.xml:127: Could not create task or type of type: junit. Ant could not find the task or a class this task relies upon. Suggestions: - for Ant 1.5.x and previous, make sure optional.jar is in your ANT_HOME\lib directory. - for Ant 1.6.x and above, make sure ant-junit.jar is in your ANT_HOME\lib directory, and that jUnit.jar is either in that directory as well OR listed on your CLASSPATH. You can build SwingX by going to the command line and typing ant That should be it--this will test and build swingx.jar in the dist directory. swingx-1.0-src/swingx-demos/0000755000175000017500000000000011210401732014635 5ustar tonytonyswingx-1.0-src/swingx-demos/pom.xml0000644000175000017500000000407011210401722016152 0ustar tonytony swingx-project org.swinglabs 0.9.3-SNAPSHOT ../pom.xml 4.0.0 swingx-demo jar SwingX Demos org.swinglabs swingx-core ${parent.version} org.swinglabs swingx-beaninfo ${parent.version} com.jhlabs filters org.swinglabs swing-worker org.swinglabs multiplegradientpaint org.swinglabs swing-layout 1.0.3 compile ../src/demo org.apache.maven.plugins maven-jar-plugin swingx-1.0-src/pom.xml0000644000175000017500000002241711210401722013533 0ustar tonytony 4.0.0 org.swinglabs swingx jar SwingX Main Project 0.9.5-SNAPSHOT http://www.swinglabs.org/ Lesser General Public License (LGPL) http://www.gnu.org/copyleft/lesser.html https://swingx.dev.java.net/source/browse/swingx/ Contains extensions to the Swing GUI toolkit, including new and enhanced components that provide functionality commonly required by rich client applications. target target/classes ${project.artifactId}-${project.version} target/test-classes src/java src/main/scripts src/test src/java **/*.java src/test **/*.java maven-compiler-plugin 1.5 1.5 true true org.apache.maven.plugins maven-surefire-plugin true **/*Test.java always org.apache.maven.plugins maven-jar-plugin org.codehaus.mojo emma-maven-plugin 1.0-SNAPSHOT true instrument net.sf.jmd maven-crap4j-plugin 0.1.1-SNAPSHOT ${basedir} lib/build-only/crap4j target/site/crap4j-reports lib site crap4j crap4jAnt com.jhlabs filters 2.0.235 compile org.swinglabs swing-worker 1.1 org.swinglabs multiplegradientpaint 1.0 compile junit junit 4.5 test jmock jmock 1.2.0 test junit junit commons-collections commons-collections 3.2.1 commons-lang commons-lang 2.4 1.5 org.swinglabs swing-layout 1.0.3 compile org.apache.maven.plugins maven-checkstyle-plugin checkstyle.xml true maven-changes-plugin ${basedir}/xdocs/changes.xml maven-javadoc-plugin true true maven-surefire-report-plugin org.codehaus.mojo surefire-report-maven-plugin true org.codehaus.mojo emma-maven-plugin 1.0-SNAPSHOT true org.codehaus.mojo findbugs-maven-plugin 1.2.1 true target Normal Default FindDeadLocalStores,UnreadFields org.jdesktop.* true target codehaus Codehaus Plugin Repository http://snapshots.repository.codehaus.org default true never jmd.sf.net http://jmd.sf.net/m2repository true swingx-1.0-src/lib/0000755000175000017500000000000011210513512012757 5ustar tonytonyswingx-1.0-src/build.xml0000644000175000017500000001441011210401724014033 0ustar tonytony Builds, tests, and runs the project swingx. org/jdesktop/swingx/JXCollapsiblePane.class org/jdesktop/swingx/JXDatePicker.class org/jdesktop/swingx/JXHyperlink.class org/jdesktop/swingx/JXGraph.class org/jdesktop/swingx/JXPanel.class org/jdesktop/swingx/JXTaskPaneContainer.class org/jdesktop/swingx/JXTreeTable.class org/jdesktop/swingx/JXTitledPanel.class org/jdesktop/swingx/JXEditorPane.class org/jdesktop/swingx/JXErrorPane.class org/jdesktop/swingx/JXList.class org/jdesktop/swingx/JXImagePanel.class org/jdesktop/swingx/JXHeader.class org/jdesktop/swingx/JXTable.class org/jdesktop/swingx/JXTree.class org/jdesktop/swingx/JXTipOfTheDay.class org/jdesktop/swingx/JXRadioGroup.class org/jdesktop/swingx/JXTitledSeparator.class org/jdesktop/swingx/JXFindBar.class org/jdesktop/swingx/JXFindPanel.class org/jdesktop/swingx/JXFrame.class org/jdesktop/swingx/JXGlassBox.class org/jdesktop/swingx/JXGradientChooser.class org/jdesktop/swingx/JXLoginDialog.class org/jdesktop/swingx/JXLoginPane.class org/jdesktop/swingx/JXMonthView.class org/jdesktop/swingx/JXMultiSplitPane.class org/jdesktop/swingx/JXMultiThumbSlider.class org/jdesktop/swingx/JXRootPane.class org/jdesktop/swingx/JXSearchPanel.class org/jdesktop/swingx/JXStatusBar.class org/jdesktop/swingx/JXTaskPane.class org/jdesktop/swingx/auth/DefaultUserNameStore.class org/jdesktop/swingx/auth/JAASLoginService.class org/jdesktop/swingx/auth/JDBCLoginService.class org/jdesktop/swingx/border/DropShadowBorder.class org/jdesktop/swingx/painter/AlphaPainter.class org/jdesktop/swingx/painter/CheckerboardPainter.class org/jdesktop/swingx/painter/CompoundPainter.class org/jdesktop/swingx/painter/GlossPainter.class org/jdesktop/swingx/painter/ImagePainter.class org/jdesktop/swingx/painter/MattePainter.class org/jdesktop/swingx/painter/PinstripePainter.class org/jdesktop/swingx/painter/RectanglePainter.class org/jdesktop/swingx/painter/ShapePainter.class org/jdesktop/swingx/painter/TextPainter.class swingx-1.0-src/swingx.iml0000644000175000017500000000327311210401722014237 0ustar tonytony swingx-1.0-src/swingx-core/0000755000175000017500000000000011210401734014460 5ustar tonytonyswingx-1.0-src/swingx-core/pom.xml0000644000175000017500000000451511210401722015777 0ustar tonytony swingx-project org.swinglabs 0.9.3-SNAPSHOT ../pom.xml 4.0.0 swingx-core jar SwingX Core com.jhlabs filters org.swinglabs swing-worker org.swinglabs multiplegradientpaint junit junit jmock jmock ../src/java ../src/test ../src/java **/*.java ../src/test **/*.java org.apache.maven.plugins maven-jar-plugin test-jar swingx-1.0-src/manifest.mf0000644000175000017500000000625411210401722014351 0ustar tonytonyManifest-Version: 1.0 X-COMMENT: Main-Class will be added automatically by build Name: org/jdesktop/swingx/JXCollapsiblePane.class Java-Bean: True Name: org/jdesktop/swingx/JXDatePicker.class Java-Bean: True Name: org/jdesktop/swingx/JXDialog.class Java-Bean: False Name: org/jdesktop/swingx/JXEditorPane.class Java-Bean: True Name: org/jdesktop/swingx/JXFindBar.class Java-Bean: True Name: org/jdesktop/swingx/JXFindPanel.class Java-Bean: True Name: org/jdesktop/swingx/JXFrame.class Java-Bean: True Name: org/jdesktop/swingx/JXGlassBox.class Java-Bean: True Name: org/jdesktop/swingx/JXGradientChooser.class Java-Bean: True Name: org/jdesktop/swingx/JXGraph.class Java-Bean: True Name: org/jdesktop/swingx/JXHeader.class Java-Bean: True Name: org/jdesktop/swingx/JXHyperlink.class Java-Bean: True Name: org/jdesktop/swingx/JXImagePanel.class Java-Bean: True Name: org/jdesktop/swingx/JXList.class Java-Bean: True Name: org/jdesktop/swingx/JXLoginDialog.class Java-Bean: True Name: org/jdesktop/swingx/JXLoginPane.class Java-Bean: True Name: org/jdesktop/swingx/JXMonthView.class Java-Bean: True Name: org/jdesktop/swingx/JXMultiSplitPane.class Java-Bean: True Name: org/jdesktop/swingx/JXMultiThumbSlider.class Java-Bean: True Name: org/jdesktop/swingx/JXPanel.class Java-Bean: True Name: org/jdesktop/swingx/JXRadioGroup.class Java-Bean: True Name: org/jdesktop/swingx/JXRootPane.class Java-Bean: True Name: org/jdesktop/swingx/JXSearchPanel.class Java-Bean: True Name: org/jdesktop/swingx/JXStatusBar.class Java-Bean: True Name: org/jdesktop/swingx/JXTable.class Java-Bean: True Name: org/jdesktop/swingx/JXTaskPane.class Java-Bean: True Name: org/jdesktop/swingx/JXTaskPaneContainer.class Java-Bean: True Name: org/jdesktop/swingx/JXTipOfTheDay.class Java-Bean: True Name: org/jdesktop/swingx/JXTitledPanel.class Java-Bean: True Name: org/jdesktop/swingx/JXTitledSeparator.class Java-Bean: True Name: org/jdesktop/swingx/JXTree.class Java-Bean: True Name: org/jdesktop/swingx/JXBusyLabel.class Java-Bean: True Name: org/jdesktop/swingx/JXLabel.class Java-Bean: True Name: org/jdesktop/swingx/JXTreeTable.class Java-Bean: True Name: org/jdesktop/swingx/auth/DefaultUserNameStore.class Java-Bean: True Name: org/jdesktop/swingx/auth/JAASLoginService.class Java-Bean: True Name: org/jdesktop/swingx/auth/JDBCLoginService.class Java-Bean: True Name: org/jdesktop/swingx/border/DropShadowBorder.class Java-Bean: True Name: org/jdesktop/swingx/border/MatteBorderExt.class Java-Bean: False Name: org/jdesktop/swingx/painter/AlphaPainter.class Java-Bean: True Name: org/jdesktop/swingx/painter/CheckerboardPainter.class Java-Bean: True Name: org/jdesktop/swingx/painter/CompoundPainter.class Java-Bean: True Name: org/jdesktop/swingx/painter/GlossPainter.class Java-Bean: True Name: org/jdesktop/swingx/painter/ImagePainter.class Java-Bean: True Name: org/jdesktop/swingx/painter/MattePainter.class Java-Bean: True Name: org/jdesktop/swingx/painter/PinstripePainter.class Java-Bean: True Name: org/jdesktop/swingx/painter/RectanglePainter.class Java-Bean: True Name: org/jdesktop/swingx/painter/ShapePainter.class Java-Bean: True Name: org/jdesktop/swingx/painter/TextPainter.class Java-Bean: True swingx-1.0-src/checkstyle.xml0000644000175000017500000002546611210401722015105 0ustar tonytony swingx-1.0-src/src/0000755000175000017500000000000011210401724013001 5ustar tonytonyswingx-1.0-src/src/beaninfo/0000755000175000017500000000000011210401724014562 5ustar tonytonyswingx-1.0-src/src/beaninfo/org/0000755000175000017500000000000011210401724015351 5ustar tonytonyswingx-1.0-src/src/beaninfo/org/jdesktop/0000755000175000017500000000000011210401724017174 5ustar tonytonyswingx-1.0-src/src/beaninfo/org/jdesktop/swingx/0000755000175000017500000000000011210401736020516 5ustar tonytonyswingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXErrorPaneBeanInfo.java0000644000175000017500000000104711210401722025117 0ustar tonytonypackage org.jdesktop.swingx; import java.beans.BeanDescriptor; /** * BeanInfo class for JXErrorPane. * * @author Jan Stola */ public class JXErrorPaneBeanInfo extends BeanInfoSupport { public JXErrorPaneBeanInfo() { super(JXErrorPane.class); } protected void initialize() { BeanDescriptor bd = getBeanDescriptor(); bd.setValue("isContainer", Boolean.FALSE); setPreferred(true, "errorInfo", "icon"); setPreferred(false, "background", "border", "foreground", "toolTipText"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXTaskPaneBeanInfo.java0000644000175000017500000000363211210401722024732 0ustar tonytony/* * $Id: JXTaskPaneBeanInfo.java,v 1.4 2009/02/09 14:53:59 kschaefe Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.beans.BeanDescriptor; /** * BeanInfo class for JXTaskPane. * * @author rbair, Jan Stola */ public class JXTaskPaneBeanInfo extends BeanInfoSupport { /** Constructor for the JXTaskPaneBeanInfo object */ public JXTaskPaneBeanInfo() { super(JXTaskPane.class); } protected void initialize() { BeanDescriptor bd = getBeanDescriptor(); // setup bean descriptor in constructor. bd.setName("JXTaskPane"); bd.setShortDescription("JXTaskPane is a container for tasks and other arbitrary components."); bd.setValue("isContainer", Boolean.TRUE); bd.setValue("containerDelegate", "getContentPane"); setPreferred(true, "title", "icon", "special"); setPreferred(true, "animated", "scrollOnExpand", "collapsed", "font"); setBound(true, "title", "icon", "special", "scrollOnExpand", "collapsed"); setPreferred(false, "border"); } }swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXBusyLabelBeanInfo.java0000644000175000017500000000076111210401722025106 0ustar tonytonypackage org.jdesktop.swingx; /** * BeanInfo class for JXBusyLabel. * * @author Jan Stola */ public class JXBusyLabelBeanInfo extends BeanInfoSupport { public JXBusyLabelBeanInfo() { super(JXBusyLabel.class); } protected void initialize() { setPreferred(true, "busy"); String iconName = "resources/" + JXBusyLabel.class.getSimpleName(); setSmallMonoIconName(iconName + "16.png"); setMonoIconName(iconName + "32.png"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXTaskPaneContainerBeanInfo.java0000644000175000017500000000312411210401722026571 0ustar tonytony/* * $Id: JXTaskPaneContainerBeanInfo.java,v 1.2 2006/03/16 22:53:55 rbair Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.beans.BeanDescriptor; /** * BeanInfo class for JXTaskPaneContainer. */ public class JXTaskPaneContainerBeanInfo extends BeanInfoSupport { /** Constructor for the JXTaskPaneContainerBeanInfo object */ public JXTaskPaneContainerBeanInfo() { super(JXTaskPaneContainer.class); } protected void initialize() { BeanDescriptor bd = getBeanDescriptor(); // setup bean descriptor in constructor. bd.setName("JXTaskPaneContainer"); bd.setShortDescription("A component that contains JXTaskPanes."); bd.setValue("isContainer", Boolean.TRUE); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXFindBarBeanInfo.java0000644000175000017500000000063411210401722024530 0ustar tonytonypackage org.jdesktop.swingx; import java.beans.BeanDescriptor; /** * BeanInfo class for JXFindBar. * * @author Jan Stola */ public class JXFindBarBeanInfo extends BeanInfoSupport { public JXFindBarBeanInfo() { super(JXFindBar.class); } protected void initialize() { BeanDescriptor bd = getBeanDescriptor(); bd.setValue("isContainer", Boolean.FALSE); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXHeaderBeanInfo.java0000644000175000017500000000376111210401722024417 0ustar tonytony/* * $Id: JXHeaderBeanInfo.java,v 1.3 2007/12/08 13:43:58 stolis Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.beans.BeanDescriptor; import org.jdesktop.swingx.editors.EnumPropertyEditor; /** * BeanInfo class for JXHeader. * * @author rbair, Jan Stola */ public class JXHeaderBeanInfo extends BeanInfoSupport { public JXHeaderBeanInfo() { super(JXHeader.class); } protected void initialize() { BeanDescriptor bd = getBeanDescriptor(); bd.setValue("isContainer", Boolean.FALSE); setPreferred(true, "title", "titleFont", "titleForeground"); setPreferred(true, "description", "descriptionFont", "descriptionForeground"); setPreferred(true, "icon", "iconPosition"); setPreferred(false, "alpha", "background", "backgroundPainter", "border", "inheritAlpha", "opaque", "font"); setPropertyEditor(IconPositionPropertyEditor.class, "iconPosition"); } public static final class IconPositionPropertyEditor extends EnumPropertyEditor { public IconPositionPropertyEditor() { super(JXHeader.IconPosition.class); } } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXTableBeanInfo.java0000644000175000017500000000222411210401722024247 0ustar tonytony/* * $Id: JXTableBeanInfo.java,v 1.3 2006/03/16 22:53:54 rbair Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; /** * * @author rbair */ public class JXTableBeanInfo extends BeanInfoSupport { public JXTableBeanInfo() { super(JXTable.class); } protected void initialize() { } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/VerticalLayoutBeanInfo.java0000644000175000017500000000051711210401722025730 0ustar tonytonypackage org.jdesktop.swingx; /** * BeanInfo class for VerticalLayout. * * @author Jan Stola */ public class VerticalLayoutBeanInfo extends BeanInfoSupport { public VerticalLayoutBeanInfo() { super(VerticalLayout.class); } protected void initialize() { setHidden(true, "class"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXTreeBeanInfo.java0000644000175000017500000000222011210401724024115 0ustar tonytony/* * $Id: JXTreeBeanInfo.java,v 1.3 2006/03/16 22:53:54 rbair Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; /** * * @author rbair */ public class JXTreeBeanInfo extends BeanInfoSupport { public JXTreeBeanInfo() { super(JXTree.class); } protected void initialize() { } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXMultiSplitPaneBeanInfo.java0000644000175000017500000000274111210401722026136 0ustar tonytony/* * $Id: JXMultiSplitPaneBeanInfo.java,v 1.2 2007/08/18 11:44:11 luano Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; /** * Bean info for {@link org.jdesktop.swingx.JXMultiSplitPane} component. * * @author Hans Muller */ public class JXMultiSplitPaneBeanInfo extends BeanInfoSupport { public JXMultiSplitPaneBeanInfo() { super(JXMultiSplitPane.class); } // model, dividerSize, continuousLayout, dividerPainter protected void initialize() { setCategory("MultiSplitPane Layout, Appearance", "model", "dividerSize", "continuousLayout", "dividerPainter"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/painter/0000755000175000017500000000000011210401736022160 5ustar tonytonyswingx-1.0-src/src/beaninfo/org/jdesktop/swingx/painter/MattePainterBeanInfo.java0000644000175000017500000000067011210401722027020 0ustar tonytonypackage org.jdesktop.swingx.painter; import org.jdesktop.swingx.BeanInfoSupport; /** * BeanInfo of MattePainter. * * @author joshy, Jan Stola */ public class MattePainterBeanInfo extends BeanInfoSupport { /** Creates a new instance of MattePainterBeanInfo */ public MattePainterBeanInfo() { super(MattePainter.class); } protected void initialize() { setPreferred(true, "fillPaint"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/painter/RectanglePainterBeanInfo.java0000644000175000017500000000074711210401722027657 0ustar tonytonypackage org.jdesktop.swingx.painter; import org.jdesktop.swingx.BeanInfoSupport; /** * BeanInfo of RectanglePainter. * * @author joshy, Jan Stola */ public class RectanglePainterBeanInfo extends BeanInfoSupport { /** Creates a new instance of RectanglePainterBeanInfo */ public RectanglePainterBeanInfo() { super(RectanglePainter.class); } protected void initialize() { setPreferred(true, "roundHeight", "roundWidth", "rounded"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/painter/CompoundPainterBeanInfo.java0000644000175000017500000000070311210401722027527 0ustar tonytonypackage org.jdesktop.swingx.painter; import org.jdesktop.swingx.BeanInfoSupport; /** * BeanInfo of CompoundPainter. * * @author Richard, Jan Stola */ public class CompoundPainterBeanInfo extends BeanInfoSupport { /** Creates a new instance of CompoundPainterBeanInfo */ public CompoundPainterBeanInfo() { super(CompoundPainter.class); } protected void initialize() { setPreferred(true, "painters"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/painter/CheckerboardPainterBeanInfo.java0000644000175000017500000000117511210401722030323 0ustar tonytonypackage org.jdesktop.swingx.painter; import org.jdesktop.swingx.BeanInfoSupport; import org.jdesktop.swingx.editors.PaintPropertyEditor; /** * BeanInfo of CheckerboardPainter. * * @author Richard, Jan Stola */ public class CheckerboardPainterBeanInfo extends BeanInfoSupport { /** Creates a new instance of CheckerboardPainterBeanInfo */ public CheckerboardPainterBeanInfo() { super(CheckerboardPainter.class); } protected void initialize() { setPreferred(true, "darkPaint", "lightPaint", "squareSize"); setPropertyEditor(PaintPropertyEditor.class, "darkPaint", "lightPaint"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/painter/ShapePainterBeanInfo.java0000644000175000017500000000105311210401722027002 0ustar tonytonypackage org.jdesktop.swingx.painter; import org.jdesktop.swingx.BeanInfoSupport; import org.jdesktop.swingx.editors.ShapePropertyEditor; /** * BeanInfo of ShapePainter. * * @author joshy, Jan Stola */ public class ShapePainterBeanInfo extends BeanInfoSupport { /** Creates a new instance of ShapePainterBeanInfo */ public ShapePainterBeanInfo() { super(ShapePainter.class); } protected void initialize() { setPropertyEditor(ShapePropertyEditor.class, "shape"); setPreferred(true, "shape"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/painter/AbstractPainterBeanInfo.java0000644000175000017500000000226511210401722027513 0ustar tonytonypackage org.jdesktop.swingx.painter; import org.jdesktop.swingx.BeanInfoSupport; import org.jdesktop.swingx.editors.EnumPropertyEditor; /** * BeanInfo of AbstractPainter. * * @author Richard, Jan Stola */ public class AbstractPainterBeanInfo extends BeanInfoSupport { /** Creates a new instance of BackgroundPainterBeanInfo */ public AbstractPainterBeanInfo() { super(AbstractPainter.class); } public AbstractPainterBeanInfo(Class clazz) { super(clazz); } protected void initialize() { setHidden(true, "class", "propertyChangeListeners", "vetoableChangeListeners", "filters"); setPropertyEditor(InterpolationPropertyEditor.class, "interpolation"); //move some items into "Appearance" and some into "Behavior" //setCategory("Rendering Hints", "antialiasing", "fractionalMetrics", "interpolation"); setExpert(true, "antialiasing","cacheable","interpolation"); } public static final class InterpolationPropertyEditor extends EnumPropertyEditor { public InterpolationPropertyEditor() { super(AbstractPainter.Interpolation.class); } } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/painter/AbstractAreaPainterBeanInfo.java0000644000175000017500000000162511210401722030303 0ustar tonytonypackage org.jdesktop.swingx.painter; import org.jdesktop.swingx.BeanInfoSupport; import org.jdesktop.swingx.editors.EnumPropertyEditor; import org.jdesktop.swingx.editors.Paint2PropertyEditor; /** * BeanInfo of AbstractAreaPainter. * * @author Jan Stola */ public class AbstractAreaPainterBeanInfo extends BeanInfoSupport { public AbstractAreaPainterBeanInfo() { super(AbstractAreaPainter.class); } public AbstractAreaPainterBeanInfo(Class clazz) { super(clazz); } protected void initialize() { setPropertyEditor(StylePropertyEditor.class, "style"); setPropertyEditor(Paint2PropertyEditor.class, "fillPaint", "borderPaint"); } public static final class StylePropertyEditor extends EnumPropertyEditor { public StylePropertyEditor() { super(AbstractAreaPainter.Style.class); } } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/painter/AlphaPainterBeanInfo.java0000644000175000017500000000056311210401722026774 0ustar tonytonypackage org.jdesktop.swingx.painter; import org.jdesktop.swingx.BeanInfoSupport; /** * BeanInfo of AlphaPainter. * * @author Jan Stola */ public class AlphaPainterBeanInfo extends BeanInfoSupport { public AlphaPainterBeanInfo() { super(AlphaPainter.class); } protected void initialize() { setPreferred(true, "alpha"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/painter/effects/0000755000175000017500000000000011210401734023575 5ustar tonytonyswingx-1.0-src/src/beaninfo/org/jdesktop/swingx/painter/effects/NeonBorderEffectBeanInfo.java0000644000175000017500000000226211210401722031213 0ustar tonytony/* * NeonBorderEffectBeanInfo.java * * Created on October 30, 2006, 1:14 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.jdesktop.swingx.painter.effects; import org.jdesktop.swingx.editors.EnumPropertyEditor; import org.jdesktop.swingx.editors.Paint2PropertyEditor; import org.jdesktop.swingx.painter.AbstractPainterBeanInfo; /** * * @author joshy */ public class NeonBorderEffectBeanInfo extends AbstractPainterBeanInfo { /** Creates a new instance of NeonBorderEffectBeanInfo */ public NeonBorderEffectBeanInfo() { super(NeonBorderEffect.class); } protected void initialize() { super.initialize(); setPropertyEditor(Paint2PropertyEditor.class, "edgeColor", "centerColor", "brushColor"); //setPropertyEditor(InsetsPropertyEditor.class,"insets"); setPropertyEditor(BorderPositionPropertyEditor.class,"borderPosition"); } public static final class BorderPositionPropertyEditor extends EnumPropertyEditor { public BorderPositionPropertyEditor() { super(NeonBorderEffect.BorderPosition.class); } } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/painter/effects/AbstractPathEffectBeanInfo.java0000644000175000017500000000140711210401722031536 0ustar tonytony/* * ShapeEffectBeanInfo.java * * Created on August 23, 2006, 4:54 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.jdesktop.swingx.painter.effects; import org.jdesktop.swingx.BeanInfoSupport; import org.jdesktop.swingx.editors.Paint2PropertyEditor; import org.jdesktop.swingx.painter.effects.*; /** * * @author joshy */ public class AbstractPathEffectBeanInfo extends BeanInfoSupport { /** Creates a new instance of ShapeEffectBeanInfo */ public AbstractPathEffectBeanInfo() { super(AbstractAreaEffect.class); } protected void initialize() { setHidden(true, "class"); setPropertyEditor(Paint2PropertyEditor.class, "brushColor"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/painter/AbstractLayoutPainterBeanInfo.java0000644000175000017500000000231011210401722030700 0ustar tonytonypackage org.jdesktop.swingx.painter; import org.jdesktop.swingx.BeanInfoSupport; import org.jdesktop.swingx.editors.EnumPropertyEditor; /** * BeanInfo of AbstractLayoutPainter. * * @author Jan Stola */ public class AbstractLayoutPainterBeanInfo extends BeanInfoSupport { public AbstractLayoutPainterBeanInfo() { super(AbstractLayoutPainter.class); } public AbstractLayoutPainterBeanInfo(Class clazz) { super(clazz); } protected void initialize() { setPropertyEditor(HorizontalAlignmentPropertyEditor.class, "horizontalAlignment"); setPropertyEditor(VerticalAlignmentPropertyEditor.class, "verticalAlignment"); } public static final class HorizontalAlignmentPropertyEditor extends EnumPropertyEditor { public HorizontalAlignmentPropertyEditor() { super(AbstractLayoutPainter.HorizontalAlignment.class); } } public static final class VerticalAlignmentPropertyEditor extends EnumPropertyEditor { public VerticalAlignmentPropertyEditor() { super(AbstractLayoutPainter.VerticalAlignment.class); } } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/painter/ImagePainterBeanInfo.java0000644000175000017500000000201411210401722026762 0ustar tonytonypackage org.jdesktop.swingx.painter; import org.jdesktop.swingx.BeanInfoSupport; import org.jdesktop.swingx.editors.EnumPropertyEditor; import org.jdesktop.swingx.editors.ImageEditor; import org.jdesktop.swingx.editors.ImageURLEditor; /** * BeanInfo of ImagePainter. * * @author joshy, Jan Stola */ public class ImagePainterBeanInfo extends BeanInfoSupport { /** Creates a new instance of ImagePainterBeanInfo */ public ImagePainterBeanInfo() { super(ImagePainter.class); } protected void initialize() { setPropertyEditor(ImageEditor.class,"image"); setPropertyEditor(ImageURLEditor.class,"imageString"); setPropertyEditor(ScaleTypePropertyEditor.class, "scaleType"); setPreferred(true, "image", "imageString", "scaleType", "scaleToFit"); } public static final class ScaleTypePropertyEditor extends EnumPropertyEditor { public ScaleTypePropertyEditor() { super(ImagePainter.ScaleType.class); } } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/painter/TextPainterBeanInfo.java0000644000175000017500000000067211210401722026674 0ustar tonytonypackage org.jdesktop.swingx.painter; import org.jdesktop.swingx.BeanInfoSupport; /** * BeanInfo of TextPainter. * * @author joshy, Jan Stola */ public class TextPainterBeanInfo extends BeanInfoSupport { /** Creates a new instance of TextPainterBeanInfo */ public TextPainterBeanInfo() { super(TextPainter.class); } protected void initialize() { setPreferred(true, "font", "text"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/painter/GlossPainterBeanInfo.java0000644000175000017500000000154511210401722027037 0ustar tonytonypackage org.jdesktop.swingx.painter; import org.jdesktop.swingx.BeanInfoSupport; import org.jdesktop.swingx.editors.EnumPropertyEditor; import org.jdesktop.swingx.editors.Paint2PropertyEditor; /** * BeanInfo of GlossPainter. * * @author joshy */ public class GlossPainterBeanInfo extends BeanInfoSupport { /** Creates a new instance of GlossPainterBeanInfo */ public GlossPainterBeanInfo() { super(GlossPainter.class); } protected void initialize() { setPropertyEditor(Paint2PropertyEditor.class,"paint"); setPropertyEditor(GlossPositionPropertyEditor.class, "position"); } public static final class GlossPositionPropertyEditor extends EnumPropertyEditor { public GlossPositionPropertyEditor() { super(GlossPainter.GlossPosition.class); } } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/painter/PinstripePainterBeanInfo.java0000644000175000017500000000110711210401722027717 0ustar tonytonypackage org.jdesktop.swingx.painter; import org.jdesktop.swingx.BeanInfoSupport; import org.jdesktop.swingx.editors.Paint2PropertyEditor; /** * BeanInfo of PinstripePainter. * * @author Richard */ public class PinstripePainterBeanInfo extends BeanInfoSupport { /** Creates a new instance of PinstripePainterBeanInfo */ public PinstripePainterBeanInfo() { super(PinstripePainter.class); } protected void initialize() { setPreferred(true, "angle", "spacing", "paint"); setPropertyEditor(Paint2PropertyEditor.class, "paint"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXImageViewBeanInfo.java0000644000175000017500000000115011210401722025072 0ustar tonytony/* * JXImageViewBeanInfo.java * * Created on May 3, 2007, 5:20:50 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.jdesktop.swingx; /** * * @author joshy */ public class JXImageViewBeanInfo extends BeanInfoSupport{ public JXImageViewBeanInfo() { super(JXImageView.class); } protected void initialize() { setPreferred(true, "icon"); setPreferred(true, "dragEnabled"); setPreferred(true, "imageString"); setPreferred(true, "imageURL"); setPreferred(true, "image"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/HorizontalLayoutBeanInfo.java0000644000175000017500000000052711210401722026311 0ustar tonytonypackage org.jdesktop.swingx; /** * BeanInfo class for HorizontalLayout. * * @author Jan Stola */ public class HorizontalLayoutBeanInfo extends BeanInfoSupport { public HorizontalLayoutBeanInfo() { super(HorizontalLayout.class); } protected void initialize() { setHidden(true, "class"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXTitledPanelBeanInfo.java0000644000175000017500000000122311210401722025423 0ustar tonytonypackage org.jdesktop.swingx; import java.beans.BeanDescriptor; /** * BeanInfo class for JXTitledPanel. * * @author Richard, Jan Stola */ public class JXTitledPanelBeanInfo extends BeanInfoSupport { public JXTitledPanelBeanInfo() { super(JXTitledPanel.class); } protected void initialize() { BeanDescriptor bd = getBeanDescriptor(); bd.setValue("containerDelegate", "getContentContainer"); setPreferred(true, "title", "titleFont", "titleForeground", "titlePainter"); setPreferred(true, "leftDecoration", "rightDecoration"); setPreferred(false, "alpha", "border", "inheritAlpha"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXHyperlinkBeanInfo.java0000644000175000017500000000252511210401722025171 0ustar tonytony/* * $Id: JXHyperlinkBeanInfo.java,v 1.4 2007/12/08 15:35:05 stolis Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; /** * BeanInfo class for JXHyperlink. * * @author rbair, Jan Stola */ public class JXHyperlinkBeanInfo extends BeanInfoSupport { public JXHyperlinkBeanInfo() { super(JXHyperlink.class); } protected void initialize() { setPreferred(true, "clickedColor", "unclickedColor"); setPreferred(false, "background", "foreground", "border"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXEditorPaneBeanInfo.java0000644000175000017500000000225011210401722025251 0ustar tonytony/* * $Id: JXEditorPaneBeanInfo.java,v 1.3 2006/03/16 22:53:54 rbair Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; /** * * @author rbair */ public class JXEditorPaneBeanInfo extends BeanInfoSupport { public JXEditorPaneBeanInfo() { super(JXEditorPane.class); } protected void initialize() { } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXCollapsiblePaneBeanInfo.java0000644000175000017500000000415111210401724026260 0ustar tonytony/* * $Id: JXCollapsiblePaneBeanInfo.java,v 1.6 2008/07/31 01:20:23 kschaefe Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.beans.BeanDescriptor; import org.jdesktop.swingx.editors.EnumPropertyEditor; /** * BeanInfo class for JXCollapsiblePane. * * @author Jan Stola */ public class JXCollapsiblePaneBeanInfo extends BeanInfoSupport { /** Constructor for the JXCollapsiblePaneBeanInfo object */ public JXCollapsiblePaneBeanInfo() { super(JXCollapsiblePane.class); } protected void initialize() { BeanDescriptor bd = getBeanDescriptor(); bd.setName("JXCollapsiblePane"); bd.setShortDescription("A pane which hides its content with an animation."); bd.setValue("isContainer", Boolean.TRUE); bd.setValue("containerDelegate", "getContentPane"); setPreferred(true, "animated", "collapsed", "orientation", "direction"); setBound(true, "animated", "collapsed", "orientation", "direction"); setPropertyEditor(DirectionPropertyEditor.class, "direction"); } public static final class DirectionPropertyEditor extends EnumPropertyEditor { public DirectionPropertyEditor() { super(JXCollapsiblePane.Direction.class); } } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXListBeanInfo.java0000644000175000017500000000250311210401722024133 0ustar tonytony/* * $Id: JXListBeanInfo.java,v 1.5 2008/02/18 13:28:23 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; /** * * @author rbair */ public class JXListBeanInfo extends BeanInfoSupport { /** Creates a new instance of JXListBeanInfo */ public JXListBeanInfo() { super(JXList.class); } protected void initialize() { setPreferred(true, "highlighters"); // setPropertyEditor(HighlighterPropertyEditor.class, "highlighters"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXGraphBeanInfo.java0000644000175000017500000000434411210401722024266 0ustar tonytony/* * $Id: JXGraphBeanInfo.java,v 1.2 2006/03/16 22:53:55 rbair Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import org.jdesktop.swingx.editors.Point2DPropertyEditor; import org.jdesktop.swingx.editors.Rectangle2DPropertyEditor; /** * Bean info for {@link org.jdesktop.swingx.JXGraph} component. * * @author Romain Guy */ public class JXGraphBeanInfo extends BeanInfoSupport { public JXGraphBeanInfo() { super(JXGraph.class); } protected void initialize() { setCategory("Graph View", "majorX", "majorY", "minorCountX", "minorCountY", "origin", "view"); setCategory("Graph Appearance", "axisColor", "axisPainted", "backgroundPainted", "gridPainted", "majorGridColor", "minorGridColor", "textPainted"); setCategory("Graph Input", "inputEnabled"); setPropertyEditor(Point2DPropertyEditor.class, "origin"); setPropertyEditor(Rectangle2DPropertyEditor.class, "view"); setDisplayName("vertical lines spacing", "majorX"); setDisplayName("horizontal lines spacing", "majorY"); setDisplayName("sub-vertical lines count", "minorCountX"); setDisplayName("sub-horizontal lines count", "minorCountY"); setDisplayName("major grid lines color", "majorGridColor"); setDisplayName("minor grid lines color", "minorGridColor"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXTreeTableBeanInfo.java0000644000175000017500000000224411210401722025071 0ustar tonytony/* * $Id: JXTreeTableBeanInfo.java,v 1.3 2006/03/16 22:53:55 rbair Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; /** * * @author rbair */ public class JXTreeTableBeanInfo extends BeanInfoSupport { public JXTreeTableBeanInfo() { super(JXTreeTable.class); } protected void initialize() { } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXPanelBeanInfo.java0000644000175000017500000000275211210401722024265 0ustar tonytony/* * $Id: JXPanelBeanInfo.java,v 1.6 2007/12/08 12:47:23 stolis Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import org.jdesktop.swingx.editors.PainterPropertyEditor; /** * BeanInfo class for JXPanel. * * @author rbair, Jan Stola */ public class JXPanelBeanInfo extends BeanInfoSupport { public JXPanelBeanInfo() { super(JXPanel.class); } protected void initialize() { setPreferred(true, "opaque", "alpha", "inheritAlpha", "backgroundPainter"); setPreferred(false, "foreground"); setExpert(false, "opaque"); setPropertyEditor(PainterPropertyEditor.class, "backgroundPainter"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/border/0000755000175000017500000000000011210401732021767 5ustar tonytonyswingx-1.0-src/src/beaninfo/org/jdesktop/swingx/border/DropShadowBorderBeanInfo.java0000644000175000017500000000130511210401722027442 0ustar tonytonypackage org.jdesktop.swingx.border; import org.jdesktop.swingx.BeanInfoSupport; /** * BeanInfo class for DropShadowBorder. * * @author Jan Stola */ public class DropShadowBorderBeanInfo extends BeanInfoSupport { public DropShadowBorderBeanInfo() { super(DropShadowBorder.class); } protected void initialize() { setHidden(true, "class"); String iconName = "/org/jdesktop/swingx/resources/DropShadowBorder"; String smallIcon = iconName + "16.png"; setSmallColorIconName(smallIcon); setSmallMonoIconName(smallIcon); String icon = iconName + "32.png"; setMonoIconName(icon); setColorIconName(icon); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/border/IconBorderBeanInfo.java0000644000175000017500000000161511210401722026264 0ustar tonytonypackage org.jdesktop.swingx.border; import javax.swing.SwingConstants; import org.jdesktop.swingx.BeanInfoSupport; import org.jdesktop.swingx.EnumerationValue; /** * BeanInfo class for IconBorder. * * @author Jan Stola */ public class IconBorderBeanInfo extends BeanInfoSupport { public IconBorderBeanInfo() { super(IconBorder.class); } protected void initialize() { setHidden(true, "class", "borderOpaque"); setEnumerationValues(new EnumerationValue[] { new EnumerationValue("Leading", SwingConstants.LEADING, "SwingConstants.LEADING"), new EnumerationValue("Trailing", SwingConstants.TRAILING, "SwingConstants.TRAILING"), new EnumerationValue("East", SwingConstants.EAST, "SwingConstants.EAST"), new EnumerationValue("West", SwingConstants.WEST, "SwingConstants.WEST") }, "iconPosition"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXDatePickerBeanInfo.java0000644000175000017500000000302711210401722025235 0ustar tonytony/* * $Id: JXDatePickerBeanInfo.java,v 1.5 2008/09/04 10:27:06 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.beans.BeanDescriptor; /** * BeanInfo class for JXDatePicker. * * @author rbair, Jan Stola */ public class JXDatePickerBeanInfo extends BeanInfoSupport { /** Creates a new instance of JXListBeanInfo */ public JXDatePickerBeanInfo() { super(JXDatePicker.class); } protected void initialize() { BeanDescriptor bd = getBeanDescriptor(); bd.setValue("isContainer", Boolean.FALSE); setPreferred(true, "date", "formats"); setPreferred(false, "background", "border", "foreground", "toolTipText"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/BeanInfoSupport.java0000644000175000017500000004526611210401722024447 0ustar tonytony/* * $Id: BeanInfoSupport.java,v 1.13 2009/02/24 19:28:06 kschaefe Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.Image; import java.beans.BeanDescriptor; import java.beans.BeanInfo; import java.beans.EventSetDescriptor; import java.beans.Introspector; import java.beans.MethodDescriptor; import java.beans.PropertyDescriptor; import java.beans.SimpleBeanInfo; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; /** * Useful baseclass for BeanInfos. With this class, normal introspection occurs * and then you are given the opportunity to reconfigure portions of the * bean info in the initialize method. * * @author rbair, Jan Stola */ public abstract class BeanInfoSupport extends SimpleBeanInfo { private static Logger LOG = Logger.getLogger(BeanInfoSupport.class.getName()); /** * Indicates whether I am introspecting state for the give class. This * helps prevent infinite loops */ private static Map, Boolean> introspectingState = new HashMap, Boolean>(); /** * The class of the bean that this BeanInfoSupport is for */ private Class beanClass; /** * @see BeanInfo */ private int defaultPropertyIndex = -1; /** * @see BeanInfo */ private int defaultEventIndex = -1; /** * The 16x16 color icon */ private Image iconColor16 = null; /** * The 32x32 color icon */ private Image iconColor32 = null; /** * The 16x16 monochrome icon */ private Image iconMono16 = null; /** * The 32x32 monochrome icon */ private Image iconMono32 = null; /** * A reference to the icon. This String must be of a form that * ImageIO can use to locate and load the icon image */ private String iconNameC16 = null; /** * A reference to the icon. This String must be of a form that * ImageIO can use to locate and load the icon image */ private String iconNameC32 = null; /** * A reference to the icon. This String must be of a form that * ImageIO can use to locate and load the icon image */ private String iconNameM16 = null; /** * A reference to the icon. This String must be of a form that * ImageIO can use to locate and load the icon image */ private String iconNameM32 = null; private BeanDescriptor beanDescriptor; private Map properties = new TreeMap(); private Map events = new TreeMap(); private Map methods = new TreeMap(); /** * Creates a new instance of BeanInfoSupport. * * @param beanClass class of the bean. */ public BeanInfoSupport(Class beanClass) { this.beanClass = beanClass; if (!isIntrospecting()) { introspectingState.put(beanClass, Boolean.TRUE); try { Class superClass = beanClass.getSuperclass(); while (superClass != null) { Introspector.flushFromCaches(superClass); superClass = superClass.getSuperclass(); } BeanInfo info = Introspector.getBeanInfo(beanClass); beanDescriptor = info.getBeanDescriptor(); if (beanDescriptor != null) { Class customizerClass = getCustomizerClass(); beanDescriptor = new BeanDescriptor(beanDescriptor.getBeanClass(), customizerClass == null ? beanDescriptor.getCustomizerClass() : customizerClass); } else { beanDescriptor = new BeanDescriptor(beanClass, getCustomizerClass()); } for (PropertyDescriptor pd : info.getPropertyDescriptors()) { properties.put(pd.getName(), pd); } for (EventSetDescriptor esd : info.getEventSetDescriptors()) { events.put(esd.getName(), esd); } for (MethodDescriptor md : info.getMethodDescriptors()) { methods.put(md.getName(), md); } defaultPropertyIndex = info.getDefaultPropertyIndex(); defaultEventIndex = info.getDefaultEventIndex(); iconColor16 = loadStandardImage(info, BeanInfo.ICON_COLOR_16x16); iconColor32 = loadStandardImage(info, BeanInfo.ICON_COLOR_32x32); iconMono16 = loadStandardImage(info, BeanInfo.ICON_MONO_16x16); iconMono32 = loadStandardImage(info, BeanInfo.ICON_MONO_32x32); } catch (Exception e) { e.printStackTrace(); } introspectingState.put(beanClass, Boolean.FALSE); initialize(); } } private boolean isIntrospecting() { Boolean b = introspectingState.get(beanClass); return b == null ? false : b.booleanValue(); } /** * attempts to load a png icon from the * resource directory beneath beaninfo, named like: * JXTaskPaneContainer16.png * JXTaskPaneContainer16-mono.png * JXTaskPaneContainer32.png * JXTaskPaneContainer32-mono.png * * if any of the icons is missing, an attempt is made to * get an icon via introspection. If that fails, the icon * will be set to placeholder16.png or one of the derivitives */ private Image loadStandardImage(BeanInfo info, int size) { String s = ""; switch (size) { case BeanInfo.ICON_COLOR_16x16: s = "16"; break; case BeanInfo.ICON_COLOR_32x32: s = "32"; break; case BeanInfo.ICON_MONO_16x16: s = "16-mono"; break; case BeanInfo.ICON_MONO_32x32: s = "32-mono"; break; } String iconName = beanClass.getSimpleName() + s + ".png"; Image image = null; try { image = loadImage("resources/" + iconName); } catch (Exception e) { LOG.info("No icon named " + iconName + " was found"); } return image; } @Override public Image loadImage(final String resourceName) { URL url = getClass().getResource(resourceName); return (url == null) ? null : new ImageIcon(url).getImage(); } /** * Called by the constructor during the proper time so that subclasses * can override the settings/values for the various beaninfo properties. * For example, you could call setDisplayName("Foo Name", "foo") to change * the foo properties display name */ protected abstract void initialize(); /** * Override this method if you want to return a custom customizer class * for the bean * * @return null. */ protected Class getCustomizerClass() { return null; } //------------------------------------ Methods for mutating the BeanInfo /** * Specify the name/url/path to the small 16x16 color icon * * @param name name of the icon. */ protected void setSmallColorIconName(String name) { iconNameC16 = name; } /** * Specify the name/url/path to the 32x32 color icon * * @param name name of the icon. */ protected void setColorIconName(String name) { iconNameC32 = name; } /** * Specify the name/url/path to the small 16x16 monochrome icon * * @param name name of the icon. */ protected void setSmallMonoIconName(String name) { iconNameM16 = name; } /** * Specify the name/url/path to the 32x32 monochrome icon * * @param name name of the icon. */ protected void setMonoIconName(String name) { iconNameM32 = name; } /** * Changes the display name of the given named property. Property names * are always listed last to allow for varargs * * @param displayName display name of the property. * @param propertyName name of the property. */ protected void setDisplayName(String displayName, String propertyName) { PropertyDescriptor pd = properties.get(propertyName); if (pd != null) { pd.setDisplayName(displayName); } else { LOG.log(Level.WARNING, "Failed to set display name for property '" + propertyName + "'. No such property was found"); } } /** * Sets the given named properties to be "hidden". * * @param hidden determines whether the properties should be marked as hidden or not. * @param propertyNames name of properties. * @see PropertyDescriptor */ protected void setHidden(boolean hidden, String... propertyNames) { for (String propertyName : propertyNames) { PropertyDescriptor pd = properties.get(propertyName); if (pd != null) { pd.setHidden(hidden); } else { LOG.log(Level.WARNING, "Failed to set hidden attribute for property '" + propertyName + "'. No such property was found"); } } } protected void setExpert(boolean expert, String... propertyNames) { for (String propertyName : propertyNames) { PropertyDescriptor pd = properties.get(propertyName); if (pd != null) { pd.setExpert(expert); } else { LOG.log(Level.WARNING, "Failed to set expert attribute for property '" + propertyName + "'. No such property was found"); } } } protected void setPreferred(boolean preferred, String... propertyNames) { for (String propertyName : propertyNames) { PropertyDescriptor pd = properties.get(propertyName); if (pd != null) { pd.setPreferred(preferred); } else { LOG.log(Level.WARNING, "Failed to set preferred attribute for property '" + propertyName + "'. No such property was found"); } } } protected void setBound(boolean bound, String... propertyNames) { for (String propertyName : propertyNames) { PropertyDescriptor pd = properties.get(propertyName); if (pd != null) { pd.setBound(bound); } else { LOG.log(Level.WARNING, "Failed to set bound attribute for property '" + propertyName + "'. No such property was found"); } } } protected void setConstrained(boolean constrained, String... propertyNames) { for (String propertyName : propertyNames) { PropertyDescriptor pd = properties.get(propertyName); if (pd != null) { pd.setConstrained(constrained); } else { LOG.log(Level.WARNING, "Failed to set constrained attribute for property '" + propertyName + "'. No such property was found"); } } } protected void setCategory(String categoryName, String... propertyNames) { for (String propertyName : propertyNames) { PropertyDescriptor pd = properties.get(propertyName); if (pd != null) { pd.setValue("category", categoryName); } else { LOG.log(Level.WARNING, "Failed to set category for property '" + propertyName + "'. No such property was found"); } } } protected void setPropertyEditor(Class editorClass, String... propertyNames) { for (String propertyName : propertyNames) { PropertyDescriptor pd = properties.get(propertyName); if (pd != null) { pd.setPropertyEditorClass(editorClass); } else { LOG.log(Level.WARNING, "Failed to set property editor for property '" + propertyName + "'. No such property was found"); } } } protected void setEnumerationValues(EnumerationValue[] values, String... propertyNames) { if (values == null) { return; } Object[] enumValues = new Object[values.length * 3]; int index = 0; for (EnumerationValue ev : values) { enumValues[index++] = ev.getName(); enumValues[index++] = ev.getValue(); enumValues[index++] = ev.getJavaInitializationString(); } for (String propertyName : propertyNames) { PropertyDescriptor pd = properties.get(propertyName); if (pd != null) { pd.setValue("enumerationValues", enumValues); } else { LOG.log(Level.WARNING, "Failed to set enumeration values for property '" + propertyName + "'. No such property was found"); } } } //----------------------------------------------------- BeanInfo methods /** * Gets the bean's BeanDescriptors. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ @Override public BeanDescriptor getBeanDescriptor() { return isIntrospecting() ? null : beanDescriptor; } /** * Gets the bean's PropertyDescriptors. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. *

* If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ @Override public PropertyDescriptor[] getPropertyDescriptors() { return isIntrospecting() ? null : properties.values().toArray(new PropertyDescriptor[0]); } /** * Gets the bean's EventSetDescriptors. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ @Override public EventSetDescriptor[] getEventSetDescriptors() { return isIntrospecting() ? null : events.values().toArray(new EventSetDescriptor[0]); } /** * Gets the bean's MethodDescriptors. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ @Override public MethodDescriptor[] getMethodDescriptors() { return isIntrospecting() ? null : methods.values().toArray(new MethodDescriptor[0]); } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. *

Returns -1 if there is no default property. */ @Override public int getDefaultPropertyIndex() { return isIntrospecting() ? -1 : defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. *

Returns -1 if there is no default event. */ @Override public int getDefaultEventIndex() { return isIntrospecting() ? -1 : defaultEventIndex; } /** * This method returns an image object that can be used to * represent the bean in toolboxes, toolbars, etc. Icon images * will typically be GIFs, but may in future include other formats. *

* Beans aren't required to provide icons and may return null from * this method. *

* There are four possible flavors of icons (16x16 color, * 32x32 color, 16x16 mono, 32x32 mono). If a bean choses to only * support a single icon we recommend supporting 16x16 color. *

* We recommend that icons have a "transparent" background * so they can be rendered onto an existing background. * * @param iconKind The kind of icon requested. This should be * one of the constant values ICON_COLOR_16x16, ICON_COLOR_32x32, * ICON_MONO_16x16, or ICON_MONO_32x32. * @return An image object representing the requested icon. May * return null if no suitable icon is available. */ @Override public java.awt.Image getIcon(int iconKind) { switch ( iconKind ) { case ICON_COLOR_16x16: return getImage(iconNameC16, iconColor16); case ICON_COLOR_32x32: return getImage(iconNameC32, iconColor32); case ICON_MONO_16x16: return getImage(iconNameM16, iconMono16); case ICON_MONO_32x32: return getImage(iconNameM32, iconMono32); default: return null; } } private java.awt.Image getImage(String name, java.awt.Image img) { if (img == null) { if (name != null) { img = loadImage(name); } } return img; } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXLabelBeanInfo.java0000644000175000017500000000114311210401722024236 0ustar tonytonypackage org.jdesktop.swingx; /** * BeanInfo class for JXLabel. * * @author Jan Stola */ public class JXLabelBeanInfo extends BeanInfoSupport { public JXLabelBeanInfo() { super(JXLabel.class); } protected void initialize() { String iconName = "resources/" + JXLabel.class.getSimpleName(); setSmallMonoIconName(iconName + "16.png"); setMonoIconName(iconName + "32.png"); setPreferred(true, "foregroundPainter", "backgroundPainter"); setPreferred(true, "lineWrap", "maxLineSpan"); setPreferred(true, "textRotation"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXFindPanelBeanInfo.java0000644000175000017500000000064411210401722025064 0ustar tonytonypackage org.jdesktop.swingx; import java.beans.BeanDescriptor; /** * BeanInfo class for JXFindPanel. * * @author Jan Stola */ public class JXFindPanelBeanInfo extends BeanInfoSupport { public JXFindPanelBeanInfo() { super(JXFindPanel.class); } protected void initialize() { BeanDescriptor bd = getBeanDescriptor(); bd.setValue("isContainer", Boolean.FALSE); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXSearchPanelBeanInfo.java0000644000175000017500000000065411210401722025412 0ustar tonytonypackage org.jdesktop.swingx; import java.beans.BeanDescriptor; /** * BeanInfo class for JXSearchPanel. * * @author Jan Stola */ public class JXSearchPanelBeanInfo extends BeanInfoSupport { public JXSearchPanelBeanInfo() { super(JXSearchPanel.class); } protected void initialize() { BeanDescriptor bd = getBeanDescriptor(); bd.setValue("isContainer", Boolean.FALSE); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/0000755000175000017500000000000011210401736022167 5ustar tonytonyswingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/ImageEditor.java0000644000175000017500000000341411210401722025220 0ustar tonytony/* * ImageEditor.java * * Created on July 21, 2006, 1:35 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.jdesktop.swingx.editors; import java.awt.Component; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyEditorSupport; import javax.swing.JButton; /** * * @author joshy */ public class ImageEditor extends PropertyEditorSupport { Image image = null; ImagePicker picker = new ImagePicker(); /** Creates a new instance of ImageEditor */ public ImageEditor() { picker.imageView.addPropertyChangeListener("image",new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent propertyChangeEvent) { image = picker.imageView.getImage(); firePropertyChange(); } }); } public Image getValue() { return image; } public void setValue(Object object) { image = (Image)object; super.setValue(image); picker.imageView.setImage(image); } public void setAsText(String text) throws IllegalArgumentException { // do nothing right now } public String getAsText() { return "an Image"; } public void paintValue(Graphics graphics, Rectangle r) { graphics.drawImage(image, (int)r.getX(), (int)r.getY(), (int)r.getWidth(), (int)r.getHeight(), null); } public boolean isPaintable() { return true; } public boolean supportsCustomEditor() { return true; } public Component getCustomEditor() { return picker; } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/Rectangle2DPropertyEditor.java0000644000175000017500000000640511210401722030040 0ustar tonytony/* * $Id: Rectangle2DPropertyEditor.java,v 1.2 2007/03/14 19:46:17 joshy Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.editors; import java.awt.geom.Rectangle2D; import java.beans.PropertyEditorSupport; /** * * @author rbair */ public class Rectangle2DPropertyEditor extends PropertyEditorSupport { /** Creates a new instance of Rectangle2DPropertyEditor */ public Rectangle2DPropertyEditor() { } public Rectangle2D getValue() { return (Rectangle2D.Double)super.getValue(); } public String getJavaInitializationString() { Rectangle2D rect = getValue(); return rect == null ? "null" : "new java.awt.geom.Rectangle2D.Double(" + rect.getX() + ", " + rect.getY() + ", " + rect.getWidth() + ", " + rect.getHeight() + ")"; } public void setAsText(String text) throws IllegalArgumentException { String originalParam = text; try { Rectangle2D val = (Rectangle2D)PropertyEditorUtil.createValueFromString( text, 4, Rectangle2D.Double.class, double.class); setValue(val); } catch (Exception e) { throw new IllegalArgumentException("The input value " + originalParam + " is not formatted correctly. Please " + "try something of the form [x,y,w,h] or [x , y , w , h] or [x y w h]", e); } } public String getAsText() { Rectangle2D rect = getValue(); return rect == null ? "[]" : "[" + rect.getX() + ", " + rect.getY() + ", " + rect.getWidth() + ", " + rect.getHeight() + "]"; } public static void main(String... args) { test("[1.5,1.2,10,35]"); test("1.5,1.2,10,35]"); test("[1.5,1.2,10,35"); test("[ 1.5 , 1.2 ,10,35]"); test(" 1.5 , 1.2 ,10,35]"); test("[ 1.5 , 1.2,10,35"); test("1.5,1.2,10,35"); test(" 1.5 , 1.2 10 35"); test("1.5 1.2, 10 35"); test(""); test("null"); test("[]"); test("[ ]"); test("[1.5 1.2 10 35]"); } private static void test(String input) { System.out.print("Input '" + input + "'"); try { Rectangle2DPropertyEditor ed = new Rectangle2DPropertyEditor(); ed.setAsText(input); Rectangle2D rect = ed.getValue(); System.out.println(" succeeded: " + rect); } catch (Exception e) { System.out.println(" failed: " + e.getMessage()); } } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/ImagePicker.java0000644000175000017500000000335711210401722025215 0ustar tonytony/* * ImagePicker.java * * Created on July 21, 2006, 1:42 AM */ package org.jdesktop.swingx.editors; /** * * @author joshy */ public class ImagePicker extends javax.swing.JPanel { /** Creates new form ImagePicker */ public ImagePicker() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // //GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; imageView = new org.jdesktop.swingx.JXImageView(); jButton1 = new javax.swing.JButton(); setLayout(new java.awt.GridBagLayout()); imageView.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 10.0; gridBagConstraints.weighty = 10.0; add(imageView, gridBagConstraints); jButton1.setAction(imageView.getOpenAction()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST; add(jButton1, gridBagConstraints); }// //GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables public org.jdesktop.swingx.JXImageView imageView; private javax.swing.JButton jButton1; // End of variables declaration//GEN-END:variables } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/deleteHighlighter.gif0000644000175000017500000000017511210401722026275 0ustar tonytonyGIF89a̙fff333!,Bhn$>d5fB02m7\7@̷C u@0sROU8vU$;swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/InsetsPropertyEditor.java0000644000175000017500000000251211210401722027206 0ustar tonytony/* * InsetsPropertyEditor.java * * Created on July 20, 2006, 12:16 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.jdesktop.swingx.editors; import java.awt.Insets; import java.beans.PropertyEditorSupport; /** * * @author joshy */ public class InsetsPropertyEditor extends PropertyEditorSupport { /** Creates a new instance of InsetsPropertyEditor */ public InsetsPropertyEditor() { } public Insets getValue() { return (Insets)super.getValue(); } public void setAsText(String text) { String originalParam = text; try { Insets val = (Insets)PropertyEditorUtil.createValueFromString( text, 4, Insets.class, int.class); setValue(val); } catch (Exception e) { throw new IllegalArgumentException("The input value " + originalParam + " is not formatted correctly. Please " + "try something of the form [top,left,bottom,right] or [top , left , bottom , right] or [top left bottom right]", e); } } public String getAsText() { Insets val = getValue(); return val == null ? "[]" : "[" + val.top + ", " + val.left + ", " + val.bottom + ", " + val.right + "]"; } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/PainterUtil.java0000644000175000017500000003564311210401722025300 0ustar tonytony/* * PainterUtil.java * * Created on July 20, 2006, 1:18 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.jdesktop.swingx.editors; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.RenderingHints; import java.awt.geom.AffineTransform; import java.awt.geom.Arc2D; import java.awt.geom.Area; import java.awt.geom.CubicCurve2D; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.QuadCurve2D; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.beans.BeanInfo; import java.beans.DefaultPersistenceDelegate; import java.beans.Encoder; import java.beans.ExceptionListener; import java.beans.Expression; import java.beans.Introspector; import java.beans.PersistenceDelegate; import java.beans.PropertyDescriptor; import java.beans.Statement; import java.beans.XMLDecoder; import java.beans.XMLEncoder; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.net.MalformedURLException; import java.net.URL; import javax.imageio.ImageIO; import javax.swing.JComponent; import org.apache.batik.ext.awt.LinearGradientPaint; import org.apache.batik.ext.awt.RadialGradientPaint; import org.jdesktop.swingx.JXButton; import org.jdesktop.swingx.JXLabel; import org.jdesktop.swingx.JXPanel; import org.jdesktop.swingx.painter.AbstractPainter; import org.jdesktop.swingx.painter.CompoundPainter; import org.jdesktop.swingx.painter.ImagePainter; import org.jdesktop.swingx.painter.Painter; import org.jdesktop.swingx.editors.PainterPropertyEditor.*; import org.jdesktop.swingx.painter.AbstractLayoutPainter; import org.jdesktop.swingx.painter.RectanglePainter; /** * * @author joshy */ public class PainterUtil { /** Creates a new instance of PainterUtil */ private PainterUtil() { } /* public static void main(String[] args) throws Exception { ImagePainter ip = new ImagePainter(); ip.setImageString("file:/Users/joshy/Pictures/cooltikis.jpg"); File outfile = new File("/Users/joshy/Desktop/test.xml"); outfile.createNewFile(); p("outfile = " + outfile.getAbsolutePath()); p("exists = " + outfile.exists()); savePainterToFile(ip, outfile, outfile.getParentFile().toURL()); p("---------"); ip = (ImagePainter)loadPainter(outfile); p("image = " + ip.getImage()); ip = (ImagePainter)loadPainter(outfile.toURL()); p("image = " + ip.getImage()); p("=================="); }*/ public static Painter loadPainter(File file) throws FileNotFoundException, MalformedURLException, IOException { return loadPainter(file.toURI().toURL(), file.toURI().toURL()); } private static Painter loadPainter(final URL in, URL baseURL) throws FileNotFoundException, IOException { Thread.currentThread().setContextClassLoader(PainterUtil.class.getClassLoader()); XMLDecoder dec = new XMLDecoder(in.openStream()); // p("creating a persistence owner with the base url: " + baseURL); dec.setOwner(new PersistenceOwner(baseURL)); dec.setExceptionListener(new ExceptionListener() { public void exceptionThrown(Exception ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } }); Object obj = dec.readObject(); return (Painter)obj; } public static Painter loadPainter(URL url) throws IOException { return loadPainter(url,url); } static public void savePainterToFile(Painter compoundPainter, File file) throws IOException { savePainterToFile(compoundPainter,file,file.getParentFile().toURI().toURL()); } static public void savePainterToFile(Painter compoundPainter, File file, URL baseURL) throws IOException { //System.setErr(null); // u.p("writing out to: " + file.getCanonicalPath()); setTransient(ImagePainter.class, "image"); setTransient(ImagePainter.class, "imageString"); //setTransient(CompoundPainter.class,"antialiasing"); //setTransient(AbstractPainter.class,"antialiasing"); //setTransient(AbstractPainter.class,"renderingHints"); //setPropertyDelegate(); XMLEncoder e = new XMLEncoder(new FileOutputStream(file)); e.setOwner(new PersistenceOwner(baseURL)); //p("owner = " + e.getOwner()); //e.setOwner(compoundPainter); // serialize the enums //e.setPersistenceDelegate(AbstractPainter.Antialiasing.class, new TypeSafeEnumPersistenceDelegate()); e.setPersistenceDelegate(AbstractPainter.Interpolation.class, new TypeSafeEnumPersistenceDelegate()); // e.setPersistenceDelegate(AbstractPainter.FractionalMetrics.class, new TypeSafeEnumPersistenceDelegate()); e.setPersistenceDelegate(RectanglePainter.Style.class, new TypeSafeEnumPersistenceDelegate()); e.setPersistenceDelegate(AbstractLayoutPainter.HorizontalAlignment.class, new TypeSafeEnumPersistenceDelegate()); e.setPersistenceDelegate(AbstractLayoutPainter.VerticalAlignment.class, new TypeSafeEnumPersistenceDelegate()); e.setPersistenceDelegate(AbstractPainter.class, new AbstractPainterDelegate()); e.setPersistenceDelegate(ImagePainter.class, new ImagePainterDelegate()); e.setPersistenceDelegate(RenderingHints.class, new RenderingHintsDelegate()); e.setPersistenceDelegate(GradientPaint.class, new GradientPaintDelegate()); e.setPersistenceDelegate(Arc2D.Float.class, new Arc2DDelegate()); e.setPersistenceDelegate(Arc2D.Double.class, new Arc2DDelegate()); e.setPersistenceDelegate(CubicCurve2D.Float.class, new CubicCurve2DDelegate()); e.setPersistenceDelegate(CubicCurve2D.Double.class, new CubicCurve2DDelegate()); e.setPersistenceDelegate(Ellipse2D.Float.class, new Ellipse2DDelegate()); e.setPersistenceDelegate(Ellipse2D.Double.class, new Ellipse2DDelegate()); e.setPersistenceDelegate(Line2D.Float.class, new Line2DDelegate()); e.setPersistenceDelegate(Line2D.Double.class, new Line2DDelegate()); e.setPersistenceDelegate(Point2D.Float.class, new Point2DDelegate()); e.setPersistenceDelegate(Point2D.Double.class, new Point2DDelegate()); e.setPersistenceDelegate(QuadCurve2D.Float.class, new QuadCurve2DDelegate()); e.setPersistenceDelegate(QuadCurve2D.Double.class, new QuadCurve2DDelegate()); e.setPersistenceDelegate(Rectangle2D.Float.class, new Rectangle2DDelegate()); e.setPersistenceDelegate(Rectangle2D.Double.class, new Rectangle2DDelegate()); e.setPersistenceDelegate(RoundRectangle2D.Float.class, new RoundRectangle2DDelegate()); e.setPersistenceDelegate(RoundRectangle2D.Double.class, new RoundRectangle2DDelegate()); e.setPersistenceDelegate(Area.class, new AreaDelegate()); e.setPersistenceDelegate(GeneralPath.class, new GeneralPathDelegate()); e.setPersistenceDelegate(AffineTransform.class, new AffineTransformDelegate()); e.setPersistenceDelegate(RadialGradientPaint.class, new RadialGradientPaintDelegate()); e.setPersistenceDelegate(LinearGradientPaint.class, new LinearGradientPaintDelegate()); e.setPersistenceDelegate(Insets.class, new InsetsDelegate()); e.writeObject(compoundPainter); e.close(); } //private static void setPropertyDelegate(Class clazz, String property, ) private static void setTransient(Class clazz, String property) { try { BeanInfo info = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; ++i) { PropertyDescriptor pd = propertyDescriptors[i]; if (pd.getName().equals(property)) { pd.setValue("transient", Boolean.TRUE); //u.p(pd.attributeNames()); } } } catch (Exception ex) { //u.p(ex); } } static class TypeSafeEnumPersistenceDelegate extends PersistenceDelegate { protected boolean mutatesTo( Object oldInstance, Object newInstance ) { return oldInstance == newInstance; } protected Expression instantiate( Object oldInstance, Encoder out ) { Class type = oldInstance.getClass(); if ( !Modifier.isPublic( type.getModifiers() ) ) throw new IllegalArgumentException( "Could not instantiate instance of non-public class: " + oldInstance ); for ( Field field : type.getFields() ) { int mod = field.getModifiers(); if ( Modifier.isPublic( mod ) && Modifier.isStatic( mod ) && Modifier.isFinal( mod ) && ( type == field.getDeclaringClass() ) ) { try { if ( oldInstance == field.get( null ) ) return new Expression( oldInstance, field, "get", new Object[]{null} ); } catch ( IllegalAccessException exception ) { throw new IllegalArgumentException( "Could not get value of the field: " + field, exception ); } } } throw new IllegalArgumentException( "Could not instantiate value: " + oldInstance ); } } public static final class RenderingHintsDelegate extends PersistenceDelegate { protected Expression instantiate(Object oldInstance, Encoder out) { //u.p("rh inst"); // give it a constructor w/ null as the argument return new Expression(oldInstance, oldInstance.getClass(), "new", new Object[] { null }); } protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out) { //u.p("rh init "); RenderingHints rh = (RenderingHints)oldInstance; out.writeStatement(new Statement(oldInstance, "put", new Object[] {RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON})); //u.p("done"); } } public static final class AbstractPainterDelegate extends DefaultPersistenceDelegate { protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out) { // p("ap delegate called"); super.initialize(type, oldInstance, newInstance, out); } } public static final class ImagePainterDelegate extends DefaultPersistenceDelegate { protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out) { // p("image painter delegate called"); super.initialize(type, oldInstance, newInstance, out); //p("old instance = " + oldInstance); //p("owner = " + ((XMLEncoder)out).getOwner()); PersistenceOwner owner = (PersistenceOwner)((XMLEncoder)out).getOwner(); ImagePainter ip = (ImagePainter)oldInstance; // p("need to convert string: " + ip.getImageString()); String s = owner.toXMLURL(ip.getImageString()); // p("converted to: " + s); //out.writeExpression(new Expression(oldInstance,owner,"fromXMLURL",new Object[]{ip.getImageString()})); //out.writeStatement(new Statement(owner,"fromXMLURL",new Object[]{ip.getImageString()})); //out.writeStatement(new Statement(oldInstance,"setImageString",new Object[]{ //new Expression(oldInstance,owner,"fromXMLURL",new Object[]{ip.getImageString()}) //})); out.writeStatement(new Statement(oldInstance,"setResolver",new Object[]{owner})); out.writeStatement(new Statement(oldInstance,"setImageString",new Object[]{s})); } } public static void savePainterToImage(JComponent testPanel, CompoundPainter compoundPainter, File file) throws IOException { BufferedImage img = new BufferedImage(testPanel.getWidth(),testPanel.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g = img.createGraphics(); setBGP(testPanel,compoundPainter); testPanel.paint(g); ImageIO.write(img,"png",file); } public static void setBGP(JComponent comp, Painter painter) { if(comp instanceof JXPanel) { ((JXPanel)comp).setBackgroundPainter(painter); } if(comp instanceof JXButton) { ((JXButton)comp).setBackgroundPainter(painter); } } public static void setFGP(JComponent comp, Painter painter) { if(comp instanceof JXLabel) { ((JXLabel)comp).setForegroundPainter(painter); } if(comp instanceof JXButton) { ((JXButton)comp).setForegroundPainter(painter); } } public static Painter getFGP(JComponent comp) { if(comp instanceof JXLabel) { return ((JXLabel)comp).getForegroundPainter(); } if(comp instanceof JXButton) { return ((JXButton)comp).getForegroundPainter(); } return null; } public static Painter getBGP(JComponent comp) { if(comp instanceof JXPanel) { return ((JXPanel)comp).getBackgroundPainter(); } if(comp instanceof JXButton) { return ((JXButton)comp).getBackgroundPainter(); } return null; } public static class PersistenceOwner { private URL baseURL; public PersistenceOwner(URL baseURL) { this.baseURL = baseURL; } public URL getBaseURL() { return baseURL; } public String toXMLURL(String url) { // p("========"); // p("in toXMLURL()"); // p("base url = " + baseURL); // p("url to convert = " + url); //trim off the beginning if the url is relative to the base if(url.startsWith(baseURL.toString())) { // p("it's a valid substring!!!!!!!!!!!!"); url = url.substring(baseURL.toString().length()); // p("subsstring = " + url); } // p("final url = " + url); // p("========"); return url; } public String fromXMLURL(String url) throws MalformedURLException { /*p("========"); p("in fromXMLURL()"); p("base url = " + baseURL); p("url to convert: " + url);*/ String s = new URL(baseURL,url).toString(); // p("returning: " + s); // p("========"); return s; } } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/PropertyEditorUtil.java0000644000175000017500000000431711210401722026663 0ustar tonytony/* * PropertyEditorUtil.java * * Created on August 16, 2006, 7:09 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.jdesktop.swingx.editors; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /** * * @author joshy */ public class PropertyEditorUtil { //the text could be in many different formats. All of the supported formats are as follows: //(where x and y are doubles of some form) //[x,y] //[x y] //x,y] //[x,y //[ x , y ] or any other arbitrary whitespace // x , y ] or any other arbitrary whitespace //[ x , y or any other arbitrary whitespace //x,y // x , y (or any other arbitrary whitespace) //x y // (empty space) //null //[] //[ ] //any other value throws an IllegalArgumentException public static Object createValueFromString(String text, int count, Class objectClass, Class paramClass) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { // strip all extra whitespace text = text.replaceAll("[\\[|,| |\\]]"," "); text = text.replaceAll("\\s+"," "); text = text.trim(); // u.p("text = " + text); if (text == null || text.equals("") || text.equals("null")) { return null; } // split by spaces String[] strs = text.split(" "); // u.p("split:"); // u.p(strs); // u.p("len = " + strs.length); if(strs.length != count) { return null; } Object[] params = new Object[count]; Class[] paramClasses = new Class[count]; for(int i=0; i//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; tabbedPane = new javax.swing.JTabbedPane(); colorPickerParent = new javax.swing.JPanel(); colorPicker = new javax.swing.JColorChooser(); jLabel1 = new javax.swing.JLabel(); alphaSlider = new javax.swing.JSlider(); setLayout(new java.awt.GridBagLayout()); colorPickerParent.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = 2; gridBagConstraints.weightx = 10.0; gridBagConstraints.weighty = 10.0; colorPickerParent.add(colorPicker, gridBagConstraints); jLabel1.setText("Alpha:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; colorPickerParent.add(jLabel1, gridBagConstraints); alphaSlider.setMaximum(255); alphaSlider.setValue(255); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; colorPickerParent.add(alphaSlider, gridBagConstraints); tabbedPane.addTab("Color", colorPickerParent); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 10.0; gridBagConstraints.weighty = 10.0; add(tabbedPane, gridBagConstraints); }// //GEN-END:initComponents public void setPaint(Paint paint) { if(paint == selectedPaint) { return; } Paint old = selectedPaint; selectedPaint = paint; if(paint instanceof Color) { tabbedPane.setSelectedComponent(colorPickerParent); colorPicker.setColor((Color)paint); alphaSlider.setValue(((Color)paint).getAlpha()); } if(paint instanceof MultipleGradientPaint) { tabbedPane.setSelectedComponent(gradientPicker); gradientPicker.setGradient((MultipleGradientPaint)paint); } firePropertyChange("paint", old, selectedPaint); } // return a paint suitable for display in a property sheet preview Paint getDisplayPaint(Rectangle box) { if(getPaint() instanceof MultipleGradientPaint) { return getFlatGradient(gradientPicker, box.getWidth()); } return getPaint(); } /** * Creates a flat version of the current gradient. This is a linear gradient * from 0.0 to length,0. This gradient is suitable for drawing previews of * the real gradient. * * @param length * @return a gradient Paint with values between 0.0 and length */ private MultipleGradientPaint getFlatGradient(JXGradientChooser chooser, double length) { MultipleGradientPaint gp = chooser.getGradient(); // set up the data for the gradient float[] fractions = gp.getFractions(); Color[] colors = gp.getColors(); // fill in the gradient Point2D start = new Point2D.Float(0, 0); Point2D end = new Point2D.Float((float) length, 0); MultipleGradientPaint paint = new org.apache.batik.ext.awt.LinearGradientPaint( (float) start.getX(), (float) start.getY(), (float) end.getX(), (float) end.getY(), fractions, colors); return paint; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JSlider alphaSlider; public javax.swing.JColorChooser colorPicker; private javax.swing.JPanel colorPickerParent; private javax.swing.JLabel jLabel1; private javax.swing.JTabbedPane tabbedPane; // End of variables declaration//GEN-END:variables private class ColorListener implements ChangeListener { public void stateChanged(ChangeEvent e) { lastPickerUsed = colorPicker; Paint old = selectedPaint; selectedPaint = ColorUtil.setAlpha(colorPicker.getSelectionModel().getSelectedColor(), alphaSlider.getValue()); firePropertyChange("paint", old, selectedPaint); } } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/Painter2PropertyEditor.java0000644000175000017500000000634311210401722027433 0ustar tonytony/* * Painter2PropertyEditor.java * * Created on August 2, 2006, 8:27 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.jdesktop.swingx.editors; import java.awt.Color; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyEditorSupport; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import org.jdesktop.swingx.URLPainter; import org.jdesktop.swingx.painter.MattePainter; import org.jdesktop.swingx.painter.Painter; /** * * @author joshy */ public class Painter2PropertyEditor extends PropertyEditorSupport { Painter painter = new MattePainter(Color.BLUE); JFileChooser picker; void log(String str) { //JOptionPane.showMessageDialog(picker,str); System.out.println(str); } /** Creates a new instance of Painter2PropertyEditor */ public Painter2PropertyEditor() { picker = new JFileChooser(); picker.setApproveButtonText("Load Painter"); picker.setMultiSelectionEnabled(false); picker.setSelectedFile(new File("/Users/joshy/projects/current/AB5k/src/java/ab5k/desklet/")); picker.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { try { File file = picker.getSelectedFile(); painter = new URLPainter(file); //painter = PainterUtil.loadPainter(file); firePropertyChange(); log("loaded the painter: " + painter); } catch (Throwable ex) { //System.out.println("error loading the painter: " + ex.getMessage()); //ex.printStackTrace(); StringWriter wrt = new StringWriter(); ex.printStackTrace(new PrintWriter(wrt)); JOptionPane.showMessageDialog(picker,ex.getMessage() + " " + wrt.toString());// + painter.getClass().getName()); } } }); } public Painter getValue() { return painter; } public void setValue(Object object) { log("setting: " + object); painter = (Painter)object; super.setValue(object); } public void setAsText(String text) throws IllegalArgumentException { // u.p("setting as text: " + text); log("setting as text: " + text); } public String getAsText() { if(painter instanceof URLPainter) { return ((URLPainter)painter).getURL().toString(); } if(painter != null) { return painter.getClass().getName(); } else { return "null!!"; } } public String getJavaInitializationString() { URLPainter painter = (URLPainter)getValue(); return painter == null ? "null" : "new org.jdesktop.swingx.painter.FilePainter(\""+ painter.getURL().toString()+"\")"; } public boolean supportsCustomEditor() { return true; } public Component getCustomEditor() { return picker; } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/ShapePropertyEditor.java0000644000175000017500000000276211210401722027010 0ustar tonytony/* * ShapePropertyEditor.java * * Created on August 23, 2006, 10:17 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.jdesktop.swingx.editors; import java.awt.Component; import java.awt.Rectangle; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; import java.beans.PropertyEditorSupport; /** * * @author joshy */ public class ShapePropertyEditor extends PropertyEditorSupport { ShapeChooser chooser; /** Creates a new instance of ShapePropertyEditor */ public ShapePropertyEditor() { chooser = new ShapeChooser(); chooser.shapeCombo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { if(chooser.shapeCombo.getSelectedItem().equals("Square")) { setValue(new Rectangle(0,0,100,100)); } else { setValue(new Ellipse2D.Double(0,0,100,100)); } } }); } public Shape getValue() { return (Shape)super.getValue(); } public void setValue(Object value) { super.setValue(value); } public boolean isPaintable() { return true; } public boolean supportsCustomEditor() { return true; } public Component getCustomEditor() { return chooser; } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/Paint2PropertyEditor.java0000644000175000017500000000363111210401722027101 0ustar tonytonypackage org.jdesktop.swingx.editors; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Rectangle; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyEditorSupport; /** * * @author joshy */ public class Paint2PropertyEditor extends PropertyEditorSupport { Paint paint = new Color(0,128,255); PaintPicker picker = new PaintPicker(); /** Creates a new instance of Paint2PropertyEditor */ public Paint2PropertyEditor() { picker.addPropertyChangeListener("paint",new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent propertyChangeEvent) { paint = picker.getPaint(); firePropertyChange(); } }); } public Paint getValue() { return paint; } public void setValue(Object object) { paint = (Paint)object; picker.setPaint(paint); super.setValue(object); } public String getJavaInitializationString() { Paint paint = getValue(); //TODO!!! return paint == null ? "null" : "org.jdesktop.swingx.painter.gradient.LinearGradientPainter.BLACK_STAR"; } public void setAsText(String text) throws IllegalArgumentException { // do nothing right now } public String getAsText() { return "PainterText"; } public void paintValue(Graphics g, Rectangle box) { Graphics2D g2 = (Graphics2D)g; //picker.setPaint(getValue()); g2.setPaint(picker.getDisplayPaint(box)); g2.fill(box); } public boolean isPaintable() { return true; } public boolean supportsCustomEditor() { return true; } public Component getCustomEditor() { return picker; } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/EnumPropertyEditor.java0000644000175000017500000000263411210401722026652 0ustar tonytony/* * EnumPropertyEditor.java * * Created on August 18, 2006, 10:43 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.jdesktop.swingx.editors; import java.beans.PropertyEditorSupport; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; /** * * @author joshy */ public class EnumPropertyEditor> extends PropertyEditorSupport { private Class en; private EnumSet set; /** Creates a new instance of EnumPropertyEditor */ public EnumPropertyEditor(Class en) { this.en = en; set = EnumSet.allOf(en); } public String[] getTags() { List strs = new ArrayList(); for(E e : set) { strs.add(e.toString()); } return strs.toArray(new String[0]); } public String getAsText() { return getValue().toString(); } public void setAsText(String text) throws IllegalArgumentException { // u.p("setting as text: " + text); Enum e = Enum.valueOf(en, text); setValue(e); } @Override public String getJavaInitializationString() { //org.jdesktop.stuff.Stuff.InsideEnum.VALUE; // the '$' must be converted to '.' to deal with public inner classes return new String(en.getName()+"."+getAsText()).replace("$","."); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/ImageURLEditor.java0000644000175000017500000000343711210401722025610 0ustar tonytonypackage org.jdesktop.swingx.editors; import java.awt.Component; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyEditorSupport; /** * * @author joshy */ public class ImageURLEditor extends PropertyEditorSupport { Image image = null; String imageURL = null; ImagePicker picker = new ImagePicker(); /** Creates a new instance of ImageEditor */ public ImageURLEditor() { picker.imageView.addPropertyChangeListener("image",new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent propertyChangeEvent) { image = picker.imageView.getImage(); if(picker.imageView.getImageURL() != null) { imageURL = picker.imageView.getImageURL().toString(); } firePropertyChange(); } }); } public String getValue() { return imageURL; } public void setValue(Object object) { imageURL = (String)object; super.setValue(imageURL); picker.imageView.setImage(image); } public void setAsText(String text) throws IllegalArgumentException { // do nothing right now } public String getAsText() { return imageURL; } public void paintValue(Graphics graphics, Rectangle r) { //graphics.drawImage(image, (int)r.getX(), (int)r.getY(), // (int)r.getWidth(), (int)r.getHeight(), null); } public boolean isPaintable() { return false; } public boolean supportsCustomEditor() { return true; } public Component getCustomEditor() { return picker; } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/newHighlighter24.gif0000644000175000017500000000231411210401722025767 0ustar tonytonyPNG  IHDRw=bKGD pHYs  tIME(YIDATxڵMlTU޼鴝2R>UQB@\h4n(CЅpCB5jbbܙ5TH. t!*b0BZ Bfyo޼b杹=g֚,>sq#hBW}|| h7k u!! &1 ֺ@o?0tV/ׯzS\>}wqhHM+2X4eq0C_%3F@pVb"jAg34$1BUI$a$M&hjP.&VewS@ rAw7%'XYr"YH P;rDMUi#,Hͣ B:5::ٶm ?6G`i̐h mʢ*SD9EӍ ;xZfu {!-a#@ZX]O$Zؖ6=6nX{潏ƦNLcHcitNpK;q}{6vltյw [L#I4IIaivۅm߁;,n??1Xh}k>l/*ӃT9r avߏy7!ZHX%I|5|ޭ{>hcq0g|2u"7Nrfݛf~:sțy_|spҌVShTY⨂nq:SK+7*~vlbS?4ZsChB`mY&;7RYΎLM~O|u *ֲqeJ@cCƏ<ĵ_N|nK7:"s'2qen#'}'3 dbbүV>" m? 6k;K2%S&V M\IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/PainterPropertyEditor.java0000644000175000017500000004101611210401722027345 0ustar tonytony/* * PainterPropertyEditor.java * * Created on March 21, 2006, 11:26 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.jdesktop.swingx.editors; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Insets; import java.awt.geom.AffineTransform; import java.awt.geom.Arc2D; import java.awt.geom.Area; import java.awt.geom.CubicCurve2D; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.QuadCurve2D; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.beans.DefaultPersistenceDelegate; import java.beans.Encoder; import java.beans.Expression; import java.beans.PersistenceDelegate; import java.beans.PropertyEditorSupport; import java.beans.Statement; import java.beans.XMLEncoder; import java.io.ByteArrayOutputStream; import org.apache.batik.ext.awt.LinearGradientPaint; import org.apache.batik.ext.awt.MultipleGradientPaint.ColorSpaceEnum; import org.apache.batik.ext.awt.RadialGradientPaint; import org.jdesktop.swingx.JXPanel; //import org.jdesktop.swingx.painter.BackgroundPainter; import org.jdesktop.swingx.painter.CheckerboardPainter; import org.jdesktop.swingx.painter.CompoundPainter; import org.jdesktop.swingx.painter.GlossPainter; import org.jdesktop.swingx.painter.MattePainter; import org.jdesktop.swingx.painter.Painter; import org.jdesktop.swingx.painter.PinstripePainter; import org.jdesktop.swingx.painter.ShapePainter; import org.jdesktop.swingx.painter.TextPainter; //import org.jdesktop.swingx.painter.gradient.BasicGradientPainter; //import org.jdesktop.swingx.painter.gradient.LinearGradientPainter; //import org.jdesktop.swingx.painter.gradient.RadialGradientPainter; /** * Two parts to this property editor. The first part is a simple dropdown. * The second part is a complicated UI for constructing multiple "layers" of * various different Painters, including gradient painters. * * @author Richard */ public class PainterPropertyEditor extends PropertyEditorSupport { /** Creates a new instance of PainterPropertyEditor */ public PainterPropertyEditor() { } public Painter getValue() { return (Painter)super.getValue(); } public String getJavaInitializationString() { Painter painter = getValue(); //TODO!!! return painter == null ? "null" : "new org.jdesktop.swingx.painter.CheckerboardPainter()"; } public static void main(String... args) { ByteArrayOutputStream baos = new ByteArrayOutputStream(300); XMLEncoder e = new XMLEncoder(baos); e.setPersistenceDelegate(GradientPaint.class, new GradientPaintDelegate()); e.setPersistenceDelegate(Arc2D.Float.class, new Arc2DDelegate()); e.setPersistenceDelegate(Arc2D.Double.class, new Arc2DDelegate()); e.setPersistenceDelegate(CubicCurve2D.Float.class, new CubicCurve2DDelegate()); e.setPersistenceDelegate(CubicCurve2D.Double.class, new CubicCurve2DDelegate()); e.setPersistenceDelegate(Ellipse2D.Float.class, new Ellipse2DDelegate()); e.setPersistenceDelegate(Ellipse2D.Double.class, new Ellipse2DDelegate()); e.setPersistenceDelegate(Line2D.Float.class, new Line2DDelegate()); e.setPersistenceDelegate(Line2D.Double.class, new Line2DDelegate()); e.setPersistenceDelegate(Point2D.Float.class, new Point2DDelegate()); e.setPersistenceDelegate(Point2D.Double.class, new Point2DDelegate()); e.setPersistenceDelegate(QuadCurve2D.Float.class, new QuadCurve2DDelegate()); e.setPersistenceDelegate(QuadCurve2D.Double.class, new QuadCurve2DDelegate()); e.setPersistenceDelegate(Rectangle2D.Float.class, new Rectangle2DDelegate()); e.setPersistenceDelegate(Rectangle2D.Double.class, new Rectangle2DDelegate()); e.setPersistenceDelegate(RoundRectangle2D.Float.class, new RoundRectangle2DDelegate()); e.setPersistenceDelegate(RoundRectangle2D.Double.class, new RoundRectangle2DDelegate()); e.setPersistenceDelegate(Area.class, new AreaDelegate()); e.setPersistenceDelegate(GeneralPath.class, new GeneralPathDelegate()); e.setPersistenceDelegate(AffineTransform.class, new AffineTransformDelegate()); e.setPersistenceDelegate(RadialGradientPaint.class, new RadialGradientPaintDelegate()); e.setPersistenceDelegate(LinearGradientPaint.class, new LinearGradientPaintDelegate()); e.setPersistenceDelegate(Insets.class, new InsetsDelegate()); /* Area a = new Area(new RoundRectangle2D.Double(20, 20, 50, 50, 4, 4)); a.add(new Area(new Ellipse2D.Double(10, 10, 100, 20))); TextPainter textPainter = new TextPainter("Yo dude"); textPainter.setFillPaint(Color.WHITE); e.writeObject(new CompoundPainter( new MattePainter(), new CheckerboardPainter(), new MattePainter(Color.BLACK), //new BasicGradientPainter(BasicGradientPainter.RED_XP), //new LinearGradientPainter(LinearGradientPainter.BLACK_PERSPECTIVE), new MattePainter(new RadialGradientPaint( new Point2D.Double(.5, .5), .2f, new float[] {0f, .5f, 1f}, new Color[] {Color.BLACK,Color.WHITE,Color.RED})), new ShapePainter(a), new PinstripePainter(), textPainter, new GlossPainter() // new IconPainter(), // new ImagePainter(), )); e.close(); System.out.println(baos.toString()); XMLDecoder d = new XMLDecoder(new ByteArrayInputStream(baos.toByteArray())); Painter p = (Painter)d.readObject(); JFrame frame = new JFrame("Yo momma"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JXPanel panel = new JXPanel(); panel.setBackgroundPainter(p); frame.add(panel); frame.setSize(800,600); frame.setVisible(true); */ RadialGradientPaint rp = new RadialGradientPaint(new Point2D.Double(0.5,0.5), .2f, new float[] {0f, .5f, 1f}, new Color[] {Color.BLACK, Color.WHITE, Color.RED} ); baos = new ByteArrayOutputStream(300); e = new XMLEncoder(baos); TestStuff ts = new TestStuff(); //ts.setStr("asdfasdf"); ts.str = "asdfasdf"; System.out.println("db = " + ts.getDb()); ts.setDb(new Point2D.Double(1.0,1.0)); ts.setIns(new Insets(5,5,5,5)); System.out.println("db = " + ts.getDb()); e.writeObject(ts); e.close(); System.out.println("more stuff"); System.out.println(baos.toString()); if(new Point2D.Double(0,0).equals(new Point2D.Double(1,1))) { System.out.println("they are equal"); } else { System.out.println("they are not equal"); } } public static final class TestStuff { public Point2D.Double db = null;// = new Point2D.Double(5,5); public TestStuff() { } public TestStuff(Point2D.Double db, String str) { setDb(db); setStr(str); } public void setDb(Point2D.Double db) { this.db = db; } public Point2D.Double getDb() { //new Exception().printStackTrace(); return this.db; } public String str = "asdf"; public void setStr(String str) { this.str = str; } public String getStr() { return this.str; } private Insets ins = null; public Insets getIns() { return ins; } public void setIns(Insets ins) { this.ins = ins; } } public static final class GradientPaintDelegate extends DefaultPersistenceDelegate { public GradientPaintDelegate() { super(new String[] {"point1", "color1", "point2", "color2"}); } } public static final class LinearGradientPaintDelegate extends DefaultPersistenceDelegate { public LinearGradientPaintDelegate() { super(new String[] {"startPoint", "endPoint", "fractions", "colors"}); //these 3 not yet supported. The problem is the //colorspace. I haven't figured out how to transfer that one yet //, "cycleMethod", "colorSpace", "transform"}); } protected Expression instantiate(Object oldInstance, Encoder out) { ColorSpaceEnum e = ((LinearGradientPaint)oldInstance).getColorSpace(); Expression retValue; retValue = super.instantiate(oldInstance, out); return retValue; } } public static final class RadialGradientPaintDelegate extends DefaultPersistenceDelegate { public RadialGradientPaintDelegate() { super(new String[] {"centerPoint", "radius", "focusPoint", "fractions", "colors"}); //these 3 not yet supported. The problem is the //colorspace. I haven't figured out how to transfer that one yet //, "cycleMethod", "colorSpace", "transform"}); } } public static final class Arc2DDelegate extends DefaultPersistenceDelegate { public Arc2DDelegate() { super(new String[] {"x", "y", "width", "height", "angleStart", "angleExtent", "arcType"}); } } public static final class CubicCurve2DDelegate extends DefaultPersistenceDelegate { public CubicCurve2DDelegate() { super(new String[] {"x1", "y1", "ctrlX1", "ctrlY1", "ctrlX2", "ctrlY2", "x2", "y2"}); } } public static final class Ellipse2DDelegate extends DefaultPersistenceDelegate { public Ellipse2DDelegate() { super(new String[] {"x", "y", "width", "height"}); } } public static final class Line2DDelegate extends DefaultPersistenceDelegate { public Line2DDelegate() { super(new String[] {"x1", "y1", "x2", "y2"}); } } public static final class Point2DDelegate extends DefaultPersistenceDelegate { public Point2DDelegate() { super(new String[] {"x", "y"}); }/* protected Expression instantiate(Object oldInstance, Encoder out) { Point2D pt = (Point2D)oldInstance; Object[] constructorArgs = new Object[]{ pt.getX(), pt.getY() }; return new Expression(new Point2D.Double(-1,-1), oldInstance.getClass(), "new", constructorArgs); } */ /* protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out) { super.initialize(type,oldInstance,newInstance,out); System.out.println("initialize called: " + type + " " + oldInstance + " " + newInstance + " " + out); }*/ } public static final class QuadCurve2DDelegate extends DefaultPersistenceDelegate { public QuadCurve2DDelegate() { super(new String[] {"x1", "y1", "ctrlX", "ctrlY", "x2", "y2"}); } } public static final class Rectangle2DDelegate extends DefaultPersistenceDelegate { public Rectangle2DDelegate() { super(new String[] {"x", "y", "width", "height"}); } } public static final class InsetsDelegate extends DefaultPersistenceDelegate { public InsetsDelegate() { super(new String[] {"top", "left", "bottom", "right"}); } protected Expression instantiate(Object oldInstance, Encoder out) { Insets ins = (Insets)oldInstance; return new Expression(oldInstance, oldInstance.getClass(), "new", new Object[]{ ins.top, ins.left, ins.bottom, ins.right }); } } public static final class RoundRectangle2DDelegate extends DefaultPersistenceDelegate { public RoundRectangle2DDelegate() { super(new String[] {"x", "y", "width", "height", "arcWidth", "arcHeight"}); } } public static final class AreaDelegate extends PersistenceDelegate { protected Expression instantiate(Object oldInstance, Encoder out) { Area a = (Area)oldInstance; //use the default constructor AffineTransform tx = new AffineTransform(); PathIterator itr = a.getPathIterator(tx); GeneralPath path = new GeneralPath(); out.writeExpression(new Expression(path, GeneralPath.class, "new", new Object[0])); while (!itr.isDone()) { float[] segment = new float[6]; //must use floats because lineTo etc use floats int pathType = itr.currentSegment(segment); switch (pathType) { case PathIterator.SEG_CLOSE: out.writeStatement(new Statement(path, "closePath", new Object[0])); break; case PathIterator.SEG_CUBICTO: out.writeStatement(new Statement(path, "curveTo", new Object[] {segment[0], segment[1], segment[2], segment[3], segment[4], segment[5]})); break; case PathIterator.SEG_LINETO: out.writeStatement(new Statement(path, "lineTo", new Object[] {segment[0], segment[1]})); break; case PathIterator.SEG_MOVETO: out.writeStatement(new Statement(path, "moveTo", new Object[] {segment[0], segment[1]})); break; case PathIterator.SEG_QUADTO: out.writeStatement(new Statement(path, "quadTo", new Object[] {segment[0], segment[1], segment[2], segment[3]})); break; } itr.next(); } return new Expression(a, Area.class, "new", new Object[] {path}); } } public static final class AffineTransformDelegate extends DefaultPersistenceDelegate { public AffineTransformDelegate() { super(new String[] {"scaleX", "shearY", "shearX", "scaleY", "translateX", "translateY"}); } } public static final class GeneralPathDelegate extends PersistenceDelegate { protected Expression instantiate(Object oldInstance, Encoder out) { return new Expression(oldInstance, GeneralPath.class, "new", new Object[0]); } protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out) { GeneralPath a = (GeneralPath)oldInstance; AffineTransform tx = new AffineTransform(); PathIterator itr = a.getPathIterator(tx); out.writeStatement(new Statement(a, "setWindingRule", new Object[] {a.getWindingRule()})); while (!itr.isDone()) { float[] segment = new float[6]; //must use floats because lineTo etc use floats int pathType = itr.currentSegment(segment); switch (pathType) { case PathIterator.SEG_CLOSE: out.writeStatement(new Statement(a, "closePath", new Object[0])); break; case PathIterator.SEG_CUBICTO: out.writeStatement(new Statement(a, "curveTo", new Object[] {segment[0], segment[1], segment[2], segment[3], segment[4], segment[5]})); break; case PathIterator.SEG_LINETO: out.writeStatement(new Statement(a, "lineTo", new Object[] {segment[0], segment[1]})); break; case PathIterator.SEG_MOVETO: out.writeStatement(new Statement(a, "moveTo", new Object[] {segment[0], segment[1]})); break; case PathIterator.SEG_QUADTO: out.writeStatement(new Statement(a, "quadTo", new Object[] {segment[0], segment[1], segment[2], segment[3]})); break; } itr.next(); } } } // public static final class PaintDelegate extends PersistenceDelegate { // protected Expression instantiate(Object oldInstance, Encoder out) { // if (oldInstance instanceof GradientPaint) { // // } // } // } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/RectanglePropertyEditor.java0000644000175000017500000000341211210401724027647 0ustar tonytony/* * RectanglePropertyEditor.java * * Created on August 16, 2006, 12:13 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.jdesktop.swingx.editors; import java.awt.Rectangle; import java.awt.geom.Rectangle2D; import java.beans.PropertyEditorSupport; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /** * * @author joshy */ public class RectanglePropertyEditor extends PropertyEditorSupport { /** Creates a new instance of Rectangle2DPropertyEditor */ public RectanglePropertyEditor() { } public Rectangle getValue() { return (Rectangle)super.getValue(); } public String getJavaInitializationString() { Rectangle rect = getValue(); return rect == null ? "null" : "new java.awt.Rectangle(" + rect.getX() + ", " + rect.getY() + ", " + rect.getWidth() + ", " + rect.getHeight() + ")"; } public void setAsText(String text) throws IllegalArgumentException { String originalParam = text; try { Rectangle val = (Rectangle)PropertyEditorUtil.createValueFromString(text, 4, Rectangle.class, int.class); setValue(val); } catch (Throwable e) { System.out.println(e.getMessage()); e.printStackTrace(); throw new IllegalArgumentException("The input value " + originalParam + " is not formatted correctly. Please " + "try something of the form [x,y,w,h] or [x , y , w , h] or [x y w h]", e); } } public String getAsText() { Rectangle rect = getValue(); return rect == null ? "[]" : "[" + rect.x + ", " + rect.y + ", " + rect.width + ", " + rect.height + "]"; } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/ShapeChooser.form0000644000175000017500000000350611210401722025436 0ustar tonytony

swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/PaintPropertyEditor.java0000644000175000017500000001207111210401722027015 0ustar tonytony/* * PainterPropertyEditor.java * * Created on March 21, 2006, 11:26 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.jdesktop.swingx.editors; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Rectangle; import java.beans.PropertyEditorSupport; import java.util.HashMap; import java.util.Map; //import org.jdesktop.swingx.painter.gradient.BasicGradientPainter; //import org.jdesktop.swingx.painter.gradient.LinearGradientPainter; /** * Two parts to this property editor. The first part is a simple dropdown. * The second part is a complicated UI for constructing multiple "layers" of * various different Painters, including gradient paints. * * @author Richard */ public class PaintPropertyEditor extends PropertyEditorSupport { private static Map DEFAULT_PAINTS = new HashMap(); static { //add the default paints DEFAULT_PAINTS.put(Color.BLACK, "Black"); DEFAULT_PAINTS.put(Color.BLUE, "Blue"); DEFAULT_PAINTS.put(Color.CYAN, "Cyan"); DEFAULT_PAINTS.put(Color.DARK_GRAY, "Dark Gray"); DEFAULT_PAINTS.put(Color.GRAY, "Gray"); DEFAULT_PAINTS.put(Color.GREEN, "Green"); DEFAULT_PAINTS.put(Color.LIGHT_GRAY, "Light Gray"); DEFAULT_PAINTS.put(Color.MAGENTA, "Magenta"); DEFAULT_PAINTS.put(Color.ORANGE, "Orange"); DEFAULT_PAINTS.put(Color.PINK, "Pink"); DEFAULT_PAINTS.put(Color.RED, "Red"); DEFAULT_PAINTS.put(Color.WHITE, "White"); DEFAULT_PAINTS.put(Color.YELLOW, "Yellow"); DEFAULT_PAINTS.put(new Color(1f, 1f, 1f, 0f), "Transparent"); // DEFAULT_PAINTS.put( // BasicGradientPainter.WHITE_TO_CONTROL_HORZONTAL, "White->Control (horizontal)"); // DEFAULT_PAINTS.put( // BasicGradientPainter.WHITE_TO_CONTROL_VERTICAL, "White->Control (vertical)"); /* josh: this should be replaced with matte painters DEFAULT_PAINTS.put( BasicGradientPainter.AERITH, "Aerith"); DEFAULT_PAINTS.put( BasicGradientPainter.BLUE_EXPERIENCE, "Blue Experience"); DEFAULT_PAINTS.put( BasicGradientPainter.GRAY, "Gray Gradient"); DEFAULT_PAINTS.put( BasicGradientPainter.MAC_OSX, "Mac OSX"); DEFAULT_PAINTS.put( BasicGradientPainter.MAC_OSX_SELECTED, "Max OSX Selected"); DEFAULT_PAINTS.put( BasicGradientPainter.NIGHT_GRAY, "Night Gray"); DEFAULT_PAINTS.put( BasicGradientPainter.NIGHT_GRAY_LIGHT, "Night Gray Light"); DEFAULT_PAINTS.put( BasicGradientPainter.RED_XP, "Red XP"); DEFAULT_PAINTS.put( LinearGradientPainter.BLACK_STAR, "Black Star"); DEFAULT_PAINTS.put( LinearGradientPainter.ORANGE_DELIGHT, "Orange Delight");*/ } /** Creates a new instance of PainterPropertyEditor */ public PaintPropertyEditor() { } public String[] getTags() { String[] names = DEFAULT_PAINTS.values().toArray(new String[0]); String[] results = new String[names.length+1]; results[0] = ""; System.arraycopy(names, 0, results, 1, names.length); return results; } public Paint getValue() { return (Paint)super.getValue(); } public String getJavaInitializationString() { Paint paint = getValue(); //TODO!!! return paint == null ? "null" : "org.jdesktop.swingx.painter.gradient.LinearGradientPainter.BLACK_STAR"; } public void setAsText(String text) throws IllegalArgumentException { if (text == null || text.trim().equals("") || text.trim().equalsIgnoreCase("none") || text.trim().equalsIgnoreCase("") || text.trim().equalsIgnoreCase("[none]")) { setValue(null); return; } if (text.trim().equalsIgnoreCase("")) { //do nothing } for (Map.Entry entry : DEFAULT_PAINTS.entrySet()) { if (entry.getValue().equalsIgnoreCase(text)) { setValue(entry.getKey()); return; } } throw new IllegalArgumentException("The input value " + text + " does" + " not match one of the names of the standard paints"); } public String getAsText() { Paint p = getValue(); if (p == null) { return null; } else if (DEFAULT_PAINTS.containsKey(p)) { return DEFAULT_PAINTS.get(p); } else { return ""; } } public void paintValue(Graphics gfx, Rectangle box) { Paint p = getValue(); if (p == null) { //do nothing -- in the future draw the checkerboard or something } else { ((Graphics2D)gfx).setPaint(p); gfx.fillRect(box.x, box.y, box.width, box.height); } } public boolean isPaintable() { return true; } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/DimensionPropertyEditor.java0000644000175000017500000000277711210401722027703 0ustar tonytony/* * DimensionPropertyEditor.java * * Created on August 16, 2006, 12:18 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.jdesktop.swingx.editors; import java.awt.Dimension; import java.beans.PropertyEditorSupport; /** * * @author joshy */ public class DimensionPropertyEditor extends PropertyEditorSupport { public DimensionPropertyEditor() { } public Dimension getValue() { return (Dimension)super.getValue(); } public String getJavaInitializationString() { Dimension point = getValue(); return point == null ? "null" : "new java.awt.Dimension(" + point.width + ", " + point.height + ")"; } public void setAsText(String text) throws IllegalArgumentException { String originalParam = text; try { Dimension val = (Dimension)PropertyEditorUtil.createValueFromString( text, 2, Dimension.class, int.class); setValue(val); } catch (Exception ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); throw new IllegalArgumentException("The input value " + originalParam + " is not formatted correctly. Please " + "try something of the form [w,h] or [w , h] or [w h]", ex); } } public String getAsText() { Dimension dim = getValue(); return dim == null ? "[]" : "[" + dim.width + ", " + dim.height + "]"; } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/PaintPicker.form0000644000175000017500000001147111210401722025264 0ustar tonytony
swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/PointPropertyEditor.java0000644000175000017500000000423411210401724027037 0ustar tonytony/* * $Id: PointPropertyEditor.java,v 1.2 2007/03/14 19:46:16 joshy Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.editors; import java.awt.Point; import java.beans.PropertyEditorSupport; /** * * @author rbair */ public class PointPropertyEditor extends PropertyEditorSupport { /** Creates a new instance of Point2DPropertyEditor */ public PointPropertyEditor() { } public Point getValue() { return (Point)super.getValue(); } public String getJavaInitializationString() { Point point = getValue(); return point == null ? "null" : "new java.awt.Point(" + point.getX() + ", " + point.getY() + ")"; } public void setAsText(String text) throws IllegalArgumentException { String originalParam = text; try { Point val = (Point)PropertyEditorUtil.createValueFromString( text, 2, Point.class, int.class); setValue(val); } catch (Exception e) { throw new IllegalArgumentException("The input value " + originalParam + " is not formatted correctly. Please " + "try something of the form [x,y] or [x , y] or [x y]", e); } } public String getAsText() { Point point = getValue(); return point == null ? "[]" : "[" + point.x + ", " + point.y + "]"; } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/Point2DPropertyEditor.java0000644000175000017500000000621111210401722027220 0ustar tonytony/* * $Id: Point2DPropertyEditor.java,v 1.3 2007/03/14 19:46:15 joshy Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.editors; import java.awt.geom.Point2D; import java.beans.PropertyEditorSupport; /** * * @author rbair */ public class Point2DPropertyEditor extends PropertyEditorSupport { /** Creates a new instance of Point2DPropertyEditor */ public Point2DPropertyEditor() { } public Point2D getValue() { return (Point2D)super.getValue(); } public String getJavaInitializationString() { Point2D point = getValue(); return point == null ? "null" : "new java.awt.geom.Point2D.Double(" + point.getX() + ", " + point.getY() + ")"; } public void setAsText(String text) throws IllegalArgumentException { String originalParam = text; try { Point2D val = (Point2D)PropertyEditorUtil.createValueFromString( text, 2, Point2D.Double.class, double.class); setValue(val); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); throw new IllegalArgumentException("The input value " + originalParam + " is not formatted correctly. Please " + "try something of the form [x,y] or [x , y] or [x y]", e); } } public String getAsText() { Point2D point = getValue(); return point == null ? "[]" : "[" + point.getX() + ", " + point.getY() + "]"; } public static void main(String... args) { test("[1.5,1.2]"); test("1.5,1.2]"); test("[1.5,1.2"); test("[ 1.5 , 1.2 ]"); test(" 1.5 , 1.2 ]"); test("[ 1.5 , 1.2"); test("1.5,1.2"); test(" 1.5 , 1.2 "); test("1.5 1.2"); test(""); test("null"); test("[]"); test("[ ]"); test("[1.5 1.2]"); } private static void test(String input) { System.out.print("Input '" + input + "'"); try { Point2DPropertyEditor ed = new Point2DPropertyEditor(); ed.setAsText(input); Point2D point = ed.getValue(); System.out.println(" succeeded: " + point); } catch (Exception e) { System.out.println(" failed: " + e.getMessage()); } } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/EnumerationValuePropertyEditor.java0000644000175000017500000000473611210401724031240 0ustar tonytony/* * EnumerationValuePropertyEditor.java * * Created on March 28, 2006, 3:49 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.jdesktop.swingx.editors; import java.beans.PropertyEditorSupport; import java.util.HashMap; import java.util.Map; import org.jdesktop.swingx.EnumerationValue; /** * * @author Richard */ public abstract class EnumerationValuePropertyEditor extends PropertyEditorSupport { private String[] tags; private Map values = new HashMap(); private EnumerationValue defaultValue; /** Creates a new instance of EnumerationValuePropertyEditor */ public EnumerationValuePropertyEditor(EnumerationValue defaultEnum, EnumerationValue... enums) { this.defaultValue = defaultEnum; for (EnumerationValue v : enums) { values.put(v.getValue(), v); } tags = new String[enums.length]; int index = 0; for (EnumerationValue v : enums) { tags[index++] = v.getName(); } } public String getJavaInitializationString() { EnumerationValue value = values.get(getValue()); if (value == null) { return defaultValue == null ? "null" : defaultValue.getJavaInitializationString(); } else { return value.getJavaInitializationString(); } } public String[] getTags() { return tags; } public String getAsText() { EnumerationValue value = values.get(getValue()); if (value == null) { return defaultValue == null ? null : defaultValue.getName(); } else { return value.getName(); } } public void setAsText(String text) throws IllegalArgumentException { EnumerationValue v = getValueByName(text); if (v == null) { //hmmmm, try again but trim text if (text != null) { v = getValueByName(text.trim()); } } if (v == null) { v = defaultValue; } setValue(v == null ? null : v.getValue()); } private EnumerationValue getValueByName(String name) { for (EnumerationValue v : values.values()) { String n = v == null ? null : v.getName(); if (n == name || (n != null && n.equalsIgnoreCase(name))) { return v; } } return null; } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/ShapeChooser.java0000644000175000017500000000247311210401724025420 0ustar tonytony/* * ShapeChooser.java * * Created on August 23, 2006, 10:19 PM */ package org.jdesktop.swingx.editors; /** * * @author joshy */ public class ShapeChooser extends javax.swing.JPanel { /** Creates new form ShapeChooser */ public ShapeChooser() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // //GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; shapeCombo = new javax.swing.JComboBox(); setLayout(new java.awt.GridBagLayout()); shapeCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Square", "Circle" })); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.weightx = 10.0; gridBagConstraints.weighty = 10.0; add(shapeCombo, gridBagConstraints); }// //GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables public javax.swing.JComboBox shapeCombo; // End of variables declaration//GEN-END:variables } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/newHighlighter.gif0000644000175000017500000000146111210401722025623 0ustar tonytonyPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDATxbT?W`~tzF @ d> @LȆw *V1,m6_ ~a _}E&6^ ϯwIX(L,VOx8>VA%\"Az{;'#+8UqdgR @ A>Cbw35> 1 6&n'fo!SvIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/editors/ImagePicker.form0000644000175000017500000000456411210401722025240 0ustar tonytony
swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXMonthViewBeanInfo.java0000644000175000017500000000263611210401722025147 0ustar tonytony/* * $Id: JXMonthViewBeanInfo.java,v 1.1 2008/12/16 11:05:25 kleopatra Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx; import java.beans.BeanDescriptor; /** * Fix for #951-swingx: JXMonthView looks weird in Netbeans form. * * Applied as provided by hmichel@dev.java.net. * */ public class JXMonthViewBeanInfo extends BeanInfoSupport { public JXMonthViewBeanInfo() { super(JXMonthView.class); } @Override protected void initialize() { BeanDescriptor bd = getBeanDescriptor(); bd.setValue("isContainer", Boolean.FALSE); } }swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/EnumerationValue.java0000644000175000017500000000136711210401722024646 0ustar tonytonypackage org.jdesktop.swingx; /** * Used with the setEnumerationValues method to specify enumerated values for * properties */ public final class EnumerationValue { private String name; private Object value; private String javaInitializationString; public EnumerationValue(String name, Object value, String javaInitString) { this.name = name; this.value = value; this.javaInitializationString = javaInitString; } public String getName() { return name; } public String toString() { return name; } public Object getValue() { return value; } public String getJavaInitializationString() { return javaInitializationString; } }swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXImagePanelBeanInfo.java0000644000175000017500000000232011210401722025217 0ustar tonytony/* * $Id: JXImagePanelBeanInfo.java,v 1.4 2007/05/04 00:30:02 joshy Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; /** * * @author rbair */ public class JXImagePanelBeanInfo extends BeanInfoSupport { public JXImagePanelBeanInfo() { super(JXImagePanel.class); } protected void initialize() { setPreferred(true, "editable"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/0000755000175000017500000000000011210401736022530 5ustar tonytonyswingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXPanel32-mono.png0000644000175000017500000000102611210401724025646 0ustar tonytonyPNG  IHDR s pHYs  gAMA|Q cHRMz%u0`:o_FIDATxڜ=R1 ?m_9}\x*^ ?]Ol0ݬ̺SPH򆀮וUkE z [ZbA m-*kIɑYxgkո҅/ 2bHP|1aBvKLLɤd ,+k!e^t\I& b>w 9 Xћ`oLZwwoVaR |G7q&~:{!" Ygc.gl/zƆIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXTreeTable16.png0000644000175000017500000000620211210401722025511 0ustar tonytonyPNG  IHDRa pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FIDATxڤjSA/HSp)Bƴ1%F -)b}?.\4hI w\&7)t0|3w[mofkM?~f$)ᣪnIBƽt{+/֐p8H7zI 6?ws9 ɪ̈̌[-Lش65VgXs*kutw[qSZze4c= g+֗}l28`>iVL -~(/ntoDI⍅gx| bD$w~Ksm17o%(Kxӹ3Lc[+&@R00sq`š8+Y'$ܕ X8IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/DropShadowBorder32.png0000644000175000017500000000225511210401722026612 0ustar tonytonyPNG  IHDR DPLTE  !!!"""###$$$%%%&&&'''((()))***+++,,,---...///000111222333444555666777888999:::;;;<<<===>>>???@@@AAABBBCCCDDDEEEFFFGGGHHHIIIJJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]^^^___```aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrssstttuuuvvvwwwxxxyyyzzz{{{|||}}}~~~]}tRNSJ pHYs  ~vIDAT8ӡ EQ>}A QQFG2U69IP\ô3#1&],H# H΅ǓMlGĽFqqq_[_8։obd/g]t5gnxnnnj753BUBs{dd$Ś]Wͬ{i-Z*WN\PE1B WVVtJ1h7#E8IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXHyperlink32-mono.png0000644000175000017500000000232611210401724026560 0ustar tonytonyPNG  IHDR s pHYs  gAMA|Q cHRMz%u0`:o_FLIDATxڄOl\WϛDIǢ,ZDDjb )u؀! 6DB&Ҥ**J6Vq;'޻,2V(,t}{snyh}>WDpkEܚr;47M`ܸ}q mJeD"3aLyO'>phOI%kʩzś;#p'U[Q{-ǘ ~߇_:rlZ 1z;y9qb [7_}R2HEElmQ/Olsڌf5JfmKU mÕo:mFYlsG* zU=on'${w(dJSMgUVQvCIm%[k%k5*#yk~U2y"Ӧ]7kAUIdmPzU-A"xY>].J]2>" uT!kb*$*K$t3M%U }*hqc>#u2yEER n%hiT}zNkc2H*fwt}]Iu Hά\GѫrB;Ք*XX"MG;SSڷ,n5 *ʮYgĀD1gRTst%*Vk[]]] vGFJ]lr좲,R2n:5AA{ĝt'.Hewy nh.x]1OL_qKyMeXPYumw;?rH}aO|c˜?~h8*7_5srӏ{ĔW̃^zʌwmp#4/xa3ʥɛChwxո_zF>HDb5uY{_j&_i v_3гZN:0c.ɽK++cų^5 朱ZGs/~!2J;~]^xqŻnNɡ*1\/ ѧX_]~&VG2nщ'B2 ;dP+UW[%C|U2eIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXTreeTable16-mono.png0000644000175000017500000000056511210401724026467 0ustar tonytonyPNG  IHDR7 pHYs  gAMA|Q cHRMz%u0`:o_FIDATxd1JCAȫ$!eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FIDATxl{hSw&6ӴGSN R:MZ|ieC((:Ad "XP3ђ> $xz9qK_ss)%Ŋe9Qus+I͢JiLZcr J+}TX)FJz+m;ky򗊉,@|%_6Y)12TFh&5kTz&k|Ld2:h Y*#۝ Z|w9G,24:qp18īUgH.Pv[>Hpr#Cr`̀3#n K~H~nb!l]rBs F6Vܺ+8ϻk$ i5d=Y|@쥆nfe#20# BE{mYJE2?WnBE(*O n!ڝu>hJ ;1{fZ=Gbٳ 5Crv'OL9v096+d`Sη]"~%6Wmj=ۦ8N#M8wDC?ܷL$x.XP[7!?ڝNqQ6D]cb s@˖~/~?lBþ=H)3L[5YGoi{eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FIDATxڜ=kTA{wDָ` \ `!XBZ/2 6z3 wf~I9pfԽ7 V/6ɕZyILlQ`!@syk--"ae!@Eܢ~\Q4d?1h$IxbCD{v}(JjCH)st=ZopΕ!a?;L( ڝmZgJMQ3 aށs(N qE18s~,xr/{{|}G8ZL5ƘPi4cZw B,S'J)$9j5$)i%bs0 !'OK;iJ߾b^l61\ vG4@RJ?VIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXTitledPanel16-mono.png0000644000175000017500000000051611210401722027017 0ustar tonytonyPNG  IHDR7 pHYs  gAMA|Q cHRMz%u0`:o_FIDATxt90EHFPQPp!Z8 R% AP`'4fqO-(}(6#5+`XZR8G:&TH͑S>8Ԁ\7](y+ $ڛ9sǐ 8@2T>2@\C.JQO0tQOI17fߔ^S,oM IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXTaskPane32.png0000644000175000017500000000662111210401722025353 0ustar tonytonyPNG  IHDR szz pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FIDATxĖNQi;- P\T%g炅B@H4рiD&F#D n1y;…Q[J 3.d* 5N2͹g|{E9lLaY:.Jxte;-yu[aWoZZC( !Km-6% yضc a)) ,#>NQ)ȃ%Pn7* r[ρSn@ Fww@8f`ht@K44M:[m^^-RaqCR2ŀIRݝdd|R /o0 'EG2M:IzR]Z,BF'tD/[[HYb'=qF!~|px 7}g' B Kd NAss3J) è!Qnll$Q.w*[L4M%vk*x<@.qVӳJ$DsJ)qU~#s>bڇ\( o>bJ:%p]D":4i*=̀ׯ^+z%˲hkk;ǦibY1t27",]~<=IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXTaskPane16-mono.png0000644000175000017500000000061611210401722026321 0ustar tonytonyPNG  IHDR7 pHYs  gAMA|Q cHRMz%u0`:o_FIDATxl1N[A>HxDBԹ52'"GM"\6%w#KvRx`f5ͷiU!mˬ%ak;trμV t\eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FIDATx1 B1D_4 vi- l,>BKZ@N)m4xqM}D <2\q!O b}JVWA7S*(U7}I2lj;whSBSFIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/placeholder32.png0000644000175000017500000000622111210401722025661 0ustar tonytonyPNG  IHDR szz pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FIDATx-s@c*RG]!* H$ HZGe;Cg<\pKDE΁˹- 䃐 v&=#"Ti+DFD0@0@D; `U"r6B|E 0u~M>|c,(҆VI oA.shmkm(A*kښ7 arZL+ǞoFJ' @9$LNBϡ8@ؖ u 7:nIqi98m$8(3VtJJ̻:귝L׊DҊhO=' IYdIR|J.qz+oi-B"AhxId-kuuS/oW| Pv.H%e?bxr(^IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXTreeTable32-mono.png0000644000175000017500000000134111210401722026454 0ustar tonytonyPNG  IHDR s pHYs  gAMA|Q cHRMz%u0`:o_FWIDATxڜ?o1$P MAhh"=D  Jj>-ETPg(v74X~~~<';F0dԇ2^zZoa9tv9dvz2O5`8}63nbp5)J 莁H({3BJ61Z|.L P2lLls،&Cx TFI``)kAdt.bv*Фrbߒ* J\$+''|| ;+nAFbg3H/-/X!GLm^Ē= Z}lӔF.Yr -BHw~UB3eG %KE.YqY32LEE඲+`>N>͍ NH-O#?4+-RɵɀCVZec Z0TPg9Eiٌ p-qoI|(IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXTaskPane32-mono.png0000644000175000017500000000130511210401722026313 0ustar tonytonyPNG  IHDR s pHYs  gAMA|Q cHRMz%u0`:o_F;IDATxڜnAklGIB A" "R 4< t $$'H$_w(nnt?76t,4%޳v7t@wgcRdŹ,Qnn-q@YFSYgB!K2U+7a’aM[71Ooll::^8vI5z" hEHC:8W7Bo#@o8R?!P(KS9l:7J[pL9)L*o,^N99 <>?xM J )898N@Ax[Yc ^cnxO)+F hnQV*3p]V!0 _{V+a^0b4_AN<ܾ*wHb%)o0{U\dଞH> 6@hZnQ0 ީH 9Hx xx z{(sΝ6VMOs/lx0b[YpoD%.PIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXErrorPane32.png0000644000175000017500000000351211210401722025536 0ustar tonytonyPNG  IHDR DPLTE|JL"$BDDB>nl̒DNLĔ64 jl"$dbdܦb\$RPRT64z|rlz|dNLL64¼l"$jlBD .,tvl RPZ\24BDBD,.,:<rt 24ľbd$d^\ *,LNL T"$lnlܼrt^\NL ^\JDܖrttbaRTd^\ \\<64;<}|;<Զll DFD,*,.,vlrttZ\4܊̜~|tVT ^\|t\2,44"$.,,|vtL lVTJL:<vt64fd., &$ܚVT\BtRNS= pHYs  ~DIDAT8]y\ qPb)"+Uu$w5-,r3uKukcdu)KcI~~=sŃfs_^ORJ<{[upxywDrtbfFN= KgϟFՁ{dX˗?"5jo|{qEE᜘|aSrP'"EbmJڏVk|X5XhhsW)rVVVRR@!<;+ +=4M?MM=e ^5ͻ sn$,yiWeH c˚>Mh xO fo%"^) d00ŷsBYTh"SJdó[R>( F­ S1pX [@5BT* 6"9,f( ̝"Q&1)Y,r ǁ#SJ_p0qvm,̆F8Ųa`[F!)ǤՍq<.`Y~`AFH1hO w5.)"OQ$IޛO} ũ`$"4z@,0v,#`=NQ {dd,_ CpeyHgT`Zfls&A샂eaIcl񌒩jBCKZ9%g F Ļ:5F%qڊ)z'wf؆4K(7K>ii>Oy~xۭꮏwZ槵4  ffIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXTaskPane16.png0000644000175000017500000000623311210401722025354 0ustar tonytonyPNG  IHDRa pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FIDATxڜ=kTA{wDָ` \ `!XBZ/2 6z3 wf~I9pfԽ7 V/6ɕZyILlQ`!@syk--"ae!@Eܢ~\Q4d?1h$IxbCD{v}(JjCH)st=ZopΕ!a?;L( ڝmZgJMQ3 aށs(N qE18s~,xr/{{|}G8ZL5ƘPi4cZw B,S'J)$9j5$)i%bs0 !'OK;iJ߾b^l61\ vG4@RJ?VIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXGraph32.png0000644000175000017500000000651711210401722024712 0ustar tonytonyPNG  IHDR szz pHYs   OiCCPPhotoshop ICC profilexڝSgTS=BKKoR RB&*! J!QEEȠQ, !{kּ> H3Q5 B.@ $pd!s#~<<+"x M0B\t8K@zB@F&S`cbP-`'{[! eDh;VEX0fK9-0IWfH  0Q){`##xFW<+*x<$9E[-qWW.(I+6aa@.y24x6_-"bbϫp@t~,/;m%h^ uf@Wp~<5j>{-]cK'Xto(hw?G%fIq^D$.Tʳ?D*A, `6B$BB dr`)B(Ͱ*`/@4Qhp.U=pa( Aa!ڈbX#!H$ ɈQ"K5H1RT UH=r9\F;2G1Q= C7F dt1r=6Ыhڏ>C03l0.B8, c˱" VcϱwE 6wB aAHXLXNH $4 7 Q'"K&b21XH,#/{C7$C2'ITFnR#,4H#dk9, +ȅ3![ b@qS(RjJ4e2AURݨT5ZBRQ4u9̓IKhhitݕNWGw Ljg(gwLӋT071oUX**| J&*/Tު UUT^S}FU3S ԖUPSSg;goT?~YYLOCQ_ cx,!k u5&|v*=9C3J3WRf?qtN (~))4L1e\kXHQG6EYAJ'\'GgSSݧ M=:.kDwn^Loy}/TmG X $ <5qo</QC]@Caaᄑ.ȽJtq]zۯ6iܟ4)Y3sCQ? 0k߬~OCOg#/c/Wװwa>>r><72Y_7ȷOo_C#dz%gA[z|!?:eAAA!h쐭!ΑiP~aa~ 'W?pX15wCsDDDޛg1O9-J5*>.j<74?.fYXXIlK9.*6nl {/]py.,:@LN8A*%w% yg"/6шC\*NH*Mz쑼5y$3,幄'L Lݛ:v m2=:1qB!Mggfvˬen/kY- BTZ(*geWf͉9+̳ې7ᒶKW-X潬j9(xoʿܔĹdff-[n ڴ VE/(ۻCɾUUMfeI?m]Nmq#׹=TR+Gw- 6 U#pDy  :v{vg/jBFS[b[O>zG499?rCd&ˮ/~јѡ򗓿m|x31^VwwO| (hSЧc3-gAMA|Q cHRMz%u0`:o_FjIDATxė_HSQǿqҹ?,J!"EDO!Q>AEDS=%=ְ+h+Z܃l޹ӛԜ}<~~sl%d€c ēyizub\%ezm@ʕ쵈ɱ6={ϿBF}50N[@=rЍs'fѫ 1=ŸcލvU\ͺ g˷1.L4 Y³,"Ic!X UDEC29l^AVV+tw`iDo:v5-n7xG n_,`Qss$1oGI2UJ5K q#VI8tu*H8mU(̺x(H.D^[ _(azƋTVe*Sð4kiă]&\<5=od`G"Sв]A(bn!VU^a.~<}DŽBP$o+1wPy1跶xCjb"FC~ ~@&-7IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXTaskPaneContainer16-mono.png0000644000175000017500000000713311210401722030165 0ustar tonytonyPNG  IHDR(-S pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FPLTENNNztRNS@f_IDATx|A0 C41,`JF?uaT4GmXmT I|^mL~I `4GJN:rIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXBusyLabel32.png0000644000175000017500000000215511210401722025525 0ustar tonytonyPNG  IHDR DPLTEȢrqn\ZX000^]Zž222Ŗ887Ęę=<<ȹllk```kkjƳƺßhtRNS@f pHYs  ~IDAT8V0BM,,Q,c1!$p4k{g&2Y"}"m._8]po9XQ4 Jx2 DGB4sY"жw/[Qjy(3xFc}2FT$ ^mRB=pV\-hv8=&IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXLabel16.png0000644000175000017500000000064511210401722024666 0ustar tonytonyPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<7IDATxb?% (DDӀ g`(A }b, 6_$?| 6@ ؀es萘3 E9Y2...nOش"^xـ80(&fa ~1{w` x $0ypU#(%g? 3{!Ɂ$N6(ep(,UҼ@D&CuIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXTitledPanel32.png0000644000175000017500000000607611210401724026060 0ustar tonytonyPNG  IHDR szz pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_F[IDATx;N1EO2g :V@Cn()-TT!v'~PIzz88眴H51!09|SG׷mxW\k+T9|xig 4)>T#U_]U-EQqյ;{ZTr( v%@QSPlYѓC_`͍)=3U_"-a\G-Y/ i᠍s:9hO?IZH$_ws;IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXButton16.png0000644000175000017500000000076211210401722025122 0ustar tonytonyPNG  IHDRagAMA7tEXtSoftwareAdobe ImageReadyqe<IDATxb?% (D=u. J_8tϜ X_76WĠ>q:Ce~&ǏfP/@ˏ` v1x8;2hh3ܸqWPTb TsE60Ճ߿>}  ar ze ^ (ׯ_ ~O8A( vڕK`6aA V-cxB=P/@1#3ÿl]0gJ'Ar6q0G3^,@iye3JȊƕ3z˗/'L0'ǀ? F |dOHin 3@i?HIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXGraph32-mono.png0000644000175000017500000000104311210401722025645 0ustar tonytonyPNG  IHDR s pHYs  gAMA|Q cHRMz%u0`:o_FIDATxڤ?HPy DtuqRAAts)bqqsE.:g)(*E[ںxmI~ݗw+bg. +4pr2[ ? _Ç3]wh AyYBJ,=$$ ^1C|uXXcol~y+D5$)3 !#(QF1&X#n1NC`a%W6xfmjArQ.zFP$Faݩ;;B8:nSUܷ$V%4_!MwIBUVzPׂS@dS[^#z`'XQC57s:QvT\Dܤ"nR!OoGJIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXErrorPane32-mono.png0000644000175000017500000000353311210401722026507 0ustar tonytonyPNG  IHDR DPLTE  !!!"""###$$$%%%&&&'''((()))***+++,,,---...///000111222333444555666777888999:::;;;<<<===>>>???@@@AAABBBCCCDDDEEEFFFGGGHHHIIIJJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]^^^___```aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrssstttuuuvvvwwwxxxyyyzzz{{{|||}}}~~~]}tRNS pHYs  ~#IDAT8]_Hq|j2:6n7ہSi.֔a^tqA -E GHQFb{ ܃=DADP>\3˱gdw?{'ibY5/>3 YU6^ f ڒ1=ܿh!n%M7VV cnnZ̦r˲0d&y=e4-jim@XIڤ˧x<.')5Tz"5M;@gg?!˱H@AB,i[ZDA[ث[HG=DTEz Hz-M+ &ɲY/ڂ ᱉X"6OYF<#HO`8C_hj'>kW? =o\9 oA縁~ z^O;[D'JA^p<U㘟} y`Xx4Er%x,N7|p3 v$Ia)WW>шS]aݗKo؂.`덍<w0>RqfIoo >D4|ӏ)M̜ i*.h$ ԓEeq+\ HxB:$'P;~L`@@Ÿ==nR jsN}1JR^opm8zpJgwsο˻pVWg=QYYމy0C:o%IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXDatePicker32.png0000644000175000017500000000743211210401722025661 0ustar tonytonyPNG  IHDR szz pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_F7IDATxڼ_L[u?PLY۲ &f58b4<,3K8QUfp2F/?S#it.> _d!)^m{i0Nr{=;{νH)1ˉFNDh %^J )] Dץ`_K@s뿘X8TF{;=D[{mmef_<fm% ~ FCEflV)%KKK9w1 p a ŷP[UJI8FJɩn^E3vXˇh40DQQOk$;QeuAl65/fc5K*DBGFF6-)t|1,bnWs !-Po|c4TWp'f5ֵ`%i:?ßa:>B3!}WV%"c΂YY<};uسH! \J@ +H!W -qv] Ku'hfdt@ S+mÉU@fVtb6nH)injdNЀ"?oi$7WVp yp -!#FFǹMԼPn?Wpxp!`pCgn.ɇ}_Gp8 >/u),\ kJB>_13>{k`onZp8̥DKzY~4 {@utrxbuKjNf?#Gۓ:\?f-"LF oSS3MͿsw;w ˞T5 P|GKJx)W.hxek`-8 WJ@}.Mhri㘯Al!) eZǤJJӀn?UR7zF[)XQ&eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_F|IDATxڤ{pT޻w_y@@BHceѴJ;TQkթSjڎթ̴:>PDZ@*$$A%O6nv$T=3ߜ;w!iO&hJbWZ^<\tySĂUGL۾-- ~eع+ūMnUkYDMw|i~l{8K뙐? H"Dʠ`9&[5׭rw@x|5?`ĥ8v-@bh-!v~ @΢+r93 k~1}Y/qqJBv*² 'a{+ge1sshKBg"}s(3=6u s$ A*sb _qs3/`-;:ٖ"lAJ{tJX8I8< D (ieLB\xې!h8M<mP>sDKI9\ ًz#$;>qSM iX2fn}}`/Q@z_Sc@X#킳h ?HIJIMG>~d<̩6ڀqp=qm!iuQMXJA;Є8v6 $Y g6yr#n)GGA)Qvc'->w= }9B*5A$v63lޔ+I ݵlǑn>;Y^#AB/P)V9$~I-h@|Ryhl3Y9 ]C8^K 1Q-o2NK"5@0I&=^za#gi¤kOEQɃ莉_Zd 7]3v]g;C-{E1NiK 12I,OOR@Nv"]g !%)%JĘ2J8i~>r)E=Ͳ,4]{7wuMSq]wj(ض6GB}쮣pޕKɄbl۞ߓxnɄb>V> Ćp4p]y {Id(xWaX-X>t{54iƲ|=y<7}Vl~cK)L _5{ދ=lt `I)k4Bx?R=z'IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXGraph16-mono.png0000644000175000017500000000064511210401722025656 0ustar tonytonyPNG  IHDR7 pHYs  gAMA|Q cHRMz%u0`:o_FIDATx\?nSAF<&'J%@t4Ű$6@A٢&N> ?4gts-ʸeNr2nBgr3hP[ZkKuZpjn'"$g$Yf$Ye>>???@@@AAABBBCCCDDDEEEFFFGGGHHHIIIJJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]^^^___```aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrssstttuuuvvvwwwxxxyyyzzz{{{|||}}}~~~]}tRNSJ pHYs  ~IDAT81 0=0\P0!]/T%OIX 1p ?PgeR . \$K#H2pn J#WX k}F0 DWG u. cu1M5Pmo|rŕ~|IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXDatePicker16.png0000644000175000017500000000624611210401722025665 0ustar tonytonyPNG  IHDRa pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FIDATxڤkQd % u?@NUS[? R'AQŪJmuu1`t˛? Br9qѨp/wx/\ *[~E73sT|I,RtPU<Lz=Tv[8͢*1l ^gaq%,+_X["|V˼zSesJ% D"&Us\}D߽xqHTa@U6m['xʾ03°~ kƎafofմC ΍X CC!ǎ8f@by/ߖȾ9s=g|-$9r jdT,:gq('H?un;dR{0N6`<~;)9IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXCollapsiblePane32.png0000644000175000017500000000662111210401722026702 0ustar tonytonyPNG  IHDR szz pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FIDATxĖNQi;- P\T%g炅B@H4рiD&F#D n1y;…Q[J 3.d* 5N2͹g|{E9lLaY:.Jxte;-yu[aWoZZC( !Km-6% yضc a)) ,#>NQ)ȃ%Pn7* r[ρSn@ Fww@8f`ht@K44M:[m^^-RaqCR2ŀIRݝdd|R /o0 'EG2M:IzR]Z,BF'tD/[[HYb'=qF!~|px 7}g' B Kd NAss3J) è!Qnll$Q.w*[L4M%vk*x<@.qVӳJ$DsJ)qU~#s>bڇ\( o>bJ:%p]D":4i*=̀ׯ^+z%˲hkk;ǦibY1t27",]~<=IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXPanel16-mono.png0000644000175000017500000000045211210401722025650 0ustar tonytonyPNG  IHDR7 pHYs  gAMA|Q cHRMz%u0`:o_FIDATxtA 1 E_ƀubgn+^A6.@K  U3 vj@rBc0?ʼ`@' hiG! 뭃!Iӕ߿^5dI"a-ZB'Md(\>Ejrml2N ,IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXCollapsiblePane16-mono.png0000644000175000017500000000061611210401722027650 0ustar tonytonyPNG  IHDR7 pHYs  gAMA|Q cHRMz%u0`:o_FIDATxl1N[A>HxDBԹ52'"GM"\6%w#KvRx`f5ͷiU!mˬ%ak;trμV t\sc 6K;4 _j۬v&=IwlykyFFeN[sc҈uAR qɈʳ%PC,vpʚJ..@0P-+9;eg=e/ܥp^DZkc~2bWA@wT˰p Y7/CC(꾵f[}[p/T]GV[:]$j!xvo79)a{hjhhhgn>}dK^saL uuuoL^#^x-D*yUCځY;vZkSq~EϹ`VKKTM=woZ))?y6V 2J:#xMM[4}Z"'3ewvԓt)˛AK-d< rYGpXKKˌ_5M2冺z/NSL3eZrW݉3](o2DI$ a994l̄ 5}rWn6)7&7l]}h1e^6&\s]_.rdbj"7nRuݮYvd2\-/wYHKa 6NZXk4i..VM-ҳR5iy㓞(xp_'SK )FvsK-QSob|$Xua>`$Xe_E_>zYIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXTaskPaneContainer32-mono.png0000644000175000017500000000737311210401724030173 0ustar tonytonyPNG  IHDR D pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FPLTE333NNN\\\ntRNS@fIDATxڤn0 DiUv;UR >8aCHπV [d2f %6g3DݗPx g]1P9fpcN;/`)*ud(u'l' ]u.m9((ї~cknuo &(wq"w)٬\!rO\HRۦ?5ó^-Q0[fDk\SK5aZ[Lrp Y 7 U,IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXTreeTable32.png0000644000175000017500000000671611210401724025523 0ustar tonytonyPNG  IHDR szz pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FIDATxėOHac[A+tX<D| |́D"ކ6#jErٍ%RbSbH@΄ܷؼ Qqfkő0^RTxN!gUEc, bQ@\(܇ɖC=>heQX)rn%Pl;v^9@=q|=Pg IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXTitledSeparator16.png0000644000175000017500000000221511210401722026750 0ustar tonytonyPNG  IHDR(-SPLTE  !!!"""###$$$%%%&&&'''((()))***+++,,,---...///000111222333444555666777888999:::;;;<<<===>>>???@@@AAABBBCCCDDDEEEFFFGGGHHHIIIJJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]^^^___```aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrssstttuuuvvvwwwxxxyyyzzz{{{|||}}}~~~]}tRNSJ pHYs  ~VIDATc@H R&"D/B. ]t!4'0/_x2(`nDhYv(wNG-fIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXTitledPanel16.png0000644000175000017500000000574011210401722026055 0ustar tonytonyPNG  IHDRa pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FIDATxڜ1J173Q'Y\XXx< v[xd*(Db'k$E88&sJ3moFr]/N ֤G[ lmkutڔL~FX-|7cloGٟ8C4kmI+8<>m5EQ$UU_TxL!dU9xrx@^@X*u]Bݽzv#k.PIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXLabel32.png0000644000175000017500000000147411210401722024665 0ustar tonytonyPNG  IHDR szzgAMA7tEXtSoftwareAdobe ImageReadyqe<IDATxb?@bb`@pЀ; 4w@ %)\͛HR2 XGFR2 XKF2 X'1S)?P$"2Nv̀GW/_<((c:5&| s ?Pt&|{W//Q 馷oU3`޿aŒ1,o߼M/a=H}xnpBbSϼ}t@Lfa8ۦ-;z y~ػ7ohd9Y`sA6 !Tu}jXy_X hK TW(vhzt2# H篝 ?~|?Ȟag`Xr>!Q j]n5\ W@Laal&A q)>Ԅ&K"jߟ (,E F'|$~߿{Wo5B A~f6B@ Ezd5Aۯ ۱? 珟բ9{g@gIȔe9T1'!5K@*h@pЀ; 4w@  F ;IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXFrame32.png0000644000175000017500000000076511210401722024702 0ustar tonytonyPNG  IHDR szzgAMA7tEXtSoftwareAdobe ImageReadyqe<IDATxbuצ{lpg;9'.M.z6hQ ="vuY|fr^ix$Kf$t-ICfy"*  Y/YɎz6j yCƊqB7.?ɸiF#odAve ZseWL会s6< \ p)k9e6U/:o >c51KY)YuVOKzJs}" [k# dByؗ 7IՉm sYSʹYrNj2Xz 6UXm.X H3Q5 B.@ $pd!s#~<<+"x M0B\t8K@zB@F&S`cbP-`'{[! eDh;VEX0fK9-0IWfH  0Q){`##xFW<+*x<$9E[-qWW.(I+6aa@.y24x6_-"bbϫp@t~,/;m%h^ uf@Wp~<5j>{-]cK'Xto(hw?G%fIq^D$.Tʳ?D*A, `6B$BB dr`)B(Ͱ*`/@4Qhp.U=pa( Aa!ڈbX#!H$ ɈQ"K5H1RT UH=r9\F;2G1Q= C7F dt1r=6Ыhڏ>C03l0.B8, c˱" VcϱwE 6wB aAHXLXNH $4 7 Q'"K&b21XH,#/{C7$C2'ITFnR#,4H#dk9, +ȅ3![ b@qS(RjJ4e2AURݨT5ZBRQ4u9̓IKhhitݕNWGw Ljg(gwLӋT071oUX**| J&*/Tު UUT^S}FU3S ԖUPSSg;goT?~YYLOCQ_ cx,!k u5&|v*=9C3J3WRf?qtN (~))4L1e\kXHQG6EYAJ'\'GgSSݧ M=:.kDwn^Loy}/TmG X $ <5qo</QC]@Caaᄑ.ȽJtq]zۯ6iܟ4)Y3sCQ? 0k߬~OCOg#/c/Wװwa>>r><72Y_7ȷOo_C#dz%gA[z|!?:eAAA!h쐭!ΑiP~aa~ 'W?pX15wCsDDDޛg1O9-J5*>.j<74?.fYXXIlK9.*6nl {/]py.,:@LN8A*%w% yg"/6шC\*NH*Mz쑼5y$3,幄'L Lݛ:v m2=:1qB!Mggfvˬen/kY- BTZ(*geWf͉9+̳ې7ᒶKW-X潬j9(xoʿܔĹdff-[n ڴ VE/(ۻCɾUUMfeI?m]Nmq#׹=TR+Gw- 6 U#pDy  :v{vg/jBFS[b[O>zG499?rCd&ˮ/~јѡ򗓿m|x31^VwwO| (hSЧc3-gAMA|Q cHRMz%u0`:o_FIDATxڔMkQ`B-ҍ .\s Bn] ".?6R\".BQ$&{''g=faN "ғ}_V|ߟpk$7K4}]4)i/=ѓwY]:SAok@7dtoz51L9hES."uÕ iVK Y)?mX,ܤzLIDrs.geZma_=͹EP=[,QT~D{LL#L4MI4? h}ytPIbV-^f̥IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXErrorPane16.png0000644000175000017500000000220211210401722025533 0ustar tonytonyPNG  IHDR(-SPLTEٻ珋vtsspqfefeղݧkijj~edNNUTԗݨYV\[zypp``[[ZYOO::<;Ɍ׻^\CC]]qqCC 23TU77&%76݄33;;ЂvvkkľllRO¼MJ ''jhxy''rsfd#!'(iikk `[ wwww  kGE υbA>0,ml謬vv~^IF^Y ccjknomnc rieş#"XWkk llɷ\\{N('örn .. -. }O kebý`]wP UJGʿok#!vaJ_VS¨{POc$#YQEK;9{u2tRNS@f pHYs  ~IDAT  !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijhklmnopqrstuvwxyz{|}~66fkn֭IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/DropShadowBorder16.png0000644000175000017500000000223311210401722026610 0ustar tonytonyPNG  IHDR(-SPLTE  !!!"""###$$$%%%&&&'''((()))***+++,,,---...///000111222333444555666777888999:::;;;<<<===>>>???@@@AAABBBCCCDDDEEEFFFGGGHHHIIIJJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]^^^___```aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrssstttuuuvvvwwwxxxyyyzzz{{{|||}}}~~~]}tRNSJ pHYs  ~dIDATϡ EQA & DE OZIH`ap~Ai$ry &* m]T.v:׽OYIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXPanel16.png0000644000175000017500000000557111210401722024711 0ustar tonytonyPNG  IHDRa pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FIDATx̓ B1 EϫqQ7orvjlp0KMCY"r~QDMl~Rڔ?]㪠?ap%0u_͂2)*(QRJm[AUY,WGv@ xTy\TIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXTaskPaneContainer16.png0000644000175000017500000000714511210401724027224 0ustar tonytonyPNG  IHDR(-S pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FPLTEJꄠSuMtRNSރYbIDATx\A1CB_7J.E3_۴R{𕨃APa0vWp9-6HXIם]=2L!%N)Wh!IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXTaskPaneContainer32.png0000644000175000017500000000742211210401722027216 0ustar tonytonyPNG  IHDR D pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FPLTEJꁊ~2ɚn{Su2:ntRNS#]IDATxڄ D_8Q+w8lq=8eI:e~u-:6[9cn=k"Lg'8@FJ&\*@dP05=wXx` hKbPQ hs_z70JXP 5E)ӓT3LHo e{倥)raMRQ!"{sT@G"PuԖa~)J9a6Jf.d&U;Qyq]n3OQIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXImagePanel32.png0000644000175000017500000001044511210401722025646 0ustar tonytonyPNG  IHDR szz pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FBIDATxėL?p :+DKEhv~t-qm۲:%f]fْMR34.6n:֚vt(8-L쏋jI''9~ysuj]>^]۽oGI1 hm ܶcP綷$ D ڸ~&f̯&cC)p@cbj#xeu,*M˄& ֣,^Rɂ҅,(]vⴶ%n Lzڛ m^n=ML)H+XAJG% VL8$ c*?n,amBK3Ѡ -4Bv# qz2ξ^?) ffWSOK H!%+zD \wQdoz bG;B;y? x)ĄwoPÃth9Xb-*֋QnH7NNFEY/),W{Q{ m,8w>v"$LHQ3v#Ei#i'sļn{`W'] ss?穟!l ó9ȱ};8jH}kM|Y9uz?\BCh'x!, -/!i8_1=||m%}v&ƍaF^t\FXIlvKbJ4bTW bC3D n'ho9Sx0"ƀ`Thhldoro˖ScA-ʩ?^;}ޛqaF\; ba8 M?D(2H?ߍ+Ȫ`b.׀Z!(1E([NeI)-?Dy^%)G[y$?o`oq>ғI!* Nx#qc\q;g{~d\ӝ\MQV =A?YtIo\#3'KJƨPCӔ=J,B~yw8o nfȀ)FIRY]7}֌L`}#}vQgr$r4Cx|71 -$8f9+d4l_&Hk,hhZ7u%dYXI3;̀X\ 674jmI@6XE 5eIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXErrorPane16-mono.png0000644000175000017500000000252311210401722026507 0ustar tonytonyPNG  IHDR(-SPLTE  !!!"""###$$$%%%&&&'''((()))***+++,,,---...///000111222333444555666777888999:::;;;<<<===>>>???@@@AAABBBCCCDDDEEEFFFGGGHHHIIIJJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]^^^___```aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrssstttuuuvvvwwwxxxyyyzzz{{{|||}}}~~~]}tRNS pHYs  ~IDATé϶Ϸto‰{wbY\ixoccms̐QFO[Okw^e[OGIZRUTKEA=hIHKEHE??;8QHACAHG<:5/JX9w/%3ʆ86S:1219Q1%!fu4++--+*'$L}@,('&$ 'Xț\6(%'?{х[~QIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXTitledPanel32-mono.png0000644000175000017500000000106611210401722027016 0ustar tonytonyPNG  IHDR s pHYs  gAMA|Q cHRMz%u0`:o_FIDATxڜMn0 FT.荺!z{WbE%Tc)rlD޶)µܴğ8FWq5dz Og8؃3 yvٰ1(lG6tb[;TibVl2dp0Hb(aK7BѮD zZ~ctuYy48-jL$awN_HG ZDO+Oaon"xCXpkGt?ģFe9FځlTLBmlbGJwCS %|!qa/VʜAN&:YsudĊ*M!#LRJ%ő644Ju!_8Gn7/ 1<39'ܯ,IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXButton32.png0000644000175000017500000000127411210401722025117 0ustar tonytonyPNG  IHDR szzgAMA7tEXtSoftwareAdobe ImageReadyqe<NIDATxb?@bb`@pЀ; 4 wi7@%-)v@l5o+@ ?4 @, 30! X t_>z̰iN8ӝA^N̞A ?{ @,oiϟ@CePԁ q޲m3: Ȇ~ƪ&A7fDP=@10@ ܻ"aN ۶nP 0/vtfضe{| jQ ! @l?#ޠQPepvgرy \;, 3եV 1cfa)/@rq`JB. . @?Rh7@|)ဟ? P1>@h4w@ h`$zAIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXBusyLabel16.png0000644000175000017500000000206611210401722025530 0ustar tonytonyPNG  IHDR(-SPLTEȰ442220ļĚyxt[YW \[Y222EEDĘGFE111ONMRPMPNKQONZYVûŴ}|zihhgffiih|{yòƿƻþXtRNS@f pHYs  ~IDATc`F&f(`ec`d`   D%$edEE*jZ: z =F&&f@.-dJ N.`\E</P/+L˫5'8$4,fKDdTtLl.aqAvvº3p&0$'<~I F xIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXCollapsiblePane32-mono.png0000644000175000017500000000130511210401722027642 0ustar tonytonyPNG  IHDR s pHYs  gAMA|Q cHRMz%u0`:o_F;IDATxڜnAklGIB A" "R 4< t $$'H$_w(nnt?76t,4%޳v7t@wgcRdŹ,Qnn-q@YFSYgB!K2U+7a’aM[71Ooll::^8vI5z" hEHC:8W7Bo#@o8R?!P(KS9l:7J[pL9)L*o,^N99 <>?xM J )898N@Ax[Yc ^cnxO)+F hnQV*3p]V!0 _{V+a^0b4_AN<ܾ*wHb%)o0{U\dଞH> 6@hZnQ0 ީH 9Hx xx z{(sΝ6VMOs/lx0b[YpoD%.PIENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/resources/JXImagePanel16.png0000644000175000017500000000653111210401722025651 0ustar tonytonyPNG  IHDRa pHYs   MiCCPPhotoshop ICC profilexڝSwX>eVBl"#Ya@Ņ VHUĂ H(gAZU\8ܧ}zy&j9R<:OHɽH gyx~t?op.$P&W " R.TSd ly|B" I>ةآ(G$@`UR,@".Y2GvX@`B, 8C L0ҿ_pH˕͗K3w!lBa)f "#HL 8?flŢko">!N_puk[Vh]3 Z zy8@P< %b0>3o~@zq@qanvRB1n#Dž)4\,XP"MyRD!ɕ2 w ONl~Xv@~- g42y@+͗\LD*A aD@ $<B AT:18 \p` Aa!:b""aH4 Q"rBj]H#-r9\@ 2G1Qu@Ơst4]k=Kut}c1fa\E`X&cX5V5cX7va$^lGXLXC%#W 1'"O%zxb:XF&!!%^'_H$ɒN !%2I IkHH-S>iL&m O:ňL $RJ5e?2BQͩ:ZImvP/S4u%͛Cˤ-Кigih/t ݃EЗkw Hb(k{/LӗT02goUX**|:V~TUsU?y TU^V}FUP թU6RwRPQ__c FHTc!2eXBrV,kMb[Lvv/{LSCsfffqƱ9ٜJ! {--?-jf~7zھbrup@,:m:u 6Qu>cy Gm7046l18c̐ckihhI'&g5x>fob4ekVyVV׬I\,mWlPW :˶vm))Sn1 9a%m;t;|rtuvlp4éĩWggs5KvSmnz˕ҵܭm=}M.]=AXq㝧/^v^Y^O&0m[{`:>=e>>z"=#~~~;yN`k5/ >B Yroc3g,Z0&L~oL̶Gli})*2.QStqt,֬Yg񏩌;jrvgjlRlc웸xEt$ =sl3Ttcܢ˞w|/%ҟ3gAMA|Q cHRMz%u0`:o_FvIDATxڤKhg\LSRhWEP6% M(6 VPTTЋ6mM(H{Uq#H HP9IN7Ec@Jf3 m ;aSxT'qL43* 56\)lJ9$!Q4l΂x UZWe0!k68h8o 3 |^IENDB`swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXRadioGroupBeanInfo.java0000644000175000017500000000225011210401722025272 0ustar tonytony/* * $Id: JXRadioGroupBeanInfo.java,v 1.3 2006/03/16 22:53:56 rbair Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; /** * * @author rbair */ public class JXRadioGroupBeanInfo extends BeanInfoSupport { public JXRadioGroupBeanInfo() { super(JXRadioGroup.class); } protected void initialize() { } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXTitledSeparatorBeanInfo.java0000644000175000017500000000463211210401722026333 0ustar tonytony/* * $Id: JXTitledSeparatorBeanInfo.java,v 1.7 2007/12/14 16:25:58 stolis Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.beans.BeanDescriptor; import javax.swing.SwingConstants; /** * BeanInfo class for JXTitledSeparator. * * @author rbair, Jan Stola */ public class JXTitledSeparatorBeanInfo extends BeanInfoSupport { public JXTitledSeparatorBeanInfo() { super(JXTitledSeparator.class); } protected void initialize() { String iconName = "resources/" + JXTitledSeparator.class.getSimpleName(); setSmallMonoIconName(iconName + "16.png"); setMonoIconName(iconName + "32.png"); BeanDescriptor bd = getBeanDescriptor(); bd.setValue("isContainer", Boolean.FALSE); setPreferred(true, "icon", "title", "horizontalAlignment", "horizontalTextPosition"); setPreferred(false, "alpha", "inheritAlpha"); setPreferred(false, "background", "backgroundPainter"); setPreferred(false, "border", "opaque"); setEnumerationValues(new EnumerationValue[] { new EnumerationValue("Center", SwingConstants.CENTER, "SwingConstants.CENTER"), new EnumerationValue("Leading", SwingConstants.LEADING, "SwingConstants.LEADING"), new EnumerationValue("Left", SwingConstants.LEFT, "SwingConstants.LEFT"), new EnumerationValue("Right", SwingConstants.RIGHT, "SwingConstants.RIGHT"), new EnumerationValue("Trailing", SwingConstants.TRAILING, "SwingConstants.TRAILING") }, "horizontalAlignment", "horizontalTextPosition"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXDialogBeanInfo.java0000644000175000017500000000223011210401722024414 0ustar tonytony/* * $Id: JXDialogBeanInfo.java,v 1.3 2006/03/16 22:53:55 rbair Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; /** * * @author rbair */ public class JXDialogBeanInfo extends BeanInfoSupport { public JXDialogBeanInfo() { super(JXDialog.class); } protected void initialize() { } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXFrameBeanInfo.java0000644000175000017500000000330011210401722024246 0ustar tonytony/* * $Id: JXFrameBeanInfo.java,v 1.4 2007/12/11 16:50:12 stolis Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import org.jdesktop.swingx.editors.EnumPropertyEditor; /** * BeanInfo class for JXFrame. * * @author rbair, Jan Stola */ public class JXFrameBeanInfo extends BeanInfoSupport { public JXFrameBeanInfo() { super(JXFrame.class); } protected void initialize() { setPreferred(true, "cancelButton", "defaultButton"); setPreferred(true, "startPosition"); setPropertyEditor(StartPositionPropertyEditor.class, "startPosition"); setHidden(true, "statusBar", "toolBar"); } public static final class StartPositionPropertyEditor extends EnumPropertyEditor { public StartPositionPropertyEditor() { super(JXFrame.StartPosition.class); } } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/JXButtonBeanInfo.java0000644000175000017500000000053211210401722024473 0ustar tonytonypackage org.jdesktop.swingx; /** * BeanInfo class for JXButton. * * @author Jan Stola */ public class JXButtonBeanInfo extends BeanInfoSupport { public JXButtonBeanInfo() { super(JXButton.class); } protected void initialize() { setPreferred(true, "backgroundPainter", "foregroundPainter"); } } swingx-1.0-src/src/beaninfo/org/jdesktop/swingx/URLPainter.java0000644000175000017500000000526511210401722023351 0ustar tonytony/* * $Id: URLPainter.java,v 1.1 2007/03/15 22:56:15 joshy Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.Graphics2D; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import org.jdesktop.swingx.editors.PainterUtil; import org.jdesktop.swingx.painter.*; /** * * @author joshy */ public class URLPainter extends CompoundPainter { URL url; /** * Creates a new instance of URLPainter */ public URLPainter() { this.url = null; } public URLPainter(URL url) { this.url = url; } public URLPainter(File file) { try { this.url = file.toURI().toURL(); } catch (MalformedURLException exception) { exception.printStackTrace(); this.url = null; } } public URLPainter(String url) { try { this.url = new URL(url); } catch (MalformedURLException ex) { ex.printStackTrace(); this.url = null; } } public URLPainter(Class baseClass, String resource) { url = baseClass.getResource(resource); } public void setURL(URL url) { URL old = this.url; this.url = url; firePropertyChange("file", old, this.url); } public URL getURL() { return this.url; } private boolean loaded = false; private void load() { try { Painter painter = PainterUtil.loadPainter(url); this.setPainters(painter); loaded = true; } catch (Exception ex) { ex.printStackTrace(); } } @Override public void doPaint(Graphics2D g, Object component, int width, int height) { if(!loaded) { load(); } super.doPaint(g, component, width, height); } } swingx-1.0-src/src/test/0000755000175000017500000000000011210401732013757 5ustar tonytonyswingx-1.0-src/src/test/treeTableData.xml0000644000175000017500000000614711210401722017211 0ustar tonytony Foo 1 Bar 1 Baz 1 Foo 2 Bar 2 Baz 2 Foo 3 Bar 3 Baz 3 Foo 4 Bar 4 Baz 4 Foo 5 Bar 5 Baz 5 Foo 6 Bar 6 Baz 6 Foo 7 Bar 7 Baz 7 Foo 8 Bar 8 Baz 8 Foo 9 Bar 9 Baz 9 Foo 10 Bar 10 Baz 10 Foo 11 Bar 11 Baz 11 swingx-1.0-src/src/test/org/0000755000175000017500000000000011210401724014547 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/0000755000175000017500000000000011210401732016371 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/0000755000175000017500000000000011210401736017714 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/rollover/0000755000175000017500000000000011210401726021557 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/rollover/RolloverTest.java0000644000175000017500000001671111210401722025070 0ustar tonytony/* * Created on 06.10.2005 * */ package org.jdesktop.swingx.rollover; import java.awt.Color; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.AbstractListModel; import javax.swing.Action; import javax.swing.JPopupMenu; import javax.swing.JTree; import javax.swing.ListModel; import javax.swing.table.TableModel; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXList; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTree; import org.jdesktop.swingx.JXTreeTable; import org.jdesktop.swingx.decorator.ColorHighlighter; import org.jdesktop.swingx.decorator.CompoundHighlighter; import org.jdesktop.swingx.decorator.HighlightPredicate; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.test.AncientSwingTeam; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; @RunWith(JUnit4.class) public class RolloverTest extends InteractiveTestCase { /** * @param args */ public static void main(String[] args) { RolloverTest test = new RolloverTest(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Rend.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } private TableModel sortableTableModel; private Highlighter backgroundHighlighter; private Highlighter foregroundHighlighter; private ListModel listModel; private FileSystemModel treeTableModel; @Test public void testDummy() { } //---------------------------- interactive tests of rollover effects public void interactiveTableRollover() { JXTable table = new JXTable(sortableTableModel); final CompoundHighlighter compoundHighlighter = new CompoundHighlighter(foregroundHighlighter); table.setHighlighters(compoundHighlighter); JXFrame frame = wrapWithScrollingInFrame(table, "Table with rollover"); Action toggleAction = new AbstractAction("toggle foreground/background") { boolean isBackground; public void actionPerformed(ActionEvent e) { if (isBackground) { compoundHighlighter.addHighlighter(foregroundHighlighter); compoundHighlighter.removeHighlighter(backgroundHighlighter); } else { compoundHighlighter.addHighlighter(backgroundHighlighter); compoundHighlighter.removeHighlighter(foregroundHighlighter); } isBackground = !isBackground; } }; addAction(frame, toggleAction); frame.setVisible(true); } public void interactiveListRollover() { final JXList table = new JXList(listModel); table.setRolloverEnabled(true); final CompoundHighlighter compoundHighlighter = new CompoundHighlighter(foregroundHighlighter); table.setHighlighters(compoundHighlighter); JXFrame frame = wrapWithScrollingInFrame(table, "List with rollover"); Action toggleAction = new AbstractAction("toggle foreground/background") { boolean isBackground; public void actionPerformed(ActionEvent e) { if (isBackground) { compoundHighlighter.addHighlighter(foregroundHighlighter); compoundHighlighter.removeHighlighter(backgroundHighlighter); } else { compoundHighlighter.addHighlighter(backgroundHighlighter); compoundHighlighter.removeHighlighter(foregroundHighlighter); } isBackground = !isBackground; } }; addAction(frame, toggleAction); frame.setVisible(true); } public void interactiveTreeRollover() { final JXTree table = new JXTree(treeTableModel); table.setRolloverEnabled(true); table.setComponentPopupMenu(createPopup()); final CompoundHighlighter compoundHighlighter = new CompoundHighlighter(foregroundHighlighter); table.setHighlighters(compoundHighlighter); JTree tree = new JTree(treeTableModel); tree.setComponentPopupMenu(createPopup()); JXFrame frame = wrapWithScrollingInFrame(table, tree, "JXTree (at left) with rollover"); Action toggleAction = new AbstractAction("toggle foreground/background") { boolean isBackground; public void actionPerformed(ActionEvent e) { if (isBackground) { compoundHighlighter.addHighlighter(foregroundHighlighter); compoundHighlighter.removeHighlighter(backgroundHighlighter); } else { compoundHighlighter.addHighlighter(backgroundHighlighter); compoundHighlighter.removeHighlighter(foregroundHighlighter); } isBackground = !isBackground; } }; addAction(frame, toggleAction); addMessage(frame, "background highlight not working in JXTree"); frame.setVisible(true); } public JPopupMenu createPopup() { JPopupMenu popup = new JPopupMenu(); popup.add("dummy"); return popup; } public void interactiveTreeTableRollover() { final JXTreeTable table = new JXTreeTable(treeTableModel); table.setRolloverEnabled(true); final CompoundHighlighter compoundHighlighter = new CompoundHighlighter(foregroundHighlighter); table.setHighlighters(compoundHighlighter); JXFrame frame = wrapWithScrollingInFrame(table, "Table with rollover"); Action toggleAction = new AbstractAction("toggle foreground/background") { boolean isBackground; public void actionPerformed(ActionEvent e) { if (isBackground) { compoundHighlighter.addHighlighter(foregroundHighlighter); compoundHighlighter.removeHighlighter(backgroundHighlighter); } else { compoundHighlighter.addHighlighter(backgroundHighlighter); compoundHighlighter.removeHighlighter(foregroundHighlighter); } isBackground = !isBackground; } }; addAction(frame, toggleAction); frame.setVisible(true); } @Override protected void setUp() throws Exception { super.setUp(); sortableTableModel = new AncientSwingTeam(); listModel = new AbstractListModel() { public int getSize() { return sortableTableModel.getRowCount(); } public Object getElementAt(int index) { return sortableTableModel.getValueAt(index, 0); } }; treeTableModel = new FileSystemModel(); foregroundHighlighter = new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW, null, Color.MAGENTA); backgroundHighlighter = new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW, Color.YELLOW, null); } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/0000755000175000017500000000000011210401736021676 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/decorator/ComponentAdapterTest.java0000644000175000017500000006711711210401722026653 0ustar tonytony/* * $Id: ComponentAdapterTest.java,v 1.10 2008/12/23 18:12:38 kschaefe Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.decorator; import java.awt.Color; import javax.swing.ListModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeModel; import junit.framework.TestCase; import org.jdesktop.swingx.JXList; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTree; import org.jdesktop.swingx.JXTreeTable; import org.jdesktop.swingx.renderer.DefaultListRenderer; import org.jdesktop.swingx.renderer.DefaultTableRenderer; import org.jdesktop.swingx.renderer.DefaultTreeRenderer; import org.jdesktop.swingx.renderer.StringValue; import org.jdesktop.swingx.renderer.StringValues; import org.jdesktop.swingx.treetable.TreeTableModel; import org.jdesktop.test.AncientSwingTeam; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * Test ComponentAdapter. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class ComponentAdapterTest extends TestCase { /** * A custom StringValue for Color. Maps to a string composed of the * prefix "R/G/B: " and the Color's rgb value. */ private StringValue sv; @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } /** * Issue #791-swingx: complete coordinate transformation methods - missing id --> index * * Tree has no columns/identifiers - implement reasonable default. */ @Test public void testColumnIdentifierAtList() { JXListT tree = new JXListT(new String[] {"one" }); ComponentAdapter adapter = tree.getComponentAdapter(0); assertEquals(ComponentAdapter.DEFAULT_COLUMN_IDENTIFIER, adapter.getColumnIdentifierAt(0)); } /** * Issue #791-swingx: complete coordinate transformation methods - missing id --> index * * Here test contract: must throw IllegalArgumentException if invalid index. */ @Test public void testColumnIdentifierAtListInvalidIndex() { JXListT table = new JXListT(new String[] {"one" }); ComponentAdapter adapter = table.getComponentAdapter(0); try { adapter.getColumnIdentifierAt(adapter.getColumnCount()); fail("must throw at invalid columnIndex: " + adapter.getColumnCount()); } catch (ArrayIndexOutOfBoundsException e) { // behaves as documented } catch (Exception e) { fail("expected ArrayIndexOutOfBounds but was: " + e); } } /** * Issue #791-swingx: complete coordinate transformation methods - missing id --> index * * Here test contract: must throw NPE if nullIdentifier. */ @Test public void testColumnIdentifierReverseListNullIdentifier() { JXListT table = new JXListT(new String[] {"one" }); ComponentAdapter adapter = table.getComponentAdapter(0); try { adapter.getColumnIndex(null); fail("must throw at invalid columnIndex: " + adapter.getColumnCount()); } catch (NullPointerException e) { // behaves as documented } catch (Exception e) { fail("expected ArrayIndexOutOfBounds but was: " + e); } } /** * Issue #791-swingx: complete coordinate transformation methods - missing id --> index * * Tree has no columns/identifiers - implement reasonable default. */ @Test public void testColumnIdentifierListReverse() { JXListT tree = new JXListT(new String[] {"one" }); ComponentAdapter adapter = tree.getComponentAdapter(0); assertEquals(0, adapter.getColumnIndex(ComponentAdapter.DEFAULT_COLUMN_IDENTIFIER)); } /** * Issue #791-swingx: complete coordinate transformation methods - missing id --> index * * Tree has no columns/identifiers - implement reasonable default. */ @Test public void testColumnIdentifierListNotFound() { JXListT tree = new JXListT(new String[] {"one" }); ComponentAdapter adapter = tree.getComponentAdapter(0); assertEquals(-1, adapter.getColumnIndex("unknown")); } /** * Issue #791-swingx: complete coordinate transformation methods - missing id --> index * * Tree has no columns/identifiers - implement reasonable default. */ @Test public void testColumnIdentifierAtTree() { JXTreeT tree = new JXTreeT(); ComponentAdapter adapter = tree.getComponentAdapter(0); assertEquals(ComponentAdapter.DEFAULT_COLUMN_IDENTIFIER, adapter.getColumnIdentifierAt(0)); } /** * Issue #791-swingx: complete coordinate transformation methods - missing id --> index * * Here test contract: must throw IllegalArgumentException if invalid index. */ @Test public void testColumnIdentifierAtTreeInvalidIndex() { JXTreeT table = new JXTreeT(); ComponentAdapter adapter = table.getComponentAdapter(0); try { adapter.getColumnIdentifierAt(adapter.getColumnCount()); fail("must throw at invalid columnIndex: " + adapter.getColumnCount()); } catch (ArrayIndexOutOfBoundsException e) { // behaves as documented } catch (Exception e) { fail("expected ArrayIndexOutOfBounds but was: " + e); } } /** * Issue #791-swingx: complete coordinate transformation methods - missing id --> index * * Here test contract: must throw NPE if nullIdentifier. */ @Test public void testColumnIdentifierReverseTreeNullIdentifier() { JXTreeT table = new JXTreeT(); ComponentAdapter adapter = table.getComponentAdapter(0); try { adapter.getColumnIndex(null); fail("must throw at invalid columnIndex: " + adapter.getColumnCount()); } catch (NullPointerException e) { // behaves as documented } catch (Exception e) { fail("expected ArrayIndexOutOfBounds but was: " + e); } } /** * Issue #791-swingx: complete coordinate transformation methods - missing id --> index * * Tree has no columns/identifiers - implement reasonable default. */ @Test public void testColumnIdentifierTreeReverse() { JXTreeT tree = new JXTreeT(); ComponentAdapter adapter = tree.getComponentAdapter(0); assertEquals(0, adapter.getColumnIndex(ComponentAdapter.DEFAULT_COLUMN_IDENTIFIER)); } /** * Issue #791-swingx: complete coordinate transformation methods - missing id --> index * * Tree has no columns/identifiers - implement reasonable default. */ @Test public void testColumnIdentifierTreeNotFound() { JXTreeT tree = new JXTreeT(); ComponentAdapter adapter = tree.getComponentAdapter(0); assertEquals(-1, adapter.getColumnIndex("unknown")); } /** * Issue #791-swingx: complete coordinate transformation methods - missing id --> index * * Here: must return model index for hidden columns */ @Test public void testColumnIdentifierReverseHidden() { JXTableT table = new JXTableT(new AncientSwingTeam()); ComponentAdapter adapter = table.getComponentAdapter(0, 0); Object id = new Integer(50); table.getColumn(1).setIdentifier(id); table.getColumnExt(1).setVisible(false); assertEquals(1, adapter.getColumnIndex(id)); } /** * Issue #791-swingx: complete coordinate transformation methods - missing id --> index * * Here: must return model index */ @Test public void testColumnIdentifierReverse() { JXTableT table = new JXTableT(new AncientSwingTeam()); ComponentAdapter adapter = table.getComponentAdapter(0, 0); Object id = new Integer(50); table.getColumn(1).setIdentifier(id); assertEquals(1, adapter.getColumnIndex(id)); } /** * Issue #791-swingx: complete coordinate transformation methods - missing id --> index * * Here: must return model index if identifier not known. */ @Test public void testColumnIdentifierReverseNotFound() { JXTableT table = new JXTableT(new AncientSwingTeam()); ComponentAdapter adapter = table.getComponentAdapter(0, 0); Object id = new Integer(50); table.getColumn(1).setIdentifier(id); assertEquals(-1, adapter.getColumnIndex("unknown")); } /** * Issue #791-swingx: complete coordinate transformation methods - missing id --> index * * Here test contract: must throw IllegalArgumentException if invalid index. */ @Test public void testColumnIdentifierAtInvalidIndex() { JXTableT table = new JXTableT(new AncientSwingTeam()); ComponentAdapter adapter = table.getComponentAdapter(0, 0); try { adapter.getColumnIdentifierAt(adapter.getColumnCount()); fail("must throw at invalid columnIndex: " + adapter.getColumnCount()); } catch (ArrayIndexOutOfBoundsException e) { // behaves as documented } catch (Exception e) { fail("expected ArrayIndexOutOfBounds but was: " + e); } } /** * Issue #791-swingx: complete coordinate transformation methods - missing id --> index * * Here test contract: must throw NPE if Null identifier. */ @Test public void testColumnIdentifierReverseNullIdentifier() { JXTableT table = new JXTableT(new AncientSwingTeam()); ComponentAdapter adapter = table.getComponentAdapter(0, 0); try { adapter.getColumnIndex(null); fail("must throw for null identifier"); } catch (NullPointerException e) { // behaves as documented } catch (Exception e) { fail("expected ArrayIndexOutOfBounds but was: " + e); } } /** * Issue #791-swingx: complete coordinate transformation methods - missing id --> index * * */ @Test public void testColumnIdentifierAt() { JXTableT table = new JXTableT(new AncientSwingTeam()); ComponentAdapter adapter = table.getComponentAdapter(0, 0); Object id = new Integer(50); table.getColumn(0).setIdentifier(id); assertEquals(table.getColumn(0).getIdentifier(), adapter.getColumnIdentifierAt(0)); // this fails because the adapter returns a string representation of the identifier // assertEquals(table.getColumn(0).getIdentifier(), adapter.getColumnIdentifier(0)); } /** * Issue #821-swingx: JXTreeTable broken string rep of hierarchical column * * here: test ComponentAdapter on hidden hierarchical column */ @Test public void testTreeTableGetStringColumnHiddenHierarchicalColumn() { JXTreeTableT table = new JXTreeTableT(AncientSwingTeam.createNamedColorTreeTableModel()); table.setTreeCellRenderer(new DefaultTreeRenderer(sv)); table.getColumnExt(0).setVisible(false); String text = sv.getString(table.getModel().getValueAt(2, 0)); ComponentAdapter adapter = table.getComponentAdapter(2, 0); assertEquals(text, adapter.getString(0)); } /** * Issue #821-swingx: JXTreeTable broken string rep of hierarchical column * * here: test ComponentAdapter on hidden hierarchical column */ @Test public void testTreeTableGetStringAtHiddenHierarchicalColumn() { JXTreeTableT table = new JXTreeTableT(AncientSwingTeam.createNamedColorTreeTableModel()); table.setTreeCellRenderer(new DefaultTreeRenderer(sv)); table.getColumnExt(0).setVisible(false); String text = sv.getString(table.getModel().getValueAt(2, 0)); ComponentAdapter adapter = table.getComponentAdapter(2, 0); assertEquals(text, adapter.getStringAt(2, 0)); } /** * Issue #767-swingx: consistent string representation. * * Here: test api on tree's ComponentAdapter. */ @Test public void testTreeGetStringAt() { JXTreeT tree = new JXTreeT(AncientSwingTeam.createNamedColorTreeModel()); tree.expandAll(); tree.setCellRenderer(new DefaultTreeRenderer(sv)); String text = sv.getString(((DefaultMutableTreeNode) tree.getPathForRow(2).getLastPathComponent()).getUserObject()); ComponentAdapter adapter = tree.getComponentAdapter(2); assertEquals(text, adapter.getStringAt(2, 0)); } /** * Issue #767-swingx: consistent string representation. * * Here: test api on tree's ComponentAdapter. */ @Test public void testTreeGetString() { JXTreeT tree = new JXTreeT(AncientSwingTeam.createNamedColorTreeModel()); tree.expandAll(); tree.setCellRenderer(new DefaultTreeRenderer(sv)); String text = sv.getString(((DefaultMutableTreeNode) tree.getPathForRow(2).getLastPathComponent()).getUserObject()); ComponentAdapter adapter = tree.getComponentAdapter(2); assertEquals(text, adapter.getString()); } /** * Issue #767-swingx: consistent string representation. * * Here: test api on tree's ComponentAdapter. */ @Test public void testTreeGetFilteredString() { JXTreeT tree = new JXTreeT(AncientSwingTeam.createNamedColorTreeModel()); tree.expandAll(); tree.setCellRenderer(new DefaultTreeRenderer(sv)); String text = sv.getString(((DefaultMutableTreeNode) tree.getPathForRow(2).getLastPathComponent()).getUserObject()); ComponentAdapter adapter = tree.getComponentAdapter(2); assertEquals(text, adapter.getFilteredStringAt(2, 0)); } /** * Issue #767-swingx: consistent string representation. * * Here: test api on tree's ComponentAdapter. */ @Test public void testTreeGetStringColumn() { JXTreeT tree = new JXTreeT(AncientSwingTeam.createNamedColorTreeModel()); tree.expandAll(); tree.setCellRenderer(new DefaultTreeRenderer(sv)); String text = sv.getString(((DefaultMutableTreeNode) tree.getPathForRow(2).getLastPathComponent()).getUserObject()); ComponentAdapter adapter = tree.getComponentAdapter(2); assertEquals(text, adapter.getString(0)); } /** * Subclass to access ComponentAdapter. */ public static class JXTreeT extends JXTree { public JXTreeT(TreeModel model) { super(model); } public JXTreeT() { super(); } @Override public ComponentAdapter getComponentAdapter(int row) { return super.getComponentAdapter(row); } } /** * Issue #767-swingx: consistent string representation. * * Here: test api on list's ComponentAdapter. */ @Test public void testListGetStringAtSorted() { JXListT list = new JXListT(AncientSwingTeam.createNamedColorListModel()); list.setFilterEnabled(true); list.setCellRenderer(new DefaultListRenderer(sv)); list.toggleSortOrder(); String text = sv.getString(list.getWrappedModel().getElementAt(2)); ComponentAdapter adapter = list.getComponentAdapter(2); assertEquals(text, adapter.getStringAt(2, 0)); } /** * Issue #767-swingx: consistent string representation. * * Here: test api on list's ComponentAdapter. */ @Test public void testListGetStringAtUnsorted() { JXListT list = new JXListT(AncientSwingTeam.createNamedColorListModel()); list.setCellRenderer(new DefaultListRenderer(sv)); String text = sv.getString(list.getElementAt(2)); ComponentAdapter adapter = list.getComponentAdapter(2); assertEquals(text, adapter.getStringAt(2, 0)); } /** * Issue #767-swingx: consistent string representation. * * Here: test api on list's ComponentAdapter. */ @Test public void testListGetString() { JXListT list = new JXListT(AncientSwingTeam.createNamedColorListModel()); list.setCellRenderer(new DefaultListRenderer(sv)); String text = sv.getString(list.getElementAt(2)); ComponentAdapter adapter = list.getComponentAdapter(2); assertEquals(text, adapter.getString()); } /** * Issue #767-swingx: consistent string representation. * * Here: test api on list's ComponentAdapter. */ @Test public void testListGetFilteredString() { JXListT list = new JXListT(AncientSwingTeam.createNamedColorListModel()); list.setCellRenderer(new DefaultListRenderer(sv)); String text = sv.getString(list.getElementAt(2)); ComponentAdapter adapter = list.getComponentAdapter(2); assertEquals(text, adapter.getFilteredStringAt(2, 0)); } /** * Issue #767-swingx: consistent string representation. * * Here: test api on list's ComponentAdapter. */ @Test public void testListGetStringColumn() { JXListT list = new JXListT(AncientSwingTeam.createNamedColorListModel()); list.setCellRenderer(new DefaultListRenderer(sv)); String text = sv.getString(list.getElementAt(2)); ComponentAdapter adapter = list.getComponentAdapter(2); assertEquals(text, adapter.getString(0)); } /** * Subclass to access ComponentAdapter. */ public static class JXListT extends JXList { public JXListT(ListModel model) { super(model); } public JXListT(Object[] data) { super(data); } @Override public ComponentAdapter getComponentAdapter(int row) { return super.getComponentAdapter(row); } } /** * Issue #767-swingx: consistent string representation. * * Here: test api on table's ComponentAdapter. */ @Test public void testTableGetStringColumnHiddenColumn() { JXTableT table = new JXTableT(new AncientSwingTeam()); table.setDefaultRenderer(Color.class, new DefaultTableRenderer(sv)); table.getColumnExt(2).setVisible(false); String text = sv.getString(table.getModel().getValueAt(2, 2)); ComponentAdapter adapter = table.getComponentAdapter(2, 2); assertEquals(text, adapter.getString(2)); } /** * Issue #767-swingx: consistent string representation. * * Here: test api on table's ComponentAdapter. */ @Test public void testTableGetStringAtHiddenColumn() { JXTableT table = new JXTableT(new AncientSwingTeam()); table.setDefaultRenderer(Color.class, new DefaultTableRenderer(sv)); table.getColumnExt(2).setVisible(false); String text = sv.getString(table.getModel().getValueAt(2, 2)); ComponentAdapter adapter = table.getComponentAdapter(2, 2); assertEquals(text, adapter.getStringAt(2, 2)); } /** * Issue #767-swingx: consistent string representation. * * Here: test api on table's ComponentAdapter. */ @Test public void testTableGetStringAtSorted() { JXTableT table = new JXTableT(new AncientSwingTeam()); table.setDefaultRenderer(Color.class, new DefaultTableRenderer(sv)); table.toggleSortOrder(2); String text = sv.getString(table.getModel().getValueAt(2, 2)); ComponentAdapter adapter = table.getComponentAdapter(2, 2); assertEquals(text, adapter.getStringAt(2, 2)); } /** * Issue #767-swingx: consistent string representation. * * Here: test api on table's ComponentAdapter. */ @Test public void testTableGetStringAtUnsorted() { JXTableT table = new JXTableT(new AncientSwingTeam()); table.setDefaultRenderer(Color.class, new DefaultTableRenderer(sv)); String text = sv.getString(table.getValueAt(2, 2)); ComponentAdapter adapter = table.getComponentAdapter(2, 2); assertEquals(text, adapter.getStringAt(2, 2)); } /** * Issue #767-swingx: consistent string representation. * * Here: test api on table's ComponentAdapter. */ @Test public void testTableGetString() { JXTableT table = new JXTableT(new AncientSwingTeam()); table.setDefaultRenderer(Color.class, new DefaultTableRenderer(sv)); String text = sv.getString(table.getValueAt(2, 2)); ComponentAdapter adapter = table.getComponentAdapter(2, 2); assertEquals(text, adapter.getString()); } /** * Issue #767-swingx: consistent string representation. * * Here: test api on table's ComponentAdapter. */ @Test public void testTableGetFilteredString() { JXTableT table = new JXTableT(new AncientSwingTeam()); table.setDefaultRenderer(Color.class, new DefaultTableRenderer(sv)); String text = sv.getString(table.getValueAt(2, 2)); ComponentAdapter adapter = table.getComponentAdapter(2, 2); assertEquals(text, adapter.getFilteredStringAt(2, 2)); } /** * Issue #767-swingx: consistent string representation. * * Here: test api on table's ComponentAdapter. */ @Test public void testTableGetStringColumn() { JXTableT table = new JXTableT(new AncientSwingTeam()); table.setDefaultRenderer(Color.class, new DefaultTableRenderer(sv)); String text = sv.getString(table.getValueAt(2, 2)); ComponentAdapter adapter = table.getComponentAdapter(2, 2); assertEquals(text, adapter.getString(2)); } /** * Overridden to get access to componentAdapter. * */ public static class JXTableT extends JXTable { public JXTableT(TableModel model) { super(model); } @Override public ComponentAdapter getComponentAdapter(int row, int column) { return super.getComponentAdapter(row, column); } } /** * Overridden to get access to componentAdapter. * */ public static class JXTreeTableT extends JXTreeTable { public JXTreeTableT(TreeTableModel model) { super(model); } @Override public ComponentAdapter getComponentAdapter(int row, int column) { return super.getComponentAdapter(row, column); } } /** * Issue #??- ComponentAdapter's default implementation does not * return the value at the adapter's view state. * * Clarified the documentation: the assumption for the base implementation * is that model coordinates == view coordinates, that is it's up to * subclasses to implement the model correctly if they support different * coordinate systems. * */ @Test public void testComponentAdapterCoordinates() { final JXTable table = new JXTable(createAscendingModel(0, 10)); Object originalFirstRowValue = table.getValueAt(0,0); Object originalLastRowValue = table.getValueAt(table.getRowCount() - 1, 0); assertEquals("view row coordinate equals model row coordinate", table.getModel().getValueAt(0, 0), originalFirstRowValue); // sort first column - actually does not change anything order table.toggleSortOrder(0); // sanity asssert assertEquals("view order must be unchanged ", table.getValueAt(0, 0), originalFirstRowValue); // invert sort table.toggleSortOrder(0); // sanity assert assertEquals("view order must be reversed changed ", table.getValueAt(0, 0), originalLastRowValue); ComponentAdapter adapter = new ComponentAdapter(table) { @Override public Object getColumnIdentifierAt(int columnIndex) { // TODO Auto-generated method stub return null; } @Override public int getColumnIndex(Object identifier) { // TODO Auto-generated method stub return 0; } @Override public String getColumnName(int columnIndex) { return null; } /** * {@inheritDoc} */ @Override public Object getFilteredValueAt(int row, int column) { return getValueAt(table.convertRowIndexToModel(row), column); } @Override public Object getValueAt(int row, int column) { return table.getModel().getValueAt(row, column); } @Override public Object getValue() { return getValueAt(table.convertRowIndexToModel(row), viewToModel(column)); } @Override public boolean hasFocus() { return false; } @Override public boolean isCellEditable(int row, int column) { return false; } @Override public boolean isEditable() { return false; } @Override public boolean isSelected() { return false; } @Override public void setValueAt(Object aValue, int row, int column) { } }; assertEquals("adapter filteredValue expects row view coordinates", table.getValueAt(0, 0), adapter.getFilteredValueAt(0, 0)); // adapter coordinates are view coordinates adapter.row = 0; adapter.column = 0; assertEquals("adapter.getValue must return value at adapter coordinates", table.getValueAt(0, 0), adapter.getValue()); assertEquals(adapter.getFilteredValueAt(0, adapter.getColumnCount() -1), adapter.getValue(adapter.getColumnCount()-1)); } private DefaultTableModel createAscendingModel(int startRow, int count) { DefaultTableModel model = new DefaultTableModel(count, 5); for (int i = 0; i < model.getRowCount(); i++) { model.setValueAt(new Integer(startRow++), i, 0); } return model; } /** * Creates and returns a StringValue which maps a Color to it's R/G/B rep, * prepending "R/G/B: " * * @return the StringValue for color. */ private StringValue createColorStringValue() { StringValue sv = new StringValue() { public String getString(Object value) { if (value instanceof Color) { Color color = (Color) value; return "R/G/B: " + color.getRGB(); } return StringValues.TO_STRING.getString(value); } }; return sv; } @Override protected void setUp() throws Exception { sv = createColorStringValue(); } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/TableColumnExtAsHighlighterClientTest.java0000644000175000017500000000631311210401722032067 0ustar tonytony/* * $Id: TableColumnExtAsHighlighterClientTest.java,v 1.3 2008/10/11 20:42:31 rah003 Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.decorator; import java.awt.Color; import java.beans.PropertyChangeListener; import org.jdesktop.swingx.table.TableColumnExt; import org.jdesktop.test.PropertyChangeReport; import org.jdesktop.test.TestUtils; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * Test JXTable as HighlighterClient. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class TableColumnExtAsHighlighterClientTest extends AbstractTestHighlighterClient { @Test public void testHighlighterStateChangeNotification() { TableColumnExt columnExt = new TableColumnExt(); ColorHighlighter hl = new ColorHighlighter(); columnExt.addHighlighter(hl); PropertyChangeReport report = new PropertyChangeReport(); columnExt.addPropertyChangeListener(report); hl.setBackground(Color.RED); TestUtils.assertPropertyChangeEvent(report, "highlighterStateChanged", false, true); } @Override protected HighlighterClient createHighlighterClient() { return createHighlighterClient(new TableColumnExt()); } private HighlighterClient createHighlighterClient(final TableColumnExt table) { HighlighterClient client = new HighlighterClient() { public void addHighlighter(Highlighter highlighter) { table.addHighlighter(highlighter); } public void addPropertyChangeListener(PropertyChangeListener l) { table.addPropertyChangeListener(l); } public Highlighter[] getHighlighters() { return table.getHighlighters(); } public void removeHighlighter(Highlighter highlighter) { table.removeHighlighter(highlighter); } public void removePropertyChangeListener(PropertyChangeListener l) { table.removePropertyChangeListener(l); } public void setHighlighters(Highlighter... highlighters) { table.setHighlighters(highlighters); } public void updateUI() { table.updateUI(); } }; return client; } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/TreeAsHighlighterClientTest.java0000644000175000017500000000506711210401722030105 0ustar tonytony/* * $Id: TreeAsHighlighterClientTest.java,v 1.2 2008/10/11 20:42:31 rah003 Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.decorator; import java.beans.PropertyChangeListener; import org.jdesktop.swingx.JXTree; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * Test JXTree as HighlighterClient. * * @author Jeanette Winzenburg */ public class TreeAsHighlighterClientTest extends AbstractTestHighlighterClient { @Override protected HighlighterClient createHighlighterClient() { return createHighlighterClient(new JXTree()); } private HighlighterClient createHighlighterClient(final JXTree table) { HighlighterClient client = new HighlighterClient() { public void addHighlighter(Highlighter highlighter) { table.addHighlighter(highlighter); } public void addPropertyChangeListener(PropertyChangeListener l) { table.addPropertyChangeListener(l); } public Highlighter[] getHighlighters() { return table.getHighlighters(); } public void removeHighlighter(Highlighter highlighter) { table.removeHighlighter(highlighter); } public void removePropertyChangeListener(PropertyChangeListener l) { table.removePropertyChangeListener(l); } public void setHighlighters(Highlighter... highlighters) { table.setHighlighters(highlighters); } public void updateUI() { table.updateUI(); } }; return client; } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/TableAsHighlighterClientTest.java0000644000175000017500000001032711210401722030230 0ustar tonytony/* * $Id: TableAsHighlighterClientTest.java,v 1.3 2009/01/27 11:09:16 kleopatra Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.decorator; import java.awt.Color; import java.beans.PropertyChangeListener; import java.util.logging.Logger; import javax.swing.UIManager; import javax.swing.table.TableColumn; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.table.TableColumnExt; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Test JXTable as HighlighterClient. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class TableAsHighlighterClientTest extends AbstractTestHighlighterClient { @SuppressWarnings("unused") private static final Logger LOG = Logger .getLogger(TableAsHighlighterClientTest.class.getName()); /** * Test that columnHighlighters are updated. */ @Test public void testUpdateUIColumnHighlighters() { // force loading of striping colors ColorHighlighter colorHighlighter = (ColorHighlighter) HighlighterFactory.createSimpleStriping(); Color uiColor = UIManager.getColor("UIColorHighlighter.stripingBackground"); if (uiColor == null) { LOG.info("cannot run test - no ui striping color"); return; } assertSame("sanity", uiColor, colorHighlighter.getBackground()); JXTable client = new JXTable(10, 3); for (TableColumn tableColumn : client.getColumns(true)) { ((TableColumnExt) tableColumn).addHighlighter(HighlighterFactory.createSimpleStriping()); } Color changedUIColor = Color.RED; UIManager.put("UIColorHighlighter.stripingBackground", changedUIColor); client.updateUI(); try { for (TableColumn tableColumn : client.getColumns(true)) { Highlighter hl = ((TableColumnExt) tableColumn).getHighlighters()[0]; assertSame("support must update ui color", changedUIColor, ((ColorHighlighter) hl).getBackground()); } } finally { UIManager.put("UIColorHighlighter.stripingBackground", uiColor); } } @Override protected HighlighterClient createHighlighterClient() { return createHighlighterClient(new JXTable()); } private HighlighterClient createHighlighterClient(final JXTable table) { HighlighterClient client = new HighlighterClient() { public void addHighlighter(Highlighter highlighter) { table.addHighlighter(highlighter); } public void addPropertyChangeListener(PropertyChangeListener l) { table.addPropertyChangeListener(l); } public Highlighter[] getHighlighters() { return table.getHighlighters(); } public void removeHighlighter(Highlighter highlighter) { table.removeHighlighter(highlighter); } public void removePropertyChangeListener(PropertyChangeListener l) { table.removePropertyChangeListener(l); } public void setHighlighters(Highlighter... highlighters) { table.setHighlighters(highlighters); } public void updateUI() { table.updateUI(); } }; return client; } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/HighlighterIssues.java0000644000175000017500000003256411210401722026200 0ustar tonytony/* * Created on 14.10.2005 * */ package org.jdesktop.swingx.decorator; import java.awt.Color; import java.awt.Component; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Logger; import javax.swing.DefaultListModel; import javax.swing.JTable; import javax.swing.ListModel; import javax.swing.UIManager; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import org.jdesktop.swingx.JXEditorPaneTest; import org.jdesktop.swingx.JXList; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTree; import org.jdesktop.swingx.decorator.HighlighterFactory.UIColorHighlighter; import org.jdesktop.swingx.hyperlink.LinkModel; import org.jdesktop.swingx.renderer.DefaultTreeRenderer; import org.jdesktop.test.AncientSwingTeam; public class HighlighterIssues extends org.jdesktop.swingx.InteractiveTestCase { private static final Logger LOG = Logger.getLogger(HighlighterIssues.class .getName()); protected Color ledger = new Color(0xF5, 0xFF, 0xF5); protected Color background = Color.RED; protected Color foreground = Color.BLUE; protected ColorHighlighter emptyHighlighter; // flag used in setup to explicitly choose LF protected boolean defaultToSystemLF; public static void main(String args[]) { // setSystemLF(true); HighlighterIssues test = new HighlighterIssues(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } //---------------- uidependent /** * test if background changes with LF. * * PENDING: this is not entirely correct, might fail because * both LFs fall back to GenericGray. */ public void testLookupUIColor() { UIColorHighlighter hl = new UIColorHighlighter(); Color color = hl.getBackground(); String lf = UIManager.getLookAndFeel().getName(); Color uiColor = UIManager.getColor("UIColorHighlighter.stripingBackground"); assertNotNull(uiColor); // switch LF setSystemLF(!defaultToSystemLF); if (lf.equals(UIManager.getLookAndFeel().getName())) { LOG.info("cannot run lookupUIColor - same LF" + lf); return; } Color uiColor2 = UIManager.getColor("UIColorHighlighter.stripingBackground"); assertNotNull(uiColor2); // hmm ... how to force the reloading in the addon? LOG.info("color must be different " + uiColor + "/" + uiColor2); assertFalse("color must be different " + uiColor + "/" + uiColor2 , uiColor2.equals(uiColor)); hl.updateUI(); assertFalse("highlighter background must be changed", color.equals(hl.getBackground())); } /** * test if background changes with LF. * * PENDING: this is not entirely correct, might fail because * both LFs fall back to GenericGray. */ public void testLookupUIColorInCompound() { UIColorHighlighter hl = new UIColorHighlighter(); Color color = hl.getBackground(); CompoundHighlighter compound = new CompoundHighlighter(hl); String lf = UIManager.getLookAndFeel().getName(); // switch LF setSystemLF(!defaultToSystemLF); if (lf.equals(UIManager.getLookAndFeel().getName())) { LOG.info("cannot run lookupUIColor - same LF" + lf); return; } compound.updateUI(); assertFalse("highlighter background must be changed", color.equals(hl.getBackground())); } /** * Issue #258-swingx: DefaultTableCellRenderer has memory. * How to formulate as test? * this is testing the hack (reset the memory in ResetDTCR to null), not * any highlighter! */ public void testTableUnSelectedDoNothingHighlighter() { JXTable table = new JXTable(10, 2); DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); renderer.setForeground(foreground); table.setHighlighters(new ColorHighlighter()); Component comp = table.prepareRenderer(renderer, 0, 0); assertEquals("do nothing highlighter must not change foreground", foreground, comp.getForeground()); fail("testing the hack around DefaultTableCellRenderer memory - not the memory itself"); } //--------------- /** * Issue #258-swingx: Background LegacyHighlighter must not change custom * foreground. *

* * Visualizing effect of hack: table-internally, a ResetDTCRColorHighlighter * tries to neutralize DefaultTableCellRenderer's color memory. * *

    *
  • a DTCR subclass with value-based custom foreground *
  • the renderer is shared between a table with background highlighter * (alternateRowHighlighter) and a table without highlighter *
  • the custom value-based foreground must show in both * (AlternateRowHighlighter overwrite both striped and unstriped back) *
* * This behaves as expected after moving the hack to _before_ calling * super.prepareRenderer. */ public void interactiveTableCustomCoreRendererColorBasedOnValue() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); DefaultTableCellRenderer renderer = new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { // TODO Auto-generated method stub super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (!isSelected) { if (getText().contains("y")) { setForeground(Color.RED); } else { setForeground(Color.GREEN); } } return this; } }; table.addHighlighter( HighlighterFactory.createSimpleStriping(HighlighterFactory.GENERIC_GRAY)); table.setDefaultRenderer(Object.class, renderer); JXTable nohighlight = new JXTable(model); nohighlight.setDefaultRenderer(Object.class, renderer); showWithScrollingInFrame(table, nohighlight, "core - value-based fg renderer with bg highlighter <--> shared without highl"); } /** * Issue #258-swingx: Background LegacyHighlighter must not change custom * foreground. *

* * Visualizing effect of hack: table-internally, a ResetDTCRColorHighlighter * tries to neutralize DefaultTableCellRenderer's color memory. * *

    *
  • a DTCR with custom foreground and custom background *
  • the renderer is shared between a table with background highlighter * (alternateRowHighlighter) and a table without highlighter *
  • the custom foreground must show in both *
  • the custom background must show in the table without highlighter *
  • the custom background must not show in the table with highlighter * (AlternateRowHighlighter overwrite both striped and unstriped back) *
* */ public void interactiveTableCustomCoreRendererColor() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); renderer.setForeground(foreground); renderer.setBackground(background); table.addHighlighter( HighlighterFactory.createSimpleStriping(HighlighterFactory.GENERIC_GRAY)); table.setDefaultRenderer(Object.class, renderer); JXTable nohighlight = new JXTable(model); nohighlight.setDefaultRenderer(Object.class, renderer); showWithScrollingInFrame(table, nohighlight, "core: custom colored renderer with bg highlighter <--> shared without highl"); } /** * Issue #258-swingx: Background LegacyHighlighter must not change custom * foreground. *

* * Visualizing effect of hack: table-internally, a ResetDTCRColorHighlighter * tries to neutralize DefaultTableCellRenderer's color memory. * * Problem: if pre-hack-highlighting and selected on first rendering, * the renderer always uses the selection color. Bug in hacking highlighter? * Not much it can do about it: the hacking does not store the color if * the adapter isSelected - so in the next round the previously configured * color - which was for selected state - is stored as to color to restore to. *

* Arrggghhh... * */ public void interactiveTableCoreRendererFirstSelected() { TableModel model = new AncientSwingTeam(); DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); // JXTable table = new JXTable(model); // table.addHighlighter(AlternateRowHighlighter.genericGrey); // table.setDefaultRenderer(Object.class, renderer); JXTable nohighlight = new JXTable(model); nohighlight.setDefaultRenderer(Object.class, renderer); nohighlight.setRowSelectionInterval(0, 0); // showWithScrollingInFrame(table, nohighlight, showWithScrollingInFrame(nohighlight, "core: very first match is against selected"); } /** * UIHighlighter: check if highlighter is updated when toggling LF. */ public void interactiveUITableWithAlternateRow() { JXTable table = new JXTable(10, 2); table.setBackground(ledger); table.setHighlighters(HighlighterFactory.createSimpleStriping()); JXTable nohighlight = new JXTable(10, 2); nohighlight.setBackground(ledger); showWithScrollingInFrame(table, nohighlight, "colored table with ui highlighter <--> without highlighter"); } /** * Effect of background highlighters on list with custom background. * */ public void interactiveColoredListWithAlternateRow() { JXList list = new JXList(createListModel()); list.setBackground(ledger); list.addHighlighter( HighlighterFactory.createSimpleStriping(HighlighterFactory.GENERIC_GRAY)); JXList nohighlight = new JXList(createListModel()); nohighlight.setBackground(ledger); showWithScrollingInFrame(list, nohighlight, "colored list with striping <--> without "); } /** * * Effect of background highlighters on tree with custom background. Note: * background highlighters don't work at all with DefaultTreeCellRenderers. */ public void interactiveColoredTreeWithAlternateRow() { JXTree coreRendering = new JXTree(); coreRendering.setHighlighters(HighlighterFactory.createSimpleStriping(HighlighterFactory.GENERIC_GRAY)); coreRendering.setBackground(ledger); JXTree tree = new JXTree(); tree.setCellRenderer(new DefaultTreeRenderer()); tree.setHighlighters(HighlighterFactory.createSimpleStriping(HighlighterFactory.GENERIC_GRAY)); tree.setBackground(ledger); showWithScrollingInFrame(tree, coreRendering, "colored tree with striping: swingx <--> core"); } @SuppressWarnings("all") private TableModel createTableModelWithLinks() { String[] columnNames = { "text only", "Link editable", "Link not-editable", "Bool editable", "Bool not-editable" }; DefaultTableModel model = new DefaultTableModel(columnNames, 0) { public Class getColumnClass(int column) { return getValueAt(0, column).getClass(); } @Override public boolean isCellEditable(int row, int column) { return !getColumnName(column).contains("not"); } }; for (int i = 0; i < 4; i++) { try { LinkModel link = new LinkModel("a link text " + i, null, new URL("http://some.dummy.url" + i)); if (i == 1) { URL url = JXEditorPaneTest.class.getResource("resources/test.html"); link = new LinkModel("a link text " + i, null, url); } model.addRow(new Object[] {"text only " + i, link, link, Boolean.TRUE, Boolean.TRUE }); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return model; } /** * Issue #178-swingx: Highlighters must not change the selection color if selection colors * not set. * * Compare table with empty highlighter to table without highlighter. */ public void interactiveTableWithDoNothingHighlighter() { JXTable table = new JXTable(new AncientSwingTeam()); table.addHighlighter(emptyHighlighter); showWithScrollingInFrame(table, new JXTable(table.getModel()), "selection: empty highlighter <--> no highlighter"); } //------------------ helpers private ListModel createListModel() { DefaultListModel model = new DefaultListModel(); for (int i = 0; i < 10; i++) { model.add(i, i); } return model; } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/SelectionMapperTest.java0000644000175000017500000002556511210401722026503 0ustar tonytony/* * Created on 12.07.2005 * */ package org.jdesktop.swingx.decorator; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.DefaultListSelectionModel; import javax.swing.ListSelectionModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.decorator.FilterTest.DirectModelAdapter; import org.jdesktop.test.AncientSwingTeam; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class SelectionMapperTest extends InteractiveTestCase { public SelectionMapperTest() { super("SelectionMapperTest"); } private TableModel ascendingModel; protected ComponentAdapter ascendingModelAdapter; @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } @Test public void testLeadRemoveAll() { ListSelectionModel selectionModel = new DefaultListSelectionModel(); FilterPipeline pipeline = new FilterPipeline(); pipeline.assign(ascendingModelAdapter); SelectionMapper selectionMapper = new DefaultSelectionMapper(pipeline, selectionModel); selectionModel.setSelectionInterval(5, 5); assertEquals(5, selectionModel.getLeadSelectionIndex()); selectionMapper.removeIndexInterval(0, 5); pipeline.flush(); assertEquals(-1, selectionModel.getLeadSelectionIndex()); } /** * Issue #405-swingx: AIOOB in certain conditions. *

* * The root cause is that DefaultListSelectionModel fires events with * negative firstIndex, after clearing anchor/lead. While the behaviour is wrong * (see core bug ??) for now the mapper has to cope. *

* * Fixed by guarding against -1 in mapTowardsModel(int, int). */ @SuppressWarnings("all") @Test public void testNegativFirstIndex() { ListSelectionModel selectionModel = new DefaultListSelectionModel(); FilterPipeline pipeline = new FilterPipeline(); pipeline.assign(ascendingModelAdapter); SelectionMapper selectionMapper = new DefaultSelectionMapper(pipeline, selectionModel); pipeline.getSortController().toggleSortOrder(0); // select first int index = 0; selectionModel.setSelectionInterval(index, index); selectionModel.clearSelection(); selectionModel.setAnchorSelectionIndex(-1); } /** * Related to #186-swingx: Lead/anchor not correctly synched. * */ @Test public void testSynchLeadSelection() { ListSelectionModel viewSelectionModel = new DefaultListSelectionModel(); int selected = 0; viewSelectionModel.setSelectionInterval(selected, selected); FilterPipeline pipeline = null; //new FilterPipeline(); // pipeline.assign(ascendingModelAdapter); DefaultSelectionMapper selectionMapper = new DefaultSelectionMapper(pipeline, viewSelectionModel); int anchor = selected; int lead = selected; assertAnchorLeadSynched(anchor, lead, viewSelectionModel, selectionMapper); anchor = 2; viewSelectionModel.setValueIsAdjusting(true); viewSelectionModel.setAnchorSelectionIndex(anchor); viewSelectionModel.setValueIsAdjusting(false); // pipeline.flush(); assertAnchorLeadSynched(anchor, lead, viewSelectionModel, selectionMapper); } @Test public void testAnchorLeadSelection() { ListSelectionModel viewSelectionModel = new DefaultListSelectionModel(); int selected = 0; viewSelectionModel.setSelectionInterval(selected, selected); int anchor = selected; int lead = selected; assertAnchorLead(anchor, lead, viewSelectionModel); anchor = 2; viewSelectionModel.setValueIsAdjusting(true); viewSelectionModel.setAnchorSelectionIndex(anchor); viewSelectionModel.setValueIsAdjusting(false); assertAnchorLead(anchor, lead, viewSelectionModel); } private void assertAnchorLeadSynched(int anchor, int lead, ListSelectionModel viewSelection, DefaultSelectionMapper mapper) { assertAnchorLead(anchor, lead, viewSelection); assertAnchorLead(anchor, lead, mapper.modelSelection); } private void assertAnchorLead(int anchor, int lead, ListSelectionModel viewSelection) { assertEquals("anchor", anchor, viewSelection.getAnchorSelectionIndex()); assertEquals("lead", lead, viewSelection.getLeadSelectionIndex()); } @Test public void testSelectionNullPipeline() { ListSelectionModel selectionModel = new DefaultListSelectionModel(); selectionModel.setSelectionInterval(0, 0); DefaultSelectionMapper selectionMapper = new DefaultSelectionMapper(null, selectionModel); selectionMapper.mapTowardsView(); assertTrue("selection must be retained", selectionModel.isSelectedIndex(0)); } @Test public void testLeadSelectionSetPipeline() { ListSelectionModel selectionModel = new DefaultListSelectionModel(); // select first in "model" coordinates int index0 = 0; int lead = 2; int index1 = 4; selectionModel.addSelectionInterval(index0, index0); selectionModel.addSelectionInterval(index1, index1); selectionModel.addSelectionInterval(lead, lead); assertEquals("lead is last selected", lead, selectionModel.getLeadSelectionIndex()); FilterPipeline pipeline = new FilterPipeline(); // descending sorter pipeline.setSorter(new ShuttleSorter(0, false)); pipeline.assign(ascendingModelAdapter); new DefaultSelectionMapper(pipeline, selectionModel); assertEquals("lead selection must be last added", pipeline.convertRowIndexToView(lead), selectionModel.getLeadSelectionIndex()); } @Test public void testSelectionSetPipeline() { ListSelectionModel selectionModel = new DefaultListSelectionModel(); FilterPipeline pipeline = new FilterPipeline(); // descending sorter pipeline.setSorter(new ShuttleSorter(0, false)); pipeline.assign(ascendingModelAdapter); // pipeline.flush(); // select first in model coordinates int index = 0; selectionModel.setSelectionInterval(index, index); SelectionMapper selectionMapper = new DefaultSelectionMapper(null, selectionModel); selectionMapper.setFilters(pipeline); // selection.mapTowardsView(); assertEquals("view selection must be last", ascendingModelAdapter.getRowCount() - 1, selectionModel.getMinSelectionIndex()); } /** * Issue #187: keep selection on filter change * */ @Test public void testKeepSelectionOnFilterChange() { JXTable table = new JXTable(ascendingModel); int selectedRow = 0; table.setRowSelectionInterval(selectedRow, selectedRow); // sanity assert assertEquals(selectedRow, table.getSelectedRow()); PatternFilter filter = new PatternFilter(".*", 0, 0); table.setFilters(new FilterPipeline(new Filter[] {filter})); assertEquals(ascendingModel.getRowCount(), table.getRowCount()); assertEquals("table must keep selection after setting filter", selectedRow, table.getSelectedRow()); } @Override protected void setUp() throws Exception { super.setUp(); ascendingModel = createAscendingModel(0, 20); ascendingModelAdapter = new DirectModelAdapter(ascendingModel); } /** * returns a tableModel with count rows filled with * ascending integers in first column * starting from startRow. * @param startRow the value of the first row * @param count the number of rows * @return table model */ private DefaultTableModel createAscendingModel(int startRow, int count) { DefaultTableModel model = new DefaultTableModel(count, 5) { @Override public Class getColumnClass(int column) { return column == 0 ? Integer.class : super.getColumnClass(column); } }; for (int i = 0; i < model.getRowCount(); i++) { model.setValueAt(new Integer(startRow++), i, 0); } return model; } /** * returns a pipeline with two default patternfilters on * column 0, 2 and a sorter on column 0. */ private FilterPipeline createPipeline() { Filter filterZero = createDefaultPatternFilter(0); Filter filterTwo = createDefaultPatternFilter(2); Sorter sorter = new ShuttleSorter(); Filter[] filters = new Filter[] {filterZero, filterTwo, sorter}; FilterPipeline pipeline = new FilterPipeline(filters); return pipeline; } /** returns a PatternFilter for occurences of "e" in column. * * @param column * @return a PatternFilter for occurences of "e" in column */ protected Filter createDefaultPatternFilter(int column) { Filter filterZero = new PatternFilter("e", 0, column); return filterZero; } /** * just to see the filtering effects... * */ public void interactiveTestColumnControlAndFilters() { final JXTable table = new JXTable(new AncientSwingTeam()); table.setColumnControlVisible(true); // table.setFilters(createPipeline()); Action toggleFilter = new AbstractAction("Toggle Filters") { boolean hasFilters; public void actionPerformed(ActionEvent e) { if (hasFilters) { table.setFilters(null); } else { table.setFilters(createPipeline()); // FilterPipeline pipeline = new FilterPipeline(new Filter[] {}); // table.setFilters(pipeline); } hasFilters = !hasFilters; } }; toggleFilter.putValue(Action.SHORT_DESCRIPTION, "filtering first column - problem if invisible "); JXFrame frame = wrapWithScrollingInFrame(table, "JXTable ColumnControl and Filters"); addAction(frame, toggleFilter); frame.setVisible(true); } public static void main(String args[]) { setSystemLF(true); SelectionMapperTest test = new SelectionMapperTest(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/ComponentAdapterClientTest.java0000644000175000017500000003171311210401722030003 0ustar tonytony/* * $Id: ComponentAdapterClientTest.java,v 1.11 2009/01/22 13:19:36 kleopatra Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.decorator; import java.awt.Color; import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.tree.DefaultMutableTreeNode; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXList; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTree; import org.jdesktop.swingx.decorator.ComponentAdapterTest.JXTableT; import org.jdesktop.swingx.decorator.ComponentAdapterTest.JXTreeT; import org.jdesktop.swingx.decorator.ComponentAdapterTest.JXTreeTableT; import org.jdesktop.swingx.renderer.DefaultListRenderer; import org.jdesktop.swingx.renderer.DefaultTableRenderer; import org.jdesktop.swingx.renderer.DefaultTreeRenderer; import org.jdesktop.swingx.renderer.StringValue; import org.jdesktop.swingx.renderer.StringValues; import org.jdesktop.swingx.test.ComponentTreeTableModel; import org.jdesktop.swingx.treetable.TreeTableModel; import org.jdesktop.test.AncientSwingTeam; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Testing clients of ComponentAdapter, mainly clients which rely on uniform string * representation across functionality. Not the optimal location, but where would * that be? * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class ComponentAdapterClientTest extends InteractiveTestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger .getLogger(ComponentAdapterClientTest.class.getName()); public static void main(String[] args) { ComponentAdapterClientTest test = new ComponentAdapterClientTest(); try { test.runInteractiveTests(); } catch (Exception e) { e.printStackTrace(); } } /** * A custom StringValue for Color. Maps to a string composed of the * prefix "R/G/B: " and the Color's rgb value. */ private StringValue sv; @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } /** * Issue #767-swingx: consistent string representation. * * used in find/highlight */ public void interactiveTableGetStringUsedInFind() { JXTable table = new JXTable(new AncientSwingTeam()); table.setDefaultRenderer(Color.class, new DefaultTableRenderer(sv)); HighlightPredicate predicate = new PatternPredicate("R/G/B: -2", 2, 2); table.addHighlighter(new ColorHighlighter(predicate, null, Color.RED)); table.setColumnControlVisible(true); JXFrame frame = wrapWithScrollingInFrame(table, "Find/Highlight use adapter string value"); addSearchModeToggle(frame); addMessage(frame, "Press ctrl-F to open search widget"); show(frame); } /** * Issue #767-swingx: consistent string representation. * * used in find/highlight */ public void interactiveListGetStringUsedInFind() { JXList table = new JXList(AncientSwingTeam.createNamedColorListModel()); table.setCellRenderer(new DefaultListRenderer(sv)); HighlightPredicate predicate = new PatternPredicate("R/G/B: -2", 2, 2); table.addHighlighter(new ColorHighlighter(predicate, null, Color.RED)); JXFrame frame = wrapWithScrollingInFrame(table, "Find/Highlight use adapter string value"); addSearchModeToggle(frame); addMessage(frame, "Press ctrl-F to open search widget"); show(frame); } /** * Issue #767-swingx: consistent string representation. * * used in find/highlight */ public void interactiveTreeGetStringUsedInFind() { JXTree table = new JXTree(AncientSwingTeam.createNamedColorTreeModel()); table.setCellRenderer(new DefaultTreeRenderer(sv)); HighlightPredicate predicate = new PatternPredicate("R/G/B: -2", 2, 2); table.addHighlighter(new ColorHighlighter(predicate, null, Color.RED)); JXFrame frame = wrapWithScrollingInFrame(table, "Find/Highlight use adapter string value"); addSearchModeToggle(frame); addMessage(frame, "Press ctrl-F to open search widget"); show(frame); } //--------------- unit tests /** * Issue #979-swingx: JXTreeTable broken string rep of hierarchical column * * The breakage is visible in models with * (node.toString) != (value for hierarchical column). */ @Test public void testTreeTableGetStringAtClippedTextRenderer() { JPanel panel = new JPanel(); JButton button = new JButton(); String buttonName = "buttonName"; button.setName(buttonName); panel.add(button); TreeTableModel model = new ComponentTreeTableModel(panel); JXTreeTableT table = new JXTreeTableT(model); table.setRootVisible(true); table.expandAll(); assertEquals("string rep must be button name", table.getValueAt(1, 0), table.getStringAt(1, 0)); } /** * Issue #979-swingx: JXTreeTable broken string rep of hierarchical column * * here: test search (accidentally passing because node is instanceof NamedColor * with its toString the same as the value returned for the hierarchical column) */ @Test public void testTreeTableGetStringUsedInSearchClippedTextRenderer() { JXTreeTableT table = new JXTreeTableT(AncientSwingTeam.createNamedColorTreeTableModel()); table.expandAll(); String text = table.getStringAt(2, 0); int matchRow = table.getSearchable().search(text); assertEquals(2, matchRow); } /** * Issue #979-swingx: JXTreeTable broken string rep of hierarchical column * * here: test highlight (accidentally passing because node is instanceof NamedColor * with its toString the same as the value returned for the hierarchical column) */ @Test public void testTreeTableGetStringUsedInPatternPredicateClippedTextRenderer() { JXTreeTableT table = new JXTreeTableT(AncientSwingTeam.createNamedColorTreeTableModel()); int matchRow = 2; int matchColumn = 0; String text = table.getStringAt(matchRow, matchColumn); ComponentAdapter adapter = table.getComponentAdapter(matchRow, matchColumn); HighlightPredicate predicate = new PatternPredicate(text, matchColumn, PatternPredicate.ALL); assertTrue(predicate.isHighlighted(null, adapter)); } /** * Issue #821-swingx: JXTreeTable broken string rep of hierarchical column * * here: test highlight */ @Test public void testTreeTableGetStringUsedInPatternPredicate() { JXTreeTableT table = new JXTreeTableT(AncientSwingTeam.createNamedColorTreeTableModel()); table.setTreeCellRenderer(new DefaultTreeRenderer(sv)); int matchRow = 2; int matchColumn = 0; String text = sv.getString(table.getValueAt(matchRow, matchColumn)); ComponentAdapter adapter = table.getComponentAdapter(matchRow, matchColumn); HighlightPredicate predicate = new PatternPredicate(text, matchColumn, PatternPredicate.ALL); assertTrue(predicate.isHighlighted(null, adapter)); } /** * Issue #821-swingx: JXTreeTable broken string rep of hierarchical column * * here: test search */ @Test public void testTreeTableGetStringUsedInSearch() { JXTreeTableT table = new JXTreeTableT(AncientSwingTeam.createNamedColorTreeTableModel()); table.setTreeCellRenderer(new DefaultTreeRenderer(sv)); String text = sv.getString(table.getValueAt(2, 0)); int matchRow = table.getSearchable().search(text); assertEquals(2, matchRow); } /** * Issue #767-swingx: consistent string representation. * * Here: test TableSearchable uses getStringXX */ @Test public void testTreeGetStringAtUsedInSearch() { JXTreeT tree = new JXTreeT(AncientSwingTeam.createNamedColorTreeModel()); tree.expandAll(); tree.setCellRenderer(new DefaultTreeRenderer(sv)); String text = sv.getString(((DefaultMutableTreeNode) tree.getPathForRow(2).getLastPathComponent()).getUserObject()); int matchRow = tree.getSearchable().search(text); assertEquals(2, matchRow); } /** * Issue #767-swingx: consistent string representation. * * Here: test TableSearchable uses getStringXX */ @Test public void testListGetStringUsedInSearch() { JXList table = new JXList(AncientSwingTeam.createNamedColorListModel()); table.setCellRenderer(new DefaultListRenderer(sv)); String text = sv.getString(table.getElementAt(2)); int matchRow = table.getSearchable().search(text); assertEquals(2, matchRow); } /** * Issue #767-swingx: consistent string representation. * * Here: test TableSearchable uses getStringXX */ @Test public void testTableGetStringUsedInSearch() { JXTable table = new JXTable(new AncientSwingTeam()); table.setDefaultRenderer(Color.class, new DefaultTableRenderer(sv)); String text = sv.getString(table.getValueAt(2, 2)); int matchRow = table.getSearchable().search(text); assertEquals(2, matchRow); } /** * Issue #767-swingx: consistent string representation. * * Here: test PatternFilter uses getStringXX */ @Test public void testTableGetStringUsedInPatternFilter() { JXTableT table = new JXTableT(new AncientSwingTeam()); table.setDefaultRenderer(Color.class, new DefaultTableRenderer(sv)); PatternFilter filter = new PatternFilter("R/G/B: -2", 0, 2); table.setFilters(new FilterPipeline(filter)); assertTrue(table.getRowCount() > 0); assertEquals(sv.getString(table.getValueAt(0, 2)), table.getStringAt(0, 2)); } /** * Issue #767-swingx: consistent string representation. * * Here: test SearchPredicate uses getStringXX. */ @Test public void testTableGetStringUsedInSearchPredicate() { JXTableT table = new JXTableT(new AncientSwingTeam()); table.setDefaultRenderer(Color.class, new DefaultTableRenderer(sv)); int matchRow = 3; int matchColumn = 2; String text = sv.getString(table.getValueAt(matchRow, matchColumn)); ComponentAdapter adapter = table.getComponentAdapter(matchRow, matchColumn); SearchPredicate predicate = new SearchPredicate(text, matchRow, matchColumn); assertTrue(predicate.isHighlighted(null, adapter)); } /** * Issue #767-swingx: consistent string representation. * * Here: test PatternPredicate uses getStringxx(). */ @Test public void testTableGetStringUsedInPatternPredicate() { JXTableT table = new JXTableT(new AncientSwingTeam()); table.setDefaultRenderer(Color.class, new DefaultTableRenderer(sv)); int matchRow = 3; int matchColumn = 2; String text = sv.getString(table.getValueAt(matchRow, matchColumn)); ComponentAdapter adapter = table.getComponentAdapter(matchRow, matchColumn); HighlightPredicate predicate = new PatternPredicate(text, matchColumn, PatternPredicate.ALL); assertTrue(predicate.isHighlighted(null, adapter)); } /** * Creates and returns a StringValue which maps a Color to it's R/G/B rep, * prepending "R/G/B: " * * @return the StringValue for color. */ private StringValue createColorStringValue() { StringValue sv = new StringValue() { public String getString(Object value) { if (value instanceof Color) { Color color = (Color) value; return "R/G/B: " + color.getRGB(); } return StringValues.TO_STRING.getString(value); } }; return sv; } @Override protected void setUp() throws Exception { sv = createColorStringValue(); } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/HighlighterClientVisualCheck.java0000644000175000017500000000667111210401722030265 0ustar tonytony/* * $Id: HighlighterClientVisualCheck.java,v 1.5 2008/10/11 20:42:31 rah003 Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.decorator; import java.awt.Color; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.decorator.HighlightPredicate.ColumnHighlightPredicate; import org.jdesktop.swingx.decorator.HighlighterFactory.UIColorHighlighter; import org.jdesktop.test.AncientSwingTeam; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * TODO add type doc * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class HighlighterClientVisualCheck extends InteractiveTestCase { public static void main(String[] args) { HighlighterClientVisualCheck test = new HighlighterClientVisualCheck(); try { test.runInteractiveTests(); } catch (Exception e) { e.printStackTrace(); } } /** * Regression Issue ?? swingx: column highlighter change must update view. */ public void interactiveColumnHighlighterChange() { final ColorHighlighter hl = new ColorHighlighter(HighlightPredicate.ODD, Color.RED, Color.BLACK); JXTable table = new JXTable(new AncientSwingTeam()); table.getColumnExt(0).addHighlighter(hl); Action action = new AbstractAction("toggle column color") { public void actionPerformed(ActionEvent e) { Color old = hl.getBackground(); hl.setBackground(old == Color.red ? Color.ORANGE : Color.RED); } }; table.addHighlighter(new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW, null, Color.RED)); JXFrame frame = wrapWithScrollingInFrame(table, "column highlighter update"); addAction(frame, action); addMessage(frame, "toggle column color between orange/red must update immediately"); show(frame); } /** * UI-dependent Column highlighter must updated on updateUI. */ public void interactiveColumnHighlighterUpdateUI() { JXTable table = new JXTable(new AncientSwingTeam()); table.getColumnExt(2).addHighlighter(new UIColorHighlighter()); table.addHighlighter(new UIColorHighlighter(new ColumnHighlightPredicate(1))); showWithScrollingInFrame(table, "UpdateUI - table highlighter in second, column highlighter in third"); } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/AbstractTestHighlighterClient.java0000644000175000017500000003340111210401722030456 0ustar tonytony/* * $Id: AbstractTestHighlighterClient.java,v 1.3 2009/01/27 23:00:23 rah003 Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.decorator; import java.awt.Color; import java.beans.PropertyChangeListener; import java.util.logging.Logger; import javax.swing.UIManager; import junit.framework.TestCase; import org.jdesktop.test.PropertyChangeReport; import org.jdesktop.test.TestUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Contains tests around Highlighter client api for collection components. *

* * The common public api: * *


 *  void setHighlighters(Highlighter...)
 *  HighLighter[] getHighlighters()
 *  void addHighlighter(Highlighter)
 *  void removeHighlighter(Highlighter)
 *  updateUI()
 * 
* * Subclasses testing concrete implementations must override the createHighlighterClient. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public abstract class AbstractTestHighlighterClient extends TestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger .getLogger(AbstractTestHighlighterClient.class.getName()); // ---- HighlighterClient /** * * @return the concrete HighlighterClient to test */ protected abstract HighlighterClient createHighlighterClient(); /** * Test that the client is messaged on change to a managed Highlighter. */ @Test public void testUpdateUI() { HighlighterClient client = createHighlighterClient(); // force loading of striping colors ColorHighlighter colorHighlighter = (ColorHighlighter) HighlighterFactory.createSimpleStriping(); Color uiColor = UIManager.getColor("UIColorHighlighter.stripingBackground"); if (uiColor == null) { LOG.info("cannot run test - no ui striping color"); return; } assertSame("sanity", uiColor, colorHighlighter.getBackground()); client.addHighlighter(colorHighlighter); Color changedUIColor = Color.RED; UIManager.put("UIColorHighlighter.stripingBackground", changedUIColor); client.updateUI(); try { assertSame("support must update ui color", changedUIColor, colorHighlighter.getBackground()); } finally { UIManager.put("UIColorHighlighter.stripingBackground", uiColor); } } @Test public void testSetHighlighters() { HighlighterClient client = createHighlighterClient(); Highlighter[] highlighters = new Highlighter[] {new ColorHighlighter(), new ColorHighlighter()}; client.setHighlighters(highlighters); assertSameContent(highlighters, client.getHighlighters()); } /** * Test property change event on setHighlighters for JXTable. */ @Test public void testSetHighlightersChangeEvent() { HighlighterClient client = createHighlighterClient(); PropertyChangeReport report = new PropertyChangeReport(); client.addPropertyChangeListener(report); Highlighter[] old = client.getHighlighters(); Highlighter highlighter = new ColorHighlighter(); client.setHighlighters(highlighter); TestUtils.assertPropertyChangeEvent(report, "highlighters", old, client.getHighlighters()); } /** * Sanity: handles empty array. */ @Test public void testSetHighlightersEmptyArray() { HighlighterClient client = createHighlighterClient(); client.setHighlighters(new Highlighter[] {}); assertEquals(0, client.getHighlighters().length); } /** * * Test that setting zero highlighter removes all. */ @Test public void testSetHighlightersNoArgument() { HighlighterClient client = createHighlighterClient(); client.addHighlighter(new ColorHighlighter()); // sanity assertEquals(1, client.getHighlighters().length); client.setHighlighters(); assertEquals(0, client.getHighlighters().length); } /** * Test strict enforcement of not null allowed in setHighlighters for JXTable. * * Here: null highlighter. */ @Test public void testSetHighlightersNullHighlighter() { try { createHighlighterClient().setHighlighters((Highlighter) null); fail("illegal to call setHighlighters(null)"); } catch (NullPointerException e) { // expected } } /** * Test strict enforcement of not null allowed in setHighlighters for JXTable. * * Here: null array */ @Test public void testSetHighlightersNullArray() { try { createHighlighterClient().setHighlighters((Highlighter[]) null); fail("illegal to call setHighlighters(null)"); } catch (NullPointerException e) { // expected } } /** * Test strict enforcement of not null allowed in setHighlighters for JXTable. * * Here: null array element. */ @Test public void testSetHighlightersArrayNullElement() { try { createHighlighterClient().setHighlighters(new Highlighter[] {null}); fail("illegal to call setHighlighters(null)"); } catch (NullPointerException e) { // expected } } /** * test if removeHighlighter behaves as doc'ed. * */ @Test public void testRemoveHighlighterTable() { HighlighterClient client = createHighlighterClient(); // test cope with null client.removeHighlighter(null); Highlighter presetHighlighter = new ColorHighlighter(); client.setHighlighters(presetHighlighter); Highlighter[] highlighters = client.getHighlighters(); // sanity assertEquals(1, highlighters.length); // remove uncontained client.removeHighlighter(new ColorHighlighter()); // assert no change assertSameContent(highlighters, client.getHighlighters()); client.removeHighlighter(presetHighlighter); assertEquals(0, client.getHighlighters().length); } /** * Test property change event on removeHighlighter for JXTable. */ @Test public void testRemoveHighlightersChangeEvent() { HighlighterClient table = createHighlighterClient(); Highlighter highlighter = new ColorHighlighter(); table.setHighlighters(highlighter); PropertyChangeReport report = new PropertyChangeReport(); table.addPropertyChangeListener(report); Highlighter[] old = table.getHighlighters(); table.removeHighlighter(highlighter); TestUtils.assertPropertyChangeEvent(report, "highlighters", old, table.getHighlighters()); } /** * test if addHighlighter behaves as doc'ed for JXTable. * */ @Test public void testAddHighlighter() { HighlighterClient client = createHighlighterClient(); Highlighter presetHighlighter = new ColorHighlighter(); // add the first client.addHighlighter(presetHighlighter); // assert that it is added assertEquals(1, client.getHighlighters().length); assertAsLast(client.getHighlighters(), presetHighlighter); Highlighter highlighter = new ColorHighlighter(); // add the second client.addHighlighter(highlighter); assertEquals(2, client.getHighlighters().length); // assert that it is appended assertAsLast(client.getHighlighters(), highlighter); } /** * Test property change event on addHighlighter for JXTable. */ @Test public void testAddHighlighterChangeEvent() { HighlighterClient table = createHighlighterClient(); PropertyChangeReport report = new PropertyChangeReport(); table.addPropertyChangeListener(report); Highlighter[] old = table.getHighlighters(); Highlighter highlighter = new ColorHighlighter(); table.addHighlighter(highlighter); TestUtils.assertPropertyChangeEvent(report, "highlighters", old, table.getHighlighters()); } /** * test choking on precondition failure (highlighter must not be null) for JTXTable. * */ @Test public void testAddNullHighlighter() { try { createHighlighterClient().addHighlighter(null); fail("adding a null highlighter must throw NPE"); } catch (NullPointerException e) { // pass - this is what we expect } catch (Exception e) { fail("adding a null highlighter throws exception different " + "from the expected NPE \n" + e); } } /** * Same content in both. * @param highlighters * @param highlighters2 */ private void assertSameContent(Highlighter[] highlighters, Highlighter[] highlighters2) { assertEquals(highlighters.length, highlighters2.length); for (int i = 0; i < highlighters.length; i++) { assertSame("must contain same element", highlighters[i], highlighters2[i]); } } /** * Last in list. * * @param highlighters * @param highlighter */ private void assertAsLast(Highlighter[] highlighters, Highlighter highlighter) { assertTrue("pipeline must not be empty", highlighters.length > 0); assertSame("highlighter must be added as last", highlighter, highlighters[highlighters.length - 1]); } /** * This interface defines the common contract of clients which provide * support for Highlighters. They must * *
    *
  • have a bound property "highlighters" denoting a collection of * Highlighters *
  • have methods to modify the collection *
  • update the ui of contained Highlighters on LAF changes *
  • apply the highlighters as appropriate. This implies that it must * listen to highlighter state changes to update itself (or related parties) * accordingly. *
* * The last bullet is a "vague" requirement in that it might vary * considerably across client implementations. While JComponents typically * will invoke a repaint, a non-component might choose to notify some other * listeners. Furthermore, it's not testable, as clients might choose to do * the actual update only if really needed, f.i. not if invisible or if * there are no external listeners. *

* */ public static interface HighlighterClient { /** * Sets the Highlighters to this client, replacing any old settings. * No argument or an empty array removes all Highlighters.

* * This is a bound property. * * @param highlighters zero or more not null highlighters to use for renderer decoration. * @throws NullPointerException if array is null or array contains null values. * * @see #getHighlighters() * @see #addHighlighter(Highlighter) * @see #removeHighlighter(Highlighter) * */ void setHighlighters(Highlighter... highlighters); /** * Returns the Highlighters used by this client. * Maybe empty, but guarantees to be never null. * * @return the Highlighters used by this table, guaranteed to never null. * * @see #setHighlighters(Highlighter[]) */ Highlighter[] getHighlighters(); /** * Appends a Highlighter to the end of the list of used * Highlighters. The argument must not be null. *

* * @param highlighter the Highlighter to add, must not be null. * @throws NullPointerException if Highlighter is null. * * @see #removeHighlighter(Highlighter) * @see #setHighlighters(Highlighter[]) */ void addHighlighter(Highlighter highlighter); /** * Removes the given Highlighter. Does nothing if the * Highlighter is not contained. * * @param highlighter the Highlighter to remove. * * @see #addHighlighter(Highlighter) * @see #setHighlighters(Highlighter...) */ void removeHighlighter(Highlighter highlighter); /** * Updates contained Highlighters on LAF changes. */ void updateUI(); /** * Adds a PropertyChangeListener which will be notified on changes of the * "highlighters" property. * * @param l the listener to add. */ void addPropertyChangeListener(PropertyChangeListener l); /** * Removes the PropertyChangeListener. Does nothing if the * listener is not contained. * * @param l the listener to remove. */ void removePropertyChangeListener(PropertyChangeListener l); } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/ListSelectionIssues.java0000644000175000017500000001625711210401722026524 0ustar tonytony/* * $Id: ListSelectionIssues.java,v 1.5 2008/02/14 16:00:18 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.decorator; import javax.swing.DefaultListSelectionModel; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import org.jdesktop.test.ListSelectionReport; import junit.framework.TestCase; /** * Test to understand behaviour/expose known issues of * ListSelectionModel. * * * @author Jeanette Winzenburg */ public class ListSelectionIssues extends TestCase { /** * sanity: understand DefaultListSelectionModel behaviour. * * Is it allowed that event.getFirstIndex < 0? This happens in * table.clearLeadAnchor * */ public void testEventsONLeadAnchorAfterClearSelection() { DefaultListSelectionModel selectionModel = new DefaultListSelectionModel(); int selected = 5; selectionModel.setSelectionInterval(selected, selected); assertEquals(selected, selectionModel.getAnchorSelectionIndex()); assertEquals(selected, selectionModel.getLeadSelectionIndex()); // selectionModel.setLeadAnchorNotificationEnabled(false); ListSelectionReport report = new ListSelectionReport(); selectionModel.addListSelectionListener(report); // following lines are copied from table.clearLeadAnchor() // selectionModel.setValueIsAdjusting(true); selectionModel.clearSelection(); assertEquals(1, report.getEventCount()); assertTrue(report.getLastEvent(false).getFirstIndex() >= 0); report.clear(); selectionModel.setAnchorSelectionIndex(-1); assertEquals(1, report.getEventCount()); assertTrue(report.getLastEvent(false).getFirstIndex() >= 0); report.clear(); selectionModel.setLeadSelectionIndex(-1); assertEquals(1, report.getEventCount()); assertTrue(report.getLastEvent(false).getFirstIndex() >= 0); report.clear(); } /** * sanity: understand DefaultListSelectionModel behaviour. * * Is it allowed that event.getFirstIndex < 0? This happens in * table.clearLeadAnchor * */ public void testEventONLeadAnchorAfterClearSelection() { DefaultListSelectionModel selectionModel = new DefaultListSelectionModel(); int selected = 5; selectionModel.setSelectionInterval(selected, selected); assertEquals(selected, selectionModel.getAnchorSelectionIndex()); assertEquals(selected, selectionModel.getLeadSelectionIndex()); selectionModel.setLeadAnchorNotificationEnabled(false); ListSelectionReport report = new ListSelectionReport(); selectionModel.addListSelectionListener(report); // following lines are copied from table.clearLeadAnchor() selectionModel.setValueIsAdjusting(true); selectionModel.clearSelection(); selectionModel.setAnchorSelectionIndex(-1); selectionModel.setLeadSelectionIndex(-1); assertEquals("", 0, report.getEventCount(true)); selectionModel.setValueIsAdjusting(false); ListSelectionEvent event = report.getLastEvent(true); assertEquals(5, event.getFirstIndex()); } /** * sanity: understand DefaultListSelectionModel behaviour. * * behaviour for a single selected and removal of that single selected: * if "last" selected (==lead/anchor) and removed then the * selection is empty but lead/anchor are on the new "last" row. * * behaviour for single selected and removal of larger interval: * anchor/lead moved down by the amount of the range removed. * * */ public void testLeadAnchorAfterClearSelection() { ListSelectionModel viewSelectionModel = new DefaultListSelectionModel(); int selected = 5; viewSelectionModel.setSelectionInterval(selected, selected); assertEquals(selected, viewSelectionModel.getAnchorSelectionIndex()); assertEquals(selected, viewSelectionModel.getLeadSelectionIndex()); viewSelectionModel.clearSelection(); int anchor = selected; assertTrue(viewSelectionModel.isSelectionEmpty()); assertEquals(anchor, viewSelectionModel.getAnchorSelectionIndex()); assertEquals(anchor, viewSelectionModel.getLeadSelectionIndex()); } /** * sanity: understand DefaultListSelectionModel behaviour. * * Here: select index 5, remove 5..5 -> lead == 4 * */ public void testLeadAnchorAfterRemove() { ListSelectionModel viewSelectionModel = new DefaultListSelectionModel(); assertLeadAnchorAfterRemoveAll(viewSelectionModel, 5, 5); } /** * sanity: understand DefaultListSelectionModel behaviour. * * * Here: select index 5, remove 0..5 -> lead == -1 */ public void testLeadAnchorAfterRemoveAll() { ListSelectionModel viewSelectionModel = new DefaultListSelectionModel(); assertLeadAnchorAfterRemoveAll(viewSelectionModel, 5, 0); } /** * sanity: understand DefaultListSelectionModel behaviour. * * * Here: select 0, remove 0..0 --> lead == 0 (expected -1) */ public void testLeadAnchorAfterRemoveAll0() { ListSelectionModel viewSelectionModel = new DefaultListSelectionModel(); assertLeadAnchorAfterRemoveAll(viewSelectionModel, 0, 0); } /** * Asserts lead/anchor after removeIndexInterval. * The setup is to select selectedIndex and removes the index interval first..selected. * * @param viewSelectionModel * @param selected * @param firstOfRemoveInterval */ private void assertLeadAnchorAfterRemoveAll( ListSelectionModel viewSelectionModel, int selected, int firstOfRemoveInterval) { viewSelectionModel.setSelectionInterval(selected, selected); assertEquals(selected, viewSelectionModel.getAnchorSelectionIndex()); assertEquals(selected, viewSelectionModel.getLeadSelectionIndex()); int length = selected - firstOfRemoveInterval + 1; viewSelectionModel.removeIndexInterval(firstOfRemoveInterval, selected); int anchor = selected - length; assertTrue(viewSelectionModel.isSelectionEmpty()); assertEquals(anchor, viewSelectionModel.getAnchorSelectionIndex()); assertEquals(anchor, viewSelectionModel.getLeadSelectionIndex()); } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/HighlightPredicateTest.java0000644000175000017500000011756311210401722027141 0ustar tonytony/* * $Id: HighlightPredicateTest.java,v 1.23 2008/10/11 20:42:31 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.decorator; import java.awt.Color; import java.awt.Point; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.regex.Pattern; import javax.swing.JLabel; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.decorator.HighlightPredicate.AndHighlightPredicate; import org.jdesktop.swingx.decorator.HighlightPredicate.ColumnHighlightPredicate; import org.jdesktop.swingx.decorator.HighlightPredicate.DepthHighlightPredicate; import org.jdesktop.swingx.decorator.HighlightPredicate.EqualsHighlightPredicate; import org.jdesktop.swingx.decorator.HighlightPredicate.IdentifierHighlightPredicate; import org.jdesktop.swingx.decorator.HighlightPredicate.NotHighlightPredicate; import org.jdesktop.swingx.decorator.HighlightPredicate.OrHighlightPredicate; import org.jdesktop.swingx.decorator.HighlightPredicate.RowGroupHighlightPredicate; import org.jdesktop.swingx.decorator.HighlightPredicate.TypeHighlightPredicate; import org.jdesktop.swingx.rollover.RolloverProducer; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * * Tests for Highlighters after overhaul. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class HighlightPredicateTest extends InteractiveTestCase { protected JLabel backgroundNull ; protected JLabel foregroundNull; protected JLabel allNull; protected JLabel allColored; protected Color background = Color.RED; protected Color foreground = Color.BLUE; protected Color unselectedBackground = Color.CYAN; protected Color unselectedForeground = Color.GREEN; protected Color selectedBackground = Color.LIGHT_GRAY; protected Color selectedForeground = Color.MAGENTA; protected ColorHighlighter emptyHighlighter; @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } @Override protected void setUp() { backgroundNull = new JLabel("test"); backgroundNull.setForeground(foreground); backgroundNull.setBackground(null); foregroundNull = new JLabel("test"); foregroundNull.setForeground(null); foregroundNull.setBackground(background); allNull = new JLabel("test"); allNull.setForeground(null); allNull.setBackground(null); allColored = new JLabel("test"); allColored.setForeground(foreground); allColored.setBackground(background); emptyHighlighter = new ColorHighlighter(); } // ---------------- predefined predicate /** * Issue #858-swingx: predefined focus predicate. * * Test the HAS_FOCUS predicate */ @Test public void testHasFocus() { ComponentAdapter adapter = createComponentAdapter(allColored, true, true); assertTrue("sanity", adapter.hasFocus()); assertEquals(adapter.hasFocus(), HighlightPredicate.HAS_FOCUS.isHighlighted(allColored, adapter)); } /** * Issue #858-swingx: predefined focus predicate. * * Test the HAS_FOCUS predicate */ @Test public void testNotHasFocus() { ComponentAdapter adapter = createComponentAdapter(allColored, false); assertFalse("sanity", adapter.hasFocus()); assertEquals(adapter.hasFocus(), HighlightPredicate.HAS_FOCUS.isHighlighted(allColored, adapter)); } /** * test the IS_FOLDER predicate. * */ @Test public void testFolder() { ComponentAdapter adapter = createComponentAdapter(allColored, false); assertTrue(HighlightPredicate.IS_FOLDER.isHighlighted(allColored, adapter)); } /** * test the IS_FOLDER predicate. * */ @Test public void testNotFolder() { ComponentAdapter adapter = createComponentAdapter(allColored, true); assertFalse(HighlightPredicate.IS_FOLDER.isHighlighted(allColored, adapter)); } /** * test the IS_LEAF predicate. * */ @Test public void testLeaf() { ComponentAdapter adapter = createComponentAdapter(allColored, false); assertFalse(HighlightPredicate.IS_LEAF.isHighlighted(allColored, adapter)); } /** * test the IS_LEAF predicate. * */ @Test public void testNotLeaf() { ComponentAdapter adapter = createComponentAdapter(allColored, true); assertTrue(HighlightPredicate.IS_LEAF.isHighlighted(allColored, adapter)); } /** * Can't really test the unconditional predicates. * */ @Test public void testAlways() { ComponentAdapter adapter = createComponentAdapter(allColored, true); assertTrue(HighlightPredicate.ALWAYS.isHighlighted(allColored, adapter)); } /** * Can't really test the unconditional predicates. * */ @Test public void testNever() { ComponentAdapter adapter = createComponentAdapter(allColored, true); assertFalse(HighlightPredicate.NEVER.isHighlighted(allColored, adapter)); } /** * test the Editable predicate. * */ @Test public void testEditable() { ComponentAdapter adapter = createComponentAdapter(allColored, false, true); assertTrue(HighlightPredicate.EDITABLE.isHighlighted(allColored, adapter)); assertFalse(HighlightPredicate.READ_ONLY.isHighlighted(allColored, adapter)); } /** * test the ReadOnly predicate. * */ @Test public void testNotEditable() { ComponentAdapter adapter = createComponentAdapter(allColored, false, false); assertFalse(HighlightPredicate.EDITABLE.isHighlighted(allColored, adapter)); assertTrue(HighlightPredicate.READ_ONLY.isHighlighted(allColored, adapter)); } /** * test access the contained predicates */ @Test public void testNotProperty() { HighlightPredicate inputPredicates = new IdentifierHighlightPredicate("t"); NotHighlightPredicate predicate = new NotHighlightPredicate(inputPredicates); HighlightPredicate predicates = predicate.getHighlightPredicate(); assertSame(inputPredicates, predicates); } /** * test the NOT predicate. * */ @Test public void testNot() { ComponentAdapter adapter = createComponentAdapter(allColored, true); HighlightPredicate notNever = new NotHighlightPredicate(HighlightPredicate.NEVER); assertTrue(notNever.isHighlighted(allColored, adapter)); HighlightPredicate notAlways = new NotHighlightPredicate(HighlightPredicate.ALWAYS); assertFalse(notAlways.isHighlighted(allColored, adapter)); } /** * test access the contained predicates */ @Test public void testOrProperty() { List inputPredicates = new ArrayList(); inputPredicates.add(HighlightPredicate.NEVER); inputPredicates.add(new IdentifierHighlightPredicate("t")); OrHighlightPredicate predicate = new OrHighlightPredicate(inputPredicates); HighlightPredicate[] predicates = predicate.getHighlightPredicates(); assertEquals(inputPredicates.size(), predicates.length); for (int i = 0; i < predicates.length; i++) { assertSame(inputPredicates.get(i), predicates[i]); } } /** * test that getPredicates return empty array if nothing contained. */ @Test public void testOrEmptyProperty() { OrHighlightPredicate predicate = new OrHighlightPredicate(); HighlightPredicate[] predicates = predicate.getHighlightPredicates(); assertNotNull("array must not be null", predicates); assertEquals(0, predicates.length); } /** * test that empty array doesn't highlight. */ @Test public void testOrEmpty() { ComponentAdapter adapter = createComponentAdapter(allColored, true); HighlightPredicate emptyArray = new OrHighlightPredicate(); assertFalse(emptyArray.isHighlighted(allColored, adapter)); HighlightPredicate emptyList = new OrHighlightPredicate(new ArrayList()); assertFalse(emptyList.isHighlighted(allColored, adapter)); } /** * test the OR predicate array constructor. Boring as it is, is it complete? * */ @Test public void testOr() { ComponentAdapter adapter = createComponentAdapter(allColored, true); HighlightPredicate oneTrue = new OrHighlightPredicate(HighlightPredicate.ALWAYS); assertTrue(oneTrue.isHighlighted(allColored, adapter)); HighlightPredicate oneFalse = new OrHighlightPredicate(HighlightPredicate.NEVER); assertFalse(oneFalse.isHighlighted(allColored, adapter)); HighlightPredicate oneFalseOneTrue = new OrHighlightPredicate( HighlightPredicate.NEVER, HighlightPredicate.ALWAYS); assertTrue(oneFalseOneTrue.isHighlighted(allColored, adapter)); HighlightPredicate oneTrueOneFalse = new OrHighlightPredicate( HighlightPredicate.ALWAYS, HighlightPredicate.NEVER); assertTrue(oneTrueOneFalse.isHighlighted(allColored, adapter)); } /** * test the OR predicate collection constructor. Boring as it is, is it complete? * */ @Test public void testOrCollectionConstructor() { ComponentAdapter adapter = createComponentAdapter(allColored, true); List containsOneTrue = new ArrayList(); containsOneTrue.add(HighlightPredicate.ALWAYS); HighlightPredicate oneTrue = new OrHighlightPredicate(containsOneTrue); assertTrue(oneTrue.isHighlighted(allColored, adapter)); List containsOneFalse = new ArrayList(); containsOneFalse.add(HighlightPredicate.NEVER); HighlightPredicate oneFalse = new OrHighlightPredicate(containsOneFalse); assertFalse(oneFalse.isHighlighted(allColored, adapter)); List containsOneFalseOneTrue = new ArrayList(); containsOneFalseOneTrue.add(HighlightPredicate.NEVER); containsOneFalseOneTrue.add(HighlightPredicate.ALWAYS); HighlightPredicate oneFalseOneTrue = new OrHighlightPredicate(containsOneFalseOneTrue); assertTrue(oneFalseOneTrue.isHighlighted(allColored, adapter)); List containsOneTrueOneFalse = new ArrayList(); containsOneTrueOneFalse.add(HighlightPredicate.ALWAYS); containsOneTrueOneFalse.add(HighlightPredicate.NEVER); HighlightPredicate oneTrueOneFalse = new OrHighlightPredicate(containsOneTrueOneFalse); assertTrue(oneTrueOneFalse.isHighlighted(allColored, adapter)); } /** * Issue #520-swingx: OrPredicate must throw if any of the parameters * is null. * */ @Test public void testOrThrowsOnNullPredicates() { try { new OrHighlightPredicate((HighlightPredicate[]) null); fail("orPredicate constructor must throw NullPointerException on null predicate"); } catch (NullPointerException ex) { // do nothing - the doc'ed exception } catch (Exception ex) { fail("unexpected exception: " + ex); } try { new OrHighlightPredicate(HighlightPredicate.ALWAYS, null); fail("orPredicate constructor must throw NullPointerException on null predicate"); } catch (NullPointerException ex) { // do nothing - the doc'ed exception } catch (Exception ex) { fail("unexpected exception: " + ex); } try { new OrHighlightPredicate((HighlightPredicate) null); fail("orPredicate constructor must throw NullPointerException on null predicate"); } catch (NullPointerException ex) { // do nothing - the doc'ed exception } catch (Exception ex) { fail("unexpected exception: " + ex); } try { new OrHighlightPredicate((Collection) null); fail("orPredicate constructor must throw NullPointerException on null predicate"); } catch (NullPointerException ex) { // do nothing - the doc'ed exception } catch (Exception ex) { fail("unexpected exception: " + ex); } } /** * Issue #520-swingx: OrPredicate must throw if any of the parameters * is null. * */ @Test public void testAndThrowsOnNullPredicates() { try { new AndHighlightPredicate((HighlightPredicate[]) null); fail("AndPredicate constructAnd must throw NullPointerException on null predicate"); } catch (NullPointerException ex) { // do nothing - the doc'ed exception } catch (Exception ex) { fail("unexpected exception: " + ex); } try { new AndHighlightPredicate(HighlightPredicate.ALWAYS, null); fail("AndPredicate constructAnd must throw NullPointerException on null predicate"); } catch (NullPointerException ex) { // do nothing - the doc'ed exception } catch (Exception ex) { fail("unexpected exception: " + ex); } try { new AndHighlightPredicate((HighlightPredicate) null); fail("AndPredicate constructAnd must throw NullPointerException on null predicate"); } catch (NullPointerException ex) { // do nothing - the doc'ed exception } catch (Exception ex) { fail("unexpected exception: " + ex); } try { new AndHighlightPredicate((Collection) null); fail("orPredicate constructor must throw NullPointerException on null predicate"); } catch (NullPointerException ex) { // do nothing - the doc'ed exception } catch (Exception ex) { fail("unexpected exception: " + ex); } } /** * test access the contained predicates */ @Test public void testAndProperty() { List inputPredicates = new ArrayList(); inputPredicates.add(HighlightPredicate.NEVER); inputPredicates.add(new IdentifierHighlightPredicate("t")); AndHighlightPredicate predicate = new AndHighlightPredicate(inputPredicates); HighlightPredicate[] predicates = predicate.getHighlightPredicates(); assertEquals(inputPredicates.size(), predicates.length); for (int i = 0; i < predicates.length; i++) { assertSame(inputPredicates.get(i), predicates[i]); } } /** * test that getPredicates return empty array if nothing contained. */ @Test public void testAndEmptyProperty() { AndHighlightPredicate predicate = new AndHighlightPredicate(); HighlightPredicate[] predicates = predicate.getHighlightPredicates(); assertNotNull("array must not be null", predicates); assertEquals(0, predicates.length); } /** * test that empty array doesn't highlight. */ @Test public void testAndEmpty() { ComponentAdapter adapter = createComponentAdapter(allColored, true); HighlightPredicate emptyArray = new AndHighlightPredicate(); assertFalse(emptyArray.isHighlighted(allColored, adapter)); HighlightPredicate emptyList = new AndHighlightPredicate(new ArrayList()); assertFalse(emptyList.isHighlighted(allColored, adapter)); } /** * test the AND predicate array constructor. Boring as it is, is it complete? * */ @Test public void testAnd() { ComponentAdapter adapter = createComponentAdapter(allColored, true); HighlightPredicate oneTrue = new AndHighlightPredicate(HighlightPredicate.ALWAYS); assertTrue(oneTrue.isHighlighted(allColored, adapter)); HighlightPredicate oneFalse = new AndHighlightPredicate(HighlightPredicate.NEVER); assertFalse(oneFalse.isHighlighted(allColored, adapter)); HighlightPredicate oneFalseOneTrue = new AndHighlightPredicate( HighlightPredicate.NEVER, HighlightPredicate.ALWAYS); assertFalse(oneFalseOneTrue.isHighlighted(allColored, adapter)); HighlightPredicate oneTrueOneFalse = new AndHighlightPredicate( HighlightPredicate.ALWAYS, HighlightPredicate.NEVER); assertFalse(oneTrueOneFalse.isHighlighted(allColored, adapter)); } /** * test the AND predicate collection constructor. Boring as it is, is it complete? * */ @Test public void testAndCollectionConstructor() { ComponentAdapter adapter = createComponentAdapter(allColored, true); List containsOneTrue = new ArrayList(); containsOneTrue.add(HighlightPredicate.ALWAYS); HighlightPredicate oneTrue = new AndHighlightPredicate(containsOneTrue); assertTrue(oneTrue.isHighlighted(allColored, adapter)); List containsOneFalse = new ArrayList(); containsOneFalse.add(HighlightPredicate.NEVER); HighlightPredicate oneFalse = new AndHighlightPredicate(containsOneFalse); assertFalse(oneFalse.isHighlighted(allColored, adapter)); List containsOneFalseOneTrue = new ArrayList(); containsOneFalseOneTrue.add(HighlightPredicate.NEVER); containsOneFalseOneTrue.add(HighlightPredicate.ALWAYS); HighlightPredicate oneFalseOneTrue = new AndHighlightPredicate(containsOneFalseOneTrue); assertFalse(oneFalseOneTrue.isHighlighted(allColored, adapter)); List containsOneTrueOneFalse = new ArrayList(); containsOneTrueOneFalse.add(HighlightPredicate.ALWAYS); containsOneTrueOneFalse.add(HighlightPredicate.NEVER); HighlightPredicate oneTrueOneFalse = new AndHighlightPredicate(containsOneTrueOneFalse); assertFalse(oneTrueOneFalse.isHighlighted(allColored, adapter)); } /** * test rollover * */ @Test public void testRolloverRow() { ComponentAdapter adapter = createComponentAdapter(allColored, true); // rollover and adapter at 0, 0 int row = 0; int col = 0; allColored.putClientProperty(RolloverProducer.ROLLOVER_KEY, new Point(row, col)); assertTrue(HighlightPredicate.ROLLOVER_ROW.isHighlighted(allColored, adapter)); // move adapter column in same row adapter.column = 3; assertTrue(HighlightPredicate.ROLLOVER_ROW.isHighlighted(allColored, adapter)); // move adapter row adapter.row = 1; assertFalse(HighlightPredicate.ROLLOVER_ROW.isHighlighted(allColored, adapter)); } /** * Issue #513-swingx: no rollover highlight for disabled component * */ @Test public void testRolloverDisabledComponent() { ComponentAdapter adapter = createComponentAdapter(allColored, true); // rollover and adapter at 0, 0 int row = 0; int col = 0; allColored.putClientProperty(RolloverProducer.ROLLOVER_KEY, new Point(row, col)); // sanity assertTrue(HighlightPredicate.ROLLOVER_ROW.isHighlighted(allColored, adapter)); allColored.setEnabled(false); assertFalse(HighlightPredicate.ROLLOVER_ROW.isHighlighted(allColored, adapter)); } /** * test the BIG_DECIMAL_NEGATIVE predicate. * */ @Test public void testBigDecimalNegative() { ComponentAdapter negative = createBigDecimalComponentAdapter(new JLabel("-50.00")); assertTrue(HighlightPredicate.BIG_DECIMAL_NEGATIVE.isHighlighted(negative.getComponent(), negative)); ComponentAdapter positive = createBigDecimalComponentAdapter(new JLabel("50.00")); assertFalse(HighlightPredicate.BIG_DECIMAL_NEGATIVE.isHighlighted(positive.getComponent(), positive)); ComponentAdapter zero = createBigDecimalComponentAdapter(new JLabel(BigDecimal.ZERO.toString())); // sanity assertEquals(BigDecimal.ZERO, zero.getValue()); assertFalse(HighlightPredicate.BIG_DECIMAL_NEGATIVE.isHighlighted(zero.getComponent(), zero)); } //---------------- special predicates /** * test doc'ed behaviour */ @Test public void testRowGroupConstructor() { try { new RowGroupHighlightPredicate(0); fail("RowGroupHighlight must throw IllegalArgumentException for lines < 1"); } catch (IllegalArgumentException ex) { // expected behaviour } } @Test public void testRowGroupProperty() { int lines = 5; RowGroupHighlightPredicate predicate = new RowGroupHighlightPredicate(5); assertEquals(lines, predicate.getLinesPerGroup()); } /** * test equals predicate with null value. */ @Test public void testEqualsNull() { HighlightPredicate predicate = new EqualsHighlightPredicate(); allColored.setText(null); assertNull(allColored.getText()); ComponentAdapter adapter = createComponentAdapter(allColored, false); assertTrue(predicate.isHighlighted(allColored, adapter)); String text = "test"; allColored.setText(text); assertEquals(text, allColored.getText()); assertFalse(predicate.isHighlighted(allColored, adapter)); } /** * test equals predicate with not null value. * */ @Test public void testEqualsNotNull() { HighlightPredicate predicate = new EqualsHighlightPredicate(allColored .getText()); ComponentAdapter adapter = createComponentAdapter(allColored, false); assertTrue(predicate.isHighlighted(allColored, adapter)); allColored.setText(null); assertFalse(predicate.isHighlighted(allColored, adapter)); } /** * test equals predicate with not null value. * */ @Test public void testEqualProperty() { Object text = new Object(); EqualsHighlightPredicate predicate = new EqualsHighlightPredicate(text); assertEquals(text, predicate.getCompareValue()); } @Test public void testColumnProperty() { int[] columns = new int[] {2, 7}; ColumnHighlightPredicate predicate = new ColumnHighlightPredicate(columns); Integer[] output = predicate.getColumns(); assertEquals(columns.length, output.length); for (int i = 0; i < output.length; i++) { assertEquals(columns[i], output[i].intValue()); } } @Test public void testColumnEmptyProperty() { ColumnHighlightPredicate predicate = new ColumnHighlightPredicate(); Integer[] output = predicate.getColumns(); assertEquals("output must be empty array", 0, output.length); } @Test public void testColumn() { HighlightPredicate predicate = new ColumnHighlightPredicate(1); ComponentAdapter adapter = createComponentAdapter(allColored, false); assertFalse("column 0 must not be highlighted", predicate.isHighlighted(allColored, adapter)); adapter.column = 1; assertTrue("column 1 must be highlighted", predicate.isHighlighted(allColored, adapter)); } @Test public void testDepthProperty() { int[] columns = new int[] {2, 7}; DepthHighlightPredicate predicate = new DepthHighlightPredicate(columns); Integer[] output = predicate.getDepths(); assertEquals(columns.length, output.length); for (int i = 0; i < output.length; i++) { assertEquals(columns[i], output[i].intValue()); } } @Test public void testDepthEmptyProperty() { DepthHighlightPredicate predicate = new DepthHighlightPredicate(); Integer[] output = predicate.getDepths(); assertEquals("output must be empty array", 0, output.length); } @Test public void testIdentifierProperty() { Object[] identifiers = new Object[] { "one", "two" }; IdentifierHighlightPredicate predicate = new IdentifierHighlightPredicate(identifiers); Object[] output = predicate.getIdentifiers(); assertEquals(identifiers.length, output.length); for (int i = 0; i < output.length; i++) { assertEquals(identifiers[i], output[i]); } } @Test public void testIdentifierEmptyProperty() { IdentifierHighlightPredicate predicate = new IdentifierHighlightPredicate(); Object[] output = predicate.getIdentifiers(); assertEquals("output must be empty array", 0, output.length); } @Test public void testIdentifierDefault() { HighlightPredicate predicate = new IdentifierHighlightPredicate(ComponentAdapter.DEFAULT_COLUMN_IDENTIFIER); ComponentAdapter adapter = createComponentAdapter(allColored, false); assertTrue("default (single) column must be highlighted", predicate.isHighlighted(allColored, adapter)); } @Test public void testIdentifierFalse() { HighlightPredicate predicate = new IdentifierHighlightPredicate("unknown"); ComponentAdapter adapter = createComponentAdapter(allColored, false); assertFalse("unknown identifier must not highlight", predicate.isHighlighted(allColored, adapter)); } @Test public void testTypeProperty() { Class clazz = String.class; TypeHighlightPredicate predicate = new TypeHighlightPredicate(clazz); assertEquals(clazz, predicate.getType()); } @Test public void testTypeExact() { HighlightPredicate predicate = new TypeHighlightPredicate(String.class); ComponentAdapter adapter = createComponentAdapter(allColored, false); assertTrue("string class must be highlighted", predicate.isHighlighted(allColored, adapter)); } @Test public void testTypeSubclass() { HighlightPredicate predicate = new TypeHighlightPredicate(); ComponentAdapter adapter = createComponentAdapter(allColored, false); assertTrue("string class must be highlighted", predicate.isHighlighted(allColored, adapter)); } @Test public void testTypeFalse() { HighlightPredicate predicate = new TypeHighlightPredicate(Integer.class); ComponentAdapter adapter = createComponentAdapter(allColored, false); assertFalse("string class must be highlighted", predicate.isHighlighted(allColored, adapter)); } // ------ stand-alone predicates @Test public void testPattern() { // start with "t" Pattern pattern = Pattern.compile("^t", 0); int testColumn = 0; int decorateColumn = 0; HighlightPredicate predicate = new PatternPredicate(pattern, testColumn, decorateColumn); ComponentAdapter adapter = createComponentAdapter(allColored, true); assertEquals("predicate must have same result as matcher", pattern.matcher(allColored.getText()).find(), predicate.isHighlighted(allColored, adapter)); } @Test public void testPatternWithString() { // start with "t" String regex = "^t"; int testColumn = 0; int decorateColumn = 0; PatternPredicate predicate = new PatternPredicate(regex, testColumn, decorateColumn); Pattern pattern = Pattern.compile(regex); assertEquals(pattern.pattern(), predicate.getPattern().pattern()); ComponentAdapter adapter = createComponentAdapter(allColored, true); assertEquals("predicate must have same result as matcher", pattern.matcher(allColored.getText()).find(), predicate.isHighlighted(allColored, adapter)); } @Test public void testPatternTwoParamConstructorWithString() { // start with "t" String regex = "^t"; int testColumn = 0; HighlightPredicate predicate = new PatternPredicate(regex, testColumn); Pattern pattern = Pattern.compile(regex); ComponentAdapter adapter = createComponentAdapter(allColored, true); assertEquals("predicate must have same result as matcher", pattern.matcher(allColored.getText()).find(), predicate.isHighlighted(allColored, adapter)); } @Test public void testSearchHighlightConstructorOne() { Pattern pattern = Pattern.compile("^t"); SearchPredicate predicate = new SearchPredicate(pattern); assertEquals(pattern, predicate.getPattern()); assertEquals(SearchPredicate.ALL, predicate.getHighlightColumn()); assertEquals(SearchPredicate.ALL, predicate.getHighlightRow()); } @Test public void testSearchHighlightConstructorTwo() { Pattern pattern = Pattern.compile("^t"); int column = 10; SearchPredicate predicate = new SearchPredicate(pattern, column); assertEquals(pattern, predicate.getPattern()); assertEquals(column, predicate.getHighlightColumn()); assertEquals(SearchPredicate.ALL, predicate.getHighlightRow()); } @Test public void testSearchHighlightConstructorFull() { Pattern pattern = Pattern.compile("^t"); int row = 5; int column = 10; SearchPredicate predicate = new SearchPredicate(pattern, row, column); assertEquals(pattern, predicate.getPattern()); assertEquals(column, predicate.getHighlightColumn()); assertEquals(row, predicate.getHighlightRow()); } /** * test match in all cells. * */ @Test public void testSearchHighlightAllMatches() { // start with "t" Pattern pattern = Pattern.compile("^t"); HighlightPredicate predicate = new SearchPredicate(pattern); ComponentAdapter adapter = createComponentAdapter(allColored, false); assertEquals("predicate must have same result as matcher", pattern.matcher(allColored.getText()).find(), predicate.isHighlighted(allColored, adapter)); adapter.row = 5; adapter.column = 10; assertEquals("predicate must have same result as matcher", pattern.matcher(allColored.getText()).find(), predicate.isHighlighted(allColored, adapter)); } /** * test match limited by column. * */ @Test public void testSearchHighlightColumn() { // start with "t" Pattern pattern = Pattern.compile("^t"); int column = 2; HighlightPredicate predicate = new SearchPredicate(pattern, column); ComponentAdapter adapter = createComponentAdapter(allColored, false); assertFalse("predicate must not match", predicate.isHighlighted(allColored, adapter)); adapter.column = column; assertTrue("predicate must match", predicate.isHighlighted(allColored, adapter)); } /** * test match limited by row. * */ @Test public void testSearchHighlightRow() { // start with "t" Pattern pattern = Pattern.compile("^t"); int row = 2; HighlightPredicate predicate = new SearchPredicate(pattern, row, SearchPredicate.ALL); ComponentAdapter adapter = createComponentAdapter(allColored, false); assertFalse("predicate must not match", predicate.isHighlighted(allColored, adapter)); adapter.row = row; assertTrue("predicate must match", predicate.isHighlighted(allColored, adapter)); } /** * test match limited by row and column. * */ @Test public void testSearchHighlightRowAndColumn() { // start with "t" Pattern pattern = Pattern.compile("^t"); int row = 2; int column = 2; HighlightPredicate predicate = new SearchPredicate(pattern, row, column); ComponentAdapter adapter = createComponentAdapter(allColored, false); assertFalse("predicate must not match", predicate.isHighlighted(allColored, adapter)); adapter.row = row; adapter.column = column; assertTrue("predicate must match", predicate.isHighlighted(allColored, adapter)); } /** * test match in all cells using regex constructor. * */ @Test public void testSearchHighlightAllMatchesWithString() { // start with "t" String regex = "^t"; HighlightPredicate predicate = new SearchPredicate(regex); Pattern pattern = Pattern.compile(regex); ComponentAdapter adapter = createComponentAdapter(allColored, false); assertEquals("predicate must have same result as matcher", pattern.matcher(allColored.getText()).find(), predicate.isHighlighted(allColored, adapter)); adapter.row = 5; adapter.column = 10; assertEquals("predicate must have same result as matcher", pattern.matcher(allColored.getText()).find(), predicate.isHighlighted(allColored, adapter)); } /** * test match limited by column using regex constructor. * */ @Test public void testSearchHighlightColumnWithString() { // start with "t" String regex = "^t"; int column = 2; HighlightPredicate predicate = new SearchPredicate(regex, column); ComponentAdapter adapter = createComponentAdapter(allColored, false); assertFalse("predicate must not match", predicate.isHighlighted(allColored, adapter)); adapter.column = column; assertTrue("predicate must match", predicate.isHighlighted(allColored, adapter)); } /** * test match limited by row using regex constructor. * */ @Test public void testSearchHighlightRowWithString() { // start with "t" String regex = "^t"; int row = 2; HighlightPredicate predicate = new SearchPredicate(regex, row, SearchPredicate.ALL); ComponentAdapter adapter = createComponentAdapter(allColored, false); assertFalse("predicate must not match", predicate.isHighlighted(allColored, adapter)); adapter.row = row; assertTrue("predicate must match", predicate.isHighlighted(allColored, adapter)); } @Test public void testSearchHighlightNullString() { // start with "t" String regex = null; HighlightPredicate predicate = new SearchPredicate(regex); ComponentAdapter adapter = createComponentAdapter(allColored, false); assertEquals("null regex must be no match", false, predicate.isHighlighted(allColored, adapter)); } @Test public void testSearchHighlightEmptyString() { // start with "t" String regex = ""; HighlightPredicate predicate = new SearchPredicate(regex); ComponentAdapter adapter = createComponentAdapter(allColored, false); assertEquals("empty regex must be no match", false, predicate.isHighlighted(allColored, adapter)); } @Test public void testSearchHighlightNullPattern() { Pattern pattern = null; HighlightPredicate predicate = new SearchPredicate(pattern); ComponentAdapter adapter = createComponentAdapter(allColored, false); assertEquals("null pattern must be no match", false, predicate.isHighlighted(allColored, adapter)); } // --------------------- factory methods /** * Creates and returns a ComponentAdapter on the given * label with the specified selection state and non-editable. * * @param label the adapter's component * @param selected the adapter's selected property * @return a ComponentAdapter of the label with the given properties. */ protected ComponentAdapter createComponentAdapter(final JLabel label, final boolean selected) { return createComponentAdapter(label, selected, false); } /** * Creates and returns a ComponentAdapter on the given * label with the specified selection and editable state. IsLeaf returns * the same value as selected. HasFocus returns selected && editable. * * @param label the adapter's component * @param selected the adapter's selected property * @param editable the adapter's editable property * @return a ComponentAdapter of the label with the given properties. */ protected ComponentAdapter createComponentAdapter(final JLabel label, final boolean selected, final boolean editable) { ComponentAdapter adapter = new ComponentAdapter(label) { @Override public Object getValueAt(int row, int column) { return label.getText(); } @Override public Object getFilteredValueAt(int row, int column) { return getValueAt(row, column); } @Override public Object getValue() { return getValueAt(row, column); } @Override public void setValueAt(Object aValue, int row, int column) { // not implemented } @Override public boolean isCellEditable(int row, int column) { return isEditable(); } @Override public boolean hasFocus() { return isSelected() && isEditable(); } @Override public boolean isEditable() { return editable; } @Override public boolean isSelected() { return selected; } @Override public boolean isLeaf() { return isSelected(); } @Override public String getColumnName(int columnIndex) { return null; } }; return adapter; } /** * Creates and returns a ComponentAdapter on the given * label. The labels text is parsed as BigDecimal. * * @param label * @return */ protected ComponentAdapter createBigDecimalComponentAdapter(final JLabel label) { ComponentAdapter adapter = new ComponentAdapter(label) { @Override public Object getValueAt(int row, int column) { return new BigDecimal(label.getText()); } @Override public Object getFilteredValueAt(int row, int column) { return getValueAt(row, column); } @Override public Object getValue() { return getValueAt(row, column); } @Override public void setValueAt(Object aValue, int row, int column) { // TODO Auto-generated method stub } @Override public boolean isCellEditable(int row, int column) { // TODO Auto-generated method stub return false; } @Override public boolean hasFocus() { // TODO Auto-generated method stub return false; } @Override public boolean isEditable() { return false; } @Override public boolean isSelected() { return false; } @Override public String getColumnName(int columnIndex) { return null; } }; return adapter; } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/CompoundHighlighterTest.java0000644000175000017500000004407211210401722027346 0ustar tonytony/* * $Id: CompoundHighlighterTest.java,v 1.3 2008/10/11 20:42:31 rah003 Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.decorator; import java.awt.Color; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.UIManager; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.renderer.JRendererLabel; import org.jdesktop.test.ChangeReport; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * Test CompoundHighlighter. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class CompoundHighlighterTest extends InteractiveTestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger .getLogger(CompoundHighlighterTest.class.getName()); protected JLabel backgroundNull ; protected JLabel foregroundNull; protected JLabel allNull; protected JRendererLabel allColored; protected Color background = Color.RED; protected Color foreground = Color.BLUE; protected Color unselectedBackground = Color.CYAN; protected Color unselectedForeground = Color.GREEN; protected Color selectedBackground = Color.LIGHT_GRAY; protected Color selectedForeground = Color.MAGENTA; protected ColorHighlighter emptyHighlighter; // flag used in setup to explicitly choose LF protected boolean defaultToSystemLF; @Override protected void setUp() { backgroundNull = new JLabel("test"); backgroundNull.setForeground(foreground); backgroundNull.setBackground(null); foregroundNull = new JLabel("test"); foregroundNull.setForeground(null); foregroundNull.setBackground(background); allNull = new JLabel("test"); allNull.setForeground(null); allNull.setBackground(null); allColored = new JRendererLabel(); allColored.setText("test"); allColored.setForeground(foreground); allColored.setBackground(background); allColored.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); emptyHighlighter = new ColorHighlighter(); // make sure we have the same default for each test defaultToSystemLF = false; setSystemLF(defaultToSystemLF); } /** * Test that the client is messaged on change to a managed Highlighter. */ @Test public void testUpdateUI() { CompoundHighlighter support = new CompoundHighlighter(); // force loading of striping colors ColorHighlighter colorHighlighter = (ColorHighlighter) HighlighterFactory.createSimpleStriping(); Color uiColor = UIManager.getColor("UIColorHighlighter.stripingBackground"); if (uiColor == null) { LOG.info("cannot run test - no ui striping color"); return; } assertSame("sanity", uiColor, colorHighlighter.getBackground()); support.addHighlighter(colorHighlighter); Color changedUIColor = Color.RED; UIManager.put("UIColorHighlighter.stripingBackground", changedUIColor); support.updateUI(); try { assertSame("support must update ui color", changedUIColor, colorHighlighter.getBackground()); } finally { UIManager.put("UIColorHighlighter.stripingBackground", uiColor); } } /** * * Test that setting zero highlighter removes all. */ @Test public void testSetHighlightersReset() { CompoundHighlighter support = new CompoundHighlighter(); support.addHighlighter(new ColorHighlighter()); // sanity assertEquals(1, support.getHighlighters().length); support.setHighlighters(); assertEquals(0, support.getHighlighters().length); } /** * * Test that setting zero highlighter removes all. */ @Test public void testSetHighlightersResetRemoveListeners() { CompoundHighlighter support = new CompoundHighlighter(); ColorHighlighter colorHighlighter = new ColorHighlighter(); support.addHighlighter(colorHighlighter); // sanity assertEquals(1, support.getHighlighters().length); ChangeReport report = new ChangeReport(); support.addChangeListener(report); support.setHighlighters(); assertEquals(0, support.getHighlighters().length); assertEquals("compound must fire on modification", 1, report.getEventCount()); report.clear(); colorHighlighter.setBackground(Color.RED); assertEquals("compound must have removed listener", 0, report.getEventCount()); } /** * * Test that setting zero highlighter removes all. */ @Test public void testSetHighlightersResetSingleEvent() { ColorHighlighter colorHighlighter = new ColorHighlighter(); CompoundHighlighter support = new CompoundHighlighter(colorHighlighter, new ColorHighlighter()); // sanity assertEquals(2, support.getHighlighters().length); ChangeReport report = new ChangeReport(); support.addChangeListener(report); support.setHighlighters(); assertEquals(0, support.getHighlighters().length); assertEquals("compound must fire on modification", 1, report.getEventCount()); } /** * * Test that setting zero highlighter removes all. */ @Test public void testSetHighlightersSingleEvent() { ColorHighlighter colorHighlighter = new ColorHighlighter(); CompoundHighlighter support = new CompoundHighlighter(); ChangeReport report = new ChangeReport(); support.addChangeListener(report); support.setHighlighters(colorHighlighter, new ColorHighlighter()); assertEquals(2, support.getHighlighters().length); assertEquals("compound must fire on modification", 1, report.getEventCount()); } /** * * Test that setting zero Highlighters on empty compound does not fire. */ @Test public void testSetHighlightersResetEmptyNoEvent() { CompoundHighlighter support = new CompoundHighlighter(); ChangeReport report = new ChangeReport(); support.addChangeListener(report); support.setHighlighters(); assertEquals(0, support.getHighlighters().length); assertEquals("compound must not fire without modification", 0, report.getEventCount()); } /** * Sanity: handles empty array. */ @Test public void testSetHighlightersEmptyArray() { CompoundHighlighter support = new CompoundHighlighter(); support.setHighlighters(new Highlighter[] {}); assertEquals(0, support.getHighlighters().length); assertSame(CompoundHighlighter.EMPTY_HIGHLIGHTERS, support.getHighlighters()); } /** * test if removeHighlighter behaves as doc'ed. * */ @Test public void testTableRemoveHighlighter() { CompoundHighlighter support = new CompoundHighlighter(); // test cope with null support.removeHighlighter(null); Highlighter presetHighlighter = new ColorHighlighter(); support.setHighlighters(presetHighlighter); Highlighter[] highlighters = support.getHighlighters(); // sanity assertEquals(1, highlighters.length); // remove uncontained support.removeHighlighter(new ColorHighlighter()); // assert no change assertSameContent(highlighters, support.getHighlighters()); support.removeHighlighter(presetHighlighter); assertEquals(0, support.getHighlighters().length); } /** * test if addHighlighter behaves as doc'ed. * */ @Test public void testTableAddHighlighter() { CompoundHighlighter support = new CompoundHighlighter(); Highlighter presetHighlighter = new ColorHighlighter(); // add the first support.addHighlighter(presetHighlighter); // assert that it is added assertEquals(1, support.getHighlighters().length); assertAsLast(support.getHighlighters(), presetHighlighter); Highlighter highlighter = new ColorHighlighter(); // add the second support.addHighlighter(highlighter); assertEquals(2, support.getHighlighters().length); // assert that it is appended assertAsLast(support.getHighlighters(), highlighter); } /** * Test strict enforcement of not null allowed in setHighlighters. */ @Test public void testSetHighlightersNull() { CompoundHighlighter table = new CompoundHighlighter(); try { table.setHighlighters((Highlighter) null); fail("illegal to call setHighlighters(null)"); } catch (NullPointerException e) { // expected } } /** * Test strict enforcement of not null allowed in setHighlighters. */ @Test public void testSetHighlightersWithNullArray() { CompoundHighlighter table = new CompoundHighlighter(); try { table.setHighlighters((Highlighter[]) null); fail("illegal to call setHighlighters(null)"); } catch (NullPointerException e) { // expected } } /** * Test strict enforcement of not null allowed in setHighlighters. */ @Test public void testSetHighlightersArrayNullElement() { CompoundHighlighter table = new CompoundHighlighter(); try { table.setHighlighters(new Highlighter[] {null}); fail("illegal to call setHighlighters(null)"); } catch (NullPointerException e) { // expected } } //----------------------- CompoundHighlighter /** * there had been exceptions when adding/removing highlighters to/from * an initially empty pipeline. */ @Test public void testAddToEmptyCompoundHiglighter() { CompoundHighlighter pipeline = new CompoundHighlighter(); pipeline.addHighlighter(new ColorHighlighter()); } @Test public void testRemoveFromEmptyCompoundHighlighter() { CompoundHighlighter pipeline = new CompoundHighlighter(); pipeline.removeHighlighter(new ColorHighlighter()); } @Test public void testApplyEmptyCompoundHighlighter() { CompoundHighlighter pipeline = new CompoundHighlighter(); pipeline.highlight(new JLabel(), createComponentAdapter(new JLabel(), false)); } /* */ @Test public void testAddRemoveHighlighter() { CompoundHighlighter pipeline = new CompoundHighlighter( new ColorHighlighter(Color.white, new Color(0xF0, 0xF0, 0xE0)), new ColorHighlighter(null, foreground) ); ColorHighlighter hl = new ColorHighlighter(Color.blue, Color.red); ColorHighlighter hl2 = new ColorHighlighter(Color.white, Color.black); // added highlighter should be appended pipeline.addHighlighter(hl); Highlighter[] hls = pipeline.getHighlighters(); assertTrue(hls.length == 3); assertTrue(hls[2] == hl); // added highlighter should be prepended pipeline.addHighlighter(hl2, true); hls = pipeline.getHighlighters(); assertTrue(hls.length == 4); assertTrue(hls[0] == hl2); // remove highlighter pipeline.removeHighlighter(hl); hls = pipeline.getHighlighters(); assertTrue(hls.length == 3); for (int i = 0; i < hls.length; i++) { assertTrue(hls[i] != hl); } // remove another highligher pipeline.removeHighlighter(hl2); hls = pipeline.getHighlighters(); assertTrue(hls.length == 2); for (int i = 0; i < hls.length; i++) { assertTrue(hls[i] != hl2); } } //----------------- testing change notification of pipeline /** * @todo - how to handle same highlighter inserted more than once? */ @Test public void testCompoundHighlighterWithDuplicates() { } /** * test doc'ed NPE when adding null Highlighter. * */ @Test public void testCompoundHighlighterAddNull() { CompoundHighlighter pipeline = new CompoundHighlighter(); try { pipeline.addHighlighter(null); fail("compoundHighlighter must not accept null highlighter"); } catch(NullPointerException ex) { } ComponentAdapter adapter = createComponentAdapter(allColored, false); // was added even with NPE. pipeline.highlight(allColored, adapter); } @Test public void testCompoundHighlighterChange() { ColorHighlighter highlighter = new ColorHighlighter(); CompoundHighlighter pipeline = new CompoundHighlighter(); ChangeReport changeReport = new ChangeReport(); pipeline.addChangeListener(changeReport); int count = changeReport.getEventCount(); pipeline.addHighlighter(highlighter); assertEquals("event count must be increased", ++count, changeReport.getEventCount() ); assertCompoundHighlighterChange(highlighter, pipeline, changeReport); } @Test public void testCompoundHighlighterChangeConstructor() { ColorHighlighter highlighter = new ColorHighlighter(); CompoundHighlighter pipeline = new CompoundHighlighter(highlighter); ChangeReport changeReport = new ChangeReport(); pipeline.addChangeListener(changeReport); assertCompoundHighlighterChange(highlighter, pipeline, changeReport); } private void assertCompoundHighlighterChange(ColorHighlighter highlighter, CompoundHighlighter pipeline, ChangeReport changeReport) { int count = changeReport.getEventCount(); highlighter.setBackground(Color.red); assertEquals("event count must be increased", ++count, changeReport.getEventCount() ); assertEquals("event source must be pipeline", pipeline, changeReport.getLastEvent().getSource()); pipeline.removeHighlighter(highlighter); assertEquals("event count must be increased", ++count, changeReport.getEventCount() ); pipeline.removeHighlighter(highlighter); assertEquals("event count must not be increased", count, changeReport.getEventCount() ); highlighter.setBackground(Color.BLUE); assertEquals("event count must not be increased", count, changeReport.getEventCount() ); } /** * Same content in both. * @param highlighters * @param highlighters2 */ private void assertSameContent(Highlighter[] highlighters, Highlighter[] highlighters2) { assertEquals(highlighters.length, highlighters2.length); for (int i = 0; i < highlighters.length; i++) { assertSame("must contain same element", highlighters[i], highlighters2[i]); } } /** * Last in list. * * @param highlighters * @param highlighter */ private void assertAsLast(Highlighter[] highlighters, Highlighter highlighter) { assertTrue("pipeline must not be empty", highlighters.length > 0); assertSame("highlighter must be added as last", highlighter, highlighters[highlighters.length - 1]); } // --------------------- factory methods /** * Creates and returns a ComponentAdapter on the given * label with the unselected state. * * @param label * @param selected * @return */ protected ComponentAdapter createComponentAdapter(final JLabel label) { return createComponentAdapter(label, false); } /** * Creates and returns a ComponentAdapter on the given * label with the specified selection state. * * @param label * @param selected * @return */ protected ComponentAdapter createComponentAdapter(final JLabel label, final boolean selected) { ComponentAdapter adapter = new ComponentAdapter(label) { @Override public Object getValueAt(int row, int column) { return label.getText(); } @Override public Object getFilteredValueAt(int row, int column) { return getValueAt(row, column); } @Override public Object getValue() { return getValueAt(row, column); } @Override public void setValueAt(Object aValue, int row, int column) { // TODO Auto-generated method stub } @Override public boolean isCellEditable(int row, int column) { // TODO Auto-generated method stub return false; } @Override public boolean hasFocus() { // TODO Auto-generated method stub return false; } @Override public boolean isEditable() { return false; } @Override public boolean isSelected() { return selected; } @Override public String getColumnName(int columnIndex) { return null; } }; return adapter; } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/HighlighterTest.java0000644000175000017500000010260411210401722025635 0ustar tonytony/* * $Id: HighlighterTest.java,v 1.43 2009/01/21 18:37:24 kschaefe Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.decorator; import java.awt.Color; import java.awt.Component; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.plaf.ColorUIResource; import junit.framework.TestCase; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.decorator.HighlighterFactory.UIColorHighlighter; import org.jdesktop.swingx.painter.AbstractAreaPainter; import org.jdesktop.swingx.painter.MattePainter; import org.jdesktop.swingx.painter.Painter; import org.jdesktop.swingx.renderer.JRendererLabel; import org.jdesktop.swingx.test.XTestUtils; import org.jdesktop.test.ChangeReport; import org.jdesktop.test.PropertyChangeReport; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * * Tests for Highlighters after overhaul. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class HighlighterTest extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(HighlighterTest.class .getName()); protected JLabel backgroundNull ; protected JLabel foregroundNull; protected JLabel allNull; protected JRendererLabel allColored; protected Color background = Color.RED; protected Color foreground = Color.BLUE; protected Color unselectedBackground = Color.CYAN; protected Color unselectedForeground = Color.GREEN; protected Color selectedBackground = Color.LIGHT_GRAY; protected Color selectedForeground = Color.MAGENTA; protected ColorHighlighter emptyHighlighter; // flag used in setup to explicitly choose LF protected boolean defaultToSystemLF; @Override @Before public void setUp() { backgroundNull = new JLabel("test"); backgroundNull.setForeground(foreground); backgroundNull.setBackground(null); foregroundNull = new JLabel("test"); foregroundNull.setForeground(null); foregroundNull.setBackground(background); allNull = new JLabel("test"); allNull.setForeground(null); allNull.setBackground(null); allColored = new JRendererLabel(); allColored.setText("test"); allColored.setForeground(foreground); allColored.setBackground(background); allColored.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); emptyHighlighter = new ColorHighlighter(); // make sure we have the same default for each test defaultToSystemLF = false; InteractiveTestCase.setSystemLF(defaultToSystemLF); } //-------------------PainterHighlighter @Test public void testPainterHighlighterConstructors() { PainterHighlighter hl = new PainterHighlighter(); assertEquals(HighlightPredicate.ALWAYS, hl.getHighlightPredicate()); assertNull(hl.getPainter()); Painter mattePainter = new MattePainter(); PainterHighlighter withPainter = new PainterHighlighter(mattePainter); assertEquals(HighlightPredicate.ALWAYS, withPainter.getHighlightPredicate()); assertEquals(mattePainter, withPainter.getPainter()); PainterHighlighter withPredicate = new PainterHighlighter(HighlightPredicate.NEVER); assertEquals(HighlightPredicate.NEVER, withPredicate.getHighlightPredicate()); assertEquals(null, withPredicate.getPainter()); PainterHighlighter all = new PainterHighlighter(HighlightPredicate.NEVER, mattePainter); assertEquals(HighlightPredicate.NEVER, all.getHighlightPredicate()); assertEquals(mattePainter, all.getPainter()); } @Test public void testPainterHighlighterSetPainterChangeNotificatioon() { PainterHighlighter hl = new PainterHighlighter(); ChangeReport report = new ChangeReport(); hl.addChangeListener(report); MattePainter mattePainter = new MattePainter(); hl.setPainter(mattePainter); assertEquals(mattePainter, hl.getPainter()); assertEquals(1, report.getEventCount()); } @Test public void testPainterHighlighterSetPainterNoChangeNotificatioon() { MattePainter mattePainter = new MattePainter(); PainterHighlighter hl = new PainterHighlighter(mattePainter); ChangeReport report = new ChangeReport(); hl.addChangeListener(report); hl.setPainter(mattePainter); assertEquals(0, report.getEventCount()); } /** * Issue #851-swingx: Highlighter must notify on painter property change */ @Test public void testPainterHighlighterPainterPropertyChangeNotificatioon() { PainterHighlighter hl = new PainterHighlighter(); Color red = Color.RED; MattePainter mattePainter = new MattePainter(red); assertEquals(red, mattePainter.getFillPaint()); PropertyChangeReport p = new PropertyChangeReport(); mattePainter.addPropertyChangeListener(p); hl.setPainter(mattePainter); assertEquals(mattePainter, hl.getPainter()); ChangeReport report = new ChangeReport(); hl.addChangeListener(report); mattePainter.setFillPaint(Color.BLUE); assertEquals(p.getEventCount(), report.getEventCount()); } /** * Issue #851-swingx: Highlighter must notify on painter property change. * * Here: the Highlighter must not fire if the painter is changed during * the decoration. Supported in base to ease subclassing and keep * backward compatibility */ @Test public void testPainterHighlighterPainterPropertyNotNotifyInternalChange() { Color red = Color.RED; MattePainter mattePainter = new MattePainter(red); assertEquals(red, mattePainter.getFillPaint()); PainterHighlighter hl = new PainterHighlighter(mattePainter) { @Override protected Component doHighlight(Component component, ComponentAdapter adapter) { ((AbstractAreaPainter) getPainter()).setFillPaint(Color.BLUE); return super.doHighlight(component, adapter); } }; ChangeReport report = new ChangeReport(); hl.addChangeListener(report); ComponentAdapter adapter = createComponentAdapter(allColored, false); hl.highlight(allColored, adapter); assertEquals(Color.BLUE, mattePainter.getFillPaint()); assertEquals(0, report.getEventCount()); } @Test public void testPainterHighlighterUsePainter() { ComponentAdapter adapter = createComponentAdapter(allColored, false); MattePainter mattePainter = new MattePainter(); PainterHighlighter hl = new PainterHighlighter(mattePainter); hl.highlight(allColored, adapter); // sanity assertEquals(mattePainter, allColored.getPainter()); } @Test public void testPainterHighlighterNotUseNullPainter() { ComponentAdapter adapter = createComponentAdapter(allColored, false); PainterHighlighter hl = new PainterHighlighter(); MattePainter mattePainter = new MattePainter(); allColored.setPainter(mattePainter); hl.highlight(allColored, adapter); // sanity assertEquals(mattePainter, allColored.getPainter()); } @Test public void testPainterHighlighterIgnoreNotPainterAware() { ComponentAdapter adapter = createComponentAdapter(foregroundNull, false); MattePainter mattePainter = new MattePainter(); PainterHighlighter hl = new PainterHighlighter(mattePainter); hl.highlight(foregroundNull, adapter); } //-------------------- factory /** * highlight every second */ @Test public void testSimpleStriping() { ComponentAdapter adapter = createComponentAdapter(allColored, false); Highlighter h = HighlighterFactory.createSimpleStriping(unselectedBackground); h.highlight(allColored, adapter); // no effect on first row assertEquals(background, allColored.getBackground()); adapter.row = 1; h.highlight(allColored, adapter); assertEquals(unselectedBackground, allColored.getBackground()); } /** * highlight every second */ @Test public void testAlternateStriping() { ComponentAdapter adapter = createComponentAdapter(allColored, false); Highlighter h = HighlighterFactory.createAlternateStriping(unselectedBackground, selectedBackground); h.highlight(allColored, adapter); // first color on first row assertEquals(unselectedBackground, allColored.getBackground()); adapter.row = 1; h.highlight(allColored, adapter); // second color on second row assertEquals(selectedBackground, allColored.getBackground()); } //-------------- IconHighlighter @Test public void testIconHighlighterNotHighlightUnable() { Icon icon = XTestUtils.loadDefaultIcon(); JTextField allColored = new JTextField(); IconHighlighter hl = new IconHighlighter(icon); ComponentAdapter adapter = createDummyComponentAdapter(allColored); assertNotNull(hl.highlight(allColored, adapter)); } @Test public void testIconHighlighterNotHighlight() { Icon icon = XTestUtils.loadDefaultIcon(); allColored.setIcon(icon); IconHighlighter hl = new IconHighlighter(); assertNotNull(hl.highlight(allColored, createComponentAdapter(allColored))); assertEquals(icon, allColored.getIcon()); } @Test public void testIconHighlighterHighlight() { Icon icon = XTestUtils.loadDefaultIcon(); IconHighlighter hl = new IconHighlighter(icon); assertNotNull(hl.highlight(allColored, createComponentAdapter(allColored))); assertEquals(icon, allColored.getIcon()); } @Test public void testIconHighlightIconChangeNotification() { IconHighlighter hl = new IconHighlighter(); Icon icon = XTestUtils.loadDefaultIcon(); ChangeReport report = new ChangeReport(); hl.addChangeListener(report); hl.setIcon(icon); assertEquals(icon, hl.getIcon()); assertEquals(1, report.getEventCount()); } @Test public void testIconHighlightIconNoChangeNotification() { Icon icon = XTestUtils.loadDefaultIcon(); IconHighlighter hl = new IconHighlighter(icon); ChangeReport report = new ChangeReport(); hl.addChangeListener(report); hl.setIcon(icon); assertEquals(0, report.getEventCount()); } @Test public void testIconHighlighterConstructors() { IconHighlighter empty = new IconHighlighter(); assertIconHighlighter(empty, HighlightPredicate.ALWAYS, null); IconHighlighter never = new IconHighlighter(HighlightPredicate.NEVER); assertIconHighlighter(never, HighlightPredicate.NEVER, null); Icon icon = XTestUtils.loadDefaultIcon(); IconHighlighter withIcon = new IconHighlighter(icon); assertIconHighlighter(withIcon, HighlightPredicate.ALWAYS, icon); IconHighlighter complete = new IconHighlighter(HighlightPredicate.NEVER, icon); assertIconHighlighter(complete, HighlightPredicate.NEVER, icon); } private void assertIconHighlighter(IconHighlighter hl, HighlightPredicate predicate, Icon icon) { assertEquals(predicate, hl.getHighlightPredicate()); assertEquals(icon, hl.getIcon()); } //-------------- BorderHighlighter /** * Test that all properties have setters and fire a changeEvent. */ @Test public void testBorderHighlightSetters() { BorderHighlighter hl = new BorderHighlighter(); ChangeReport report = new ChangeReport(); hl.addChangeListener(report); hl.setInner(!hl.isInner()); assertEquals(1, report.getEventCount()); report.clear(); hl.setCompound(!hl.isCompound()); assertEquals(1, report.getEventCount()); } /** * Test setBorder and fire a changeEvent. * (setter was missing) */ @Test public void testBorderHighlightSetBorder() { BorderHighlighter hl = new BorderHighlighter(); ChangeReport report = new ChangeReport(); hl.addChangeListener(report); Border padding = BorderFactory.createLineBorder(Color.RED, 3); hl.setBorder(padding); assertEquals("sanity: border set", padding, hl.getBorder()); assertEquals("must fire on setting border", 1, report.getEventCount()); report.clear(); hl.setBorder(padding); assertEquals("must not fire on setting the same border", 0, report.getEventCount()); hl.setBorder(null); assertEquals("must fire on setting border null", 1, report.getEventCount()); report.clear(); hl.setBorder(null); assertEquals("must not fire setting same null border", 0, report.getEventCount()); } @Test public void testBorderPaddingNull() { BorderHighlighter empty = new BorderHighlighter(); Border border = allColored.getBorder(); empty.highlight(allColored, createComponentAdapter(allColored)); assertEquals("borderHighlighter without padding must not change the component", border, allColored.getBorder()); } @Test public void testBorderPaddingCompoundNotInner() { Border padding = BorderFactory.createLineBorder(Color.RED, 3); BorderHighlighter empty = new BorderHighlighter(padding); empty.setInner(true); Border border = allColored.getBorder(); empty.highlight(allColored, createComponentAdapter(allColored)); Border compound = allColored.getBorder(); assertTrue(compound instanceof CompoundBorder); assertEquals("borderHighlighter with padding and outer compound must have outside", border, ((CompoundBorder) compound).getOutsideBorder()); assertEquals("borderHighlighter with padding and outer compound must have inside", padding, ((CompoundBorder) compound).getInsideBorder()); } @Test public void testBorderPaddingCompoundInner() { Border padding = BorderFactory.createLineBorder(Color.RED, 3); BorderHighlighter empty = new BorderHighlighter(padding); Border border = allColored.getBorder(); empty.highlight(allColored, createComponentAdapter(allColored)); Border compound = allColored.getBorder(); assertTrue(compound instanceof CompoundBorder); assertEquals("borderHighlighter with padding and outer compound must have outside", padding, ((CompoundBorder) compound).getOutsideBorder()); assertEquals("borderHighlighter with padding and outer compound must have inside", border, ((CompoundBorder) compound).getInsideBorder()); } @Test public void testBorderPaddingReplace() { Border padding = BorderFactory.createLineBorder(Color.RED, 3); BorderHighlighter empty = new BorderHighlighter(null, padding, false); empty.highlight(allColored, createComponentAdapter(allColored)); assertEquals("borderHighlighter padding and not-compound must replace", padding, allColored.getBorder()); } @Test public void testBorderPaddingSetBorderIfComponentBorderNull() { Border padding = BorderFactory.createLineBorder(Color.RED, 3); BorderHighlighter empty = new BorderHighlighter(padding); allColored.setBorder(null); empty.highlight(allColored, createComponentAdapter(allColored)); assertEquals("borderHighlighter padding and null component border must set", padding, allColored.getBorder()); } @Test public void testBorderConstructors() { BorderHighlighter empty = new BorderHighlighter(); assertBorderHLState(empty, HighlightPredicate.ALWAYS, null, true, false); BorderHighlighter predicate = new BorderHighlighter(HighlightPredicate.NEVER); assertBorderHLState(predicate, HighlightPredicate.NEVER, null, true, false); Border padding = BorderFactory.createLineBorder(Color.RED, 3); BorderHighlighter paddingOnly = new BorderHighlighter(padding); assertBorderHLState(paddingOnly, HighlightPredicate.ALWAYS, padding, true, false); BorderHighlighter paddingPred = new BorderHighlighter(HighlightPredicate.NEVER, padding); assertBorderHLState(paddingPred, HighlightPredicate.NEVER, padding, true, false); BorderHighlighter paddingPredCompound = new BorderHighlighter(HighlightPredicate.NEVER, padding, false); assertBorderHLState(paddingPredCompound, HighlightPredicate.NEVER, padding, false, false); BorderHighlighter all = new BorderHighlighter(HighlightPredicate.NEVER, padding, false, true); assertBorderHLState(all, HighlightPredicate.NEVER, padding, false, true); } private void assertBorderHLState(BorderHighlighter hl, HighlightPredicate predicate, Border border, boolean compound, boolean inner) { assertEquals(predicate, hl.getHighlightPredicate()); assertEquals(border, hl.getBorder()); assertEquals(compound, hl.isCompound()); assertEquals(inner, hl.isInner()); } //------------------ ShadingColorHighlighter @Test public void testShadingConstructors() { ShadingColorHighlighter shading = new ShadingColorHighlighter(); assertColorsAndPredicate(shading, HighlightPredicate.ALWAYS, null, null, null, null); ShadingColorHighlighter never = new ShadingColorHighlighter(HighlightPredicate.NEVER); assertColorsAndPredicate(never, HighlightPredicate.NEVER, null, null, null, null); } @Test public void testShadingEffect() { } //----------------------- Colorhighlighter constructors /** * Test constructor of ColorHighlighter. */ @Test public void testConstructors() { ColorHighlighter empty = new ColorHighlighter(); assertColorsAndPredicate(empty, HighlightPredicate.ALWAYS, null, null, null, null); ColorHighlighter predicateOnly = new ColorHighlighter(HighlightPredicate.NEVER); assertColorsAndPredicate(predicateOnly, HighlightPredicate.NEVER, null, null, null, null); ColorHighlighter normal = new ColorHighlighter(background, foreground); assertColorsAndPredicate(normal, HighlightPredicate.ALWAYS, background, foreground, null, null); ColorHighlighter normalNever = new ColorHighlighter(HighlightPredicate.NEVER, background, foreground); assertColorsAndPredicate(normalNever, HighlightPredicate.NEVER, background, foreground, null, null); ColorHighlighter full = new ColorHighlighter(background, foreground, selectedBackground , selectedForeground); assertColorsAndPredicate(full, HighlightPredicate.ALWAYS, background, foreground, selectedBackground, selectedForeground); ColorHighlighter fullNever = new ColorHighlighter(HighlightPredicate.NEVER, background, foreground , selectedBackground, selectedForeground); assertColorsAndPredicate(fullNever, HighlightPredicate.NEVER, background, foreground, selectedBackground, selectedForeground); } private void assertColorsAndPredicate(ColorHighlighter highlighter, HighlightPredicate predicate, Color background, Color foreground, Color selectedBackground, Color selectedForeground) { assertEquals("background", background, highlighter.getBackground()); assertEquals("foreground", foreground, highlighter.getForeground()); assertEquals("selectedbackground", selectedBackground, highlighter.getSelectedBackground()); assertEquals("selectedForeground", selectedForeground, highlighter.getSelectedForeground()); assertEquals("predicate", predicate, highlighter.getHighlightPredicate()); } //----------------- testing change notification ColorHighlighter /** * Test ui dependent color is updated. */ @Test public void testCustomUIColorHighlighter() { UIColorHighlighter h = new UIColorHighlighter(); Color uiBackground = h.getBackground(); Color uiColor = UIManager.getColor("UIColorHighlighter.stripingBackground"); // very unusual ui striping Color color = new ColorUIResource(Color.BLACK); if (color.equals(uiBackground)) { LOG.info("cannot run testUIColorHighlight - ui striping same as test color"); return; } UIManager.put("UIColorHighlighter.stripingBackground", color); try { h.updateUI(); assertEquals(color, h.getBackground()); } finally { // remove custom setting. DO NOT set the old uiColor manually! UIManager.put("UIColorHighlighter.stripingBackground", null); } // sanity - reset h.updateUI(); assertNotNull(h.getBackground()); assertNotSame(color.getRGB(), h.getBackground().getRGB()); // can be generic grey as well (as per HighLighterFactory treatment of cases with no LAF defined) boolean found = h.getBackground().equals( uiColor) || h.getBackground().equals(HighlighterFactory.GENERIC_GRAY); assertTrue("Found " + h.getBackground() + " while expected " + uiColor, found); } @Test public void testColorHighlighterChangeNotification() { ColorHighlighter highlighter = new ColorHighlighter(); assertBaseHighlighterChange(highlighter, 1); } @Test public void testColorHighlighterNoChangeNotification() { ColorHighlighter highlighter = new ColorHighlighter(HighlightPredicate.NEVER, Color.RED, Color.RED, Color.RED, Color.RED); assertBaseHighlighterChange(highlighter, 0); } private void assertBaseHighlighterChange(ColorHighlighter highlighter, int count ) { ChangeReport changeReport = new ChangeReport(); highlighter.addChangeListener(changeReport); highlighter.setBackground(Color.red); assertEquals("event count ", count, changeReport.getEventCount() ); changeReport.clear(); highlighter.setForeground(Color.red); assertEquals("event count ", count, changeReport.getEventCount() ); changeReport.clear(); highlighter.setSelectedBackground(Color.red); assertEquals("event count ", count, changeReport.getEventCount() ); changeReport.clear(); highlighter.setSelectedForeground(Color.red); assertEquals("event count ", count, changeReport.getEventCount() ); changeReport.clear(); highlighter.setHighlightPredicate(HighlightPredicate.NEVER); assertEquals("event count ", count, changeReport.getEventCount()); } /** * test that the base implementation is polite and fires only if * the predicate is really changed. */ @Test public void testHighlightPredicateNoChangeNotification() { AbstractHighlighter hl = new AbstractHighlighter() { @Override protected Component doHighlight(Component component, ComponentAdapter adapter) { return component; } }; ChangeReport report = new ChangeReport(); hl.addChangeListener(report); hl.setHighlightPredicate(HighlightPredicate.ALWAYS); assertEquals("must not fire on setting same predicate", 0, report.getEventCount()); report.clear(); hl.setHighlightPredicate(null); assertEquals("must not fire on setting same predicate", 0, report.getEventCount()); } //---------------------- exposing highlighter probs with null component color @Test public void testLabelSanity() { assertNull("foreground must be null", foregroundNull.getForeground()); assertNotNull("background must not be null", foregroundNull.getBackground()); assertNull("background must be null", backgroundNull.getBackground()); assertNotNull("foreground must not be null", backgroundNull.getForeground()); assertNull("foreground must be null", allNull.getForeground()); assertNull("background must be null", allNull.getBackground()); assertEquals(background, allColored.getBackground()); assertEquals(foreground, allColored.getForeground()); } // --------------------- highlightPredicate /** * test predicate defaults to always */ @Test public void testDefaultPredicate() { ColorHighlighter highlighter = new ColorHighlighter(); assertSame(HighlightPredicate.ALWAYS, highlighter.getHighlightPredicate()); } /** * test highlight respects predicate never. * */ @Test public void testHighlightPredicate() { ColorHighlighter highlighter = new ColorHighlighter(unselectedBackground, unselectedForeground); highlighter.setHighlightPredicate(HighlightPredicate.NEVER); ComponentAdapter adapter = createComponentAdapter(allColored, false); highlighter.highlight(allColored, adapter); // assert unchanged colors assertEquals(foreground, allColored.getForeground()); assertEquals(background, allColored.getBackground()); } //------------------------- test highlight effects ColorHighlighter /** * Test ColorHighlighter decorate unselected cell. * */ @Test public void testApplyColorHighlighterUnselected() { ComponentAdapter adapter = createComponentAdapter(allColored, false); ColorHighlighter highlighter = new ColorHighlighter(unselectedBackground, unselectedForeground, selectedBackground, selectedForeground); assertApplied(highlighter, allColored, adapter); } /** * Test ColorHighlighter decorate selected cell. * */ @Test public void testApplyColorHighlighterSelected() { ComponentAdapter adapter = createComponentAdapter(allColored, true); ColorHighlighter highlighter = new ColorHighlighter(unselectedBackground, unselectedForeground, selectedBackground, selectedForeground); assertApplied(highlighter, allColored, adapter); } /** * test that same renderer is returned. * */ @Test public void testReturnHighlightedComponent() { ComponentAdapter adapter = createComponentAdapter(allColored, false); ColorHighlighter highlighter = new ColorHighlighter(unselectedBackground, unselectedForeground); assertSame(allColored, highlighter.highlight(allColored, adapter)); } /** * Issue #178-swingx: Highlighters always change the selection color. * sanity test to see if non-selected colors are unchanged. */ @Test public void testUnSelectedDoNothingHighlighter() { ComponentAdapter adapter = createComponentAdapter(allColored, false); assertApplied(emptyHighlighter, allColored, adapter); } /** * Issue #178-swingx: Highlighters always change the selection color. */ @Test public void testSelectedDoNothingHighlighter() { ComponentAdapter adapter = createComponentAdapter(allColored, true); assertApplied(emptyHighlighter, allColored, adapter); } /** * running assertion for all highlighter colors, depending on selection of adapter and * colors set/not set in highlighter. * * @param highlighter * @param label * @param adapter */ protected void assertApplied(ColorHighlighter highlighter, Component label, ComponentAdapter adapter) { Color labelForeground = label.getForeground(); Color labelBackground = label.getBackground(); highlighter.highlight(label, adapter); if (!adapter.isSelected()) { if (highlighter.getBackground() == null) { assertEquals("unselected: background must not be changed", labelBackground, label.getBackground()); } else { assertEquals("unselected: background must be changed", highlighter.getBackground(), label.getBackground()); } if (highlighter.getForeground() == null) { assertEquals("unselected: forground must not be changed", labelForeground, label.getForeground()); } else { assertEquals("unselected: forground must be changed", highlighter.getForeground(), label.getForeground()); } } else { if (highlighter.getSelectedBackground() == null) { assertEquals("selected: background must not be changed", labelBackground, label.getBackground()); } else { assertEquals("selected: background must be changed", highlighter.getSelectedBackground(), label.getBackground()); } if (highlighter.getSelectedForeground() == null) { assertEquals("selected: forground must not be changed", labelForeground, label.getForeground()); } else { assertEquals("selected: forground must be changed", highlighter.getSelectedForeground(), label.getForeground()); } } } //------------------ UIDependent /** * test that the ui color highlighter comes up with * the ui-setting. */ @Test public void testInitialUIColorHighlighter() { ColorHighlighter h = new UIColorHighlighter(); Color uiBackground = h.getBackground(); Color uiColor = UIManager.getColor("UIColorHighlighter.stripingBackground"); if (uiColor == null) { LOG.info("cannot test initial ui striping color - UIManager has null"); } assertEquals(uiColor, uiBackground); } // --------------------- factory methods /** * Creates and returns a ComponentAdapter on the given * label with the unselected state. * * @param label * @param selected * @return */ protected ComponentAdapter createComponentAdapter(final JLabel label) { return createComponentAdapter(label, false); } /** * Creates and returns a ComponentAdapter on the given * label with the specified selection state. * * @param label * @param selected * @return */ protected ComponentAdapter createComponentAdapter(final JLabel label, final boolean selected) { ComponentAdapter adapter = new ComponentAdapter(label) { @Override public Object getValueAt(int row, int column) { return label.getText(); } @Override public Object getFilteredValueAt(int row, int column) { return getValueAt(row, column); } @Override public Object getValue() { return getValueAt(row, column); } @Override public void setValueAt(Object aValue, int row, int column) { // TODO Auto-generated method stub } @Override public boolean isCellEditable(int row, int column) { // TODO Auto-generated method stub return false; } @Override public boolean hasFocus() { // TODO Auto-generated method stub return false; } @Override public boolean isEditable() { return false; } @Override public boolean isSelected() { return selected; } @Override public String getColumnName(int columnIndex) { return null; } }; return adapter; } private ComponentAdapter createDummyComponentAdapter(JComponent allColored) { ComponentAdapter adapter = new ComponentAdapter(allColored) { @Override public Object getFilteredValueAt(int row, int column) { // TODO Auto-generated method stub return null; } @Override public Object getValueAt(int row, int column) { // TODO Auto-generated method stub return null; } @Override public boolean hasFocus() { // TODO Auto-generated method stub return false; } @Override public boolean isCellEditable(int row, int column) { // TODO Auto-generated method stub return false; } @Override public boolean isEditable() { // TODO Auto-generated method stub return false; } @Override public boolean isSelected() { // TODO Auto-generated method stub return false; } @Override public void setValueAt(Object value, int row, int column) { // TODO Auto-generated method stub } }; return adapter; } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/ComponentAdapterIssues.java0000644000175000017500000001510111210401722027171 0ustar tonytony/* * $Id: ComponentAdapterIssues.java,v 1.13 2009/01/22 13:08:50 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.decorator; import java.awt.Color; import java.util.logging.Logger; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXTree; import org.jdesktop.swingx.JXTreeTable; import org.jdesktop.swingx.renderer.DefaultTreeRenderer; import org.jdesktop.swingx.renderer.StringValue; import org.jdesktop.swingx.renderer.StringValues; import org.jdesktop.swingx.search.SearchFactory; import org.jdesktop.swingx.test.ComponentTreeTableModel; import org.jdesktop.swingx.treetable.TreeTableModel; import org.jdesktop.test.AncientSwingTeam; /** * Test to exposed known issues of ComponentAdapter. * * Ideally, there would be at least one failing test method per open * Issue in the issue tracker. Plus additional failing test methods for * not fully specified or not yet decided upon features/behaviour. * * * @author Jeanette Winzenburg */ public class ComponentAdapterIssues extends InteractiveTestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger .getLogger(ComponentAdapterIssues.class.getName()); public static void main(String[] args) { SearchFactory.getInstance().setUseFindBar(true); ComponentAdapterIssues test = new ComponentAdapterIssues(); try { test.runInteractiveTests(); } catch (Exception e) { e.printStackTrace(); } } private StringValue sv; /** * Issue ??-swingx: TreeTable doesn't return correct string value for hierarchical column. * * This is probably a variant of not using the table's renderer (at least I expect it * to be solved then at the latest). In the meantime, might want to do something special * for the hierarchical column? */ public void interactiveTreeTableStringValue() { TreeTableModel model = AncientSwingTeam.createNamedColorTreeTableModel(); JXTreeTable treeTable = new JXTreeTable(model); treeTable.setRootVisible(true); // treeTable.setTreeCellRenderer(new DefaultTreeRenderer(sv)); JXTree tree = new JXTree(model); // tree.setCellRenderer(new DefaultTreeRenderer(sv)); HighlightPredicate predicate = new PatternPredicate("R/G/B: -2", 0, PatternPredicate.ALL); ColorHighlighter hl = new ColorHighlighter(predicate, null, Color.RED); treeTable.addHighlighter(hl); tree.addHighlighter(hl); JXFrame frame = wrapWithScrollingInFrame(tree, treeTable, "string rep in hierarchical column"); show(frame); } /** * Issue ??-swingx: TreeTable doesn't return correct string value for hierarchical column. * * This is probably a variant of not using the table's renderer (at least I expect it * to be solved then at the latest). In the meantime, might want to do something special * for the hierarchical column? */ public void interactiveTreeTableStringValueComponent() { TreeTableModel model = new ComponentTreeTableModel(new JXFrame()); JXTreeTable treeTable = new JXTreeTable(model); treeTable.setRootVisible(true); treeTable.expandAll(); LOG.info(treeTable.getStringAt(3, 0)); // treeTable.setTreeCellRenderer(new DefaultTreeRenderer(sv)); JXTree tree = new JXTree(model); // tree.setCellRenderer(new DefaultTreeRenderer(sv)); HighlightPredicate predicate = new PatternPredicate("null", 0, PatternPredicate.ALL); ColorHighlighter hl = new ColorHighlighter(predicate, null, Color.RED); treeTable.addHighlighter(hl); tree.addHighlighter(hl); JXFrame frame = wrapWithScrollingInFrame( treeTable, "string rep in hierarchical column"); show(frame); } /** * Issue ??-swingx: TreeTable doesn't return correct string value for hierarchical column. * * This is probably a variant of not using the table's renderer (at least I expect it * to be solved then at the latest). In the meantime, might want to do something special * for the hierarchical column? */ public void interactiveTreeStringValueComponent() { TreeTableModel model = new ComponentTreeTableModel(new JXFrame()); JXTreeTable treeTable = new JXTreeTable(model); treeTable.setRootVisible(true); treeTable.expandAll(); LOG.info(treeTable.getStringAt(3, 0)); // treeTable.setTreeCellRenderer(new DefaultTreeRenderer(sv)); JXTree tree = new JXTree(model); // tree.setCellRenderer(new DefaultTreeRenderer(sv)); HighlightPredicate predicate = new PatternPredicate("null", 0, PatternPredicate.ALL); ColorHighlighter hl = new ColorHighlighter(predicate, null, Color.RED); treeTable.addHighlighter(hl); tree.addHighlighter(hl); JXFrame frame = wrapWithScrollingInFrame( tree, "string rep in hierarchical column"); show(frame); } /** * Creates and returns a StringValue which maps a Color to it's R/G/B rep, * prepending "R/G/B: " * * @return the StringValue for color. */ private StringValue createColorStringValue() { StringValue sv = new StringValue() { public String getString(Object value) { if (value instanceof Color) { Color color = (Color) value; return "R/G/B: " + color.getRGB(); } return StringValues.TO_STRING.getString(value); } }; return sv; } @Override protected void setUp() throws Exception { sv = createColorStringValue(); } public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/ListAsHighlighterClientTest.java0000644000175000017500000000466111210401722030120 0ustar tonytony/* * $Id: ListAsHighlighterClientTest.java,v 1.2 2008/10/11 20:42:31 rah003 Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.decorator; import java.beans.PropertyChangeListener; import org.jdesktop.swingx.JXList; /** * Test JXList as HighlighterClient. * * @author Jeanette Winzenburg */ public class ListAsHighlighterClientTest extends AbstractTestHighlighterClient { @Override protected HighlighterClient createHighlighterClient() { return createHighlighterClient(new JXList()); } private HighlighterClient createHighlighterClient(final JXList table) { HighlighterClient client = new HighlighterClient() { public void addHighlighter(Highlighter highlighter) { table.addHighlighter(highlighter); } public void addPropertyChangeListener(PropertyChangeListener l) { table.addPropertyChangeListener(l); } public Highlighter[] getHighlighters() { return table.getHighlighters(); } public void removeHighlighter(Highlighter highlighter) { table.removeHighlighter(highlighter); } public void removePropertyChangeListener(PropertyChangeListener l) { table.removePropertyChangeListener(l); } public void setHighlighters(Highlighter... highlighters) { table.setHighlighters(highlighters); } public void updateUI() { table.updateUI(); } }; return client; } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/SorterTest.java0000644000175000017500000001575611210401722024670 0ustar tonytony/* * $Id: SorterTest.java,v 1.9 2008/10/11 20:42:31 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.decorator; import java.text.Collator; import java.util.Comparator; import java.util.Locale; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; import junit.framework.TestCase; /** * Unit test for divers sort-related classes/issues. * *

    *
  • SortKey *
  • SortOrder *
  • Sorter *
* @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class SorterTest extends TestCase { /** * test that sorter returns SortKey * synched to internal state. * */ @Test public void testSorterSynchedToSortKey() { int column = 1; Sorter sorter = new ShuttleSorter(column, false, Collator.getInstance()); SortKey sortKey = sorter.getSortKey(); assertSorterSortKeySynched(sortKey, sorter); } /** * test that sorter updates internal state from SortKey. * */ @Test public void testSorterSynchedFromSortKey() { // create a sorter for column 0, ascending, // without explicit comparator Sorter sorter = new ShuttleSorter(); SortKey sortKey = new SortKey(SortOrder.DESCENDING, 1, Collator.getInstance()); sorter.setSortKey(sortKey); assertSorterSortKeySynched(sortKey, sorter); } public static void assertSorterSortKeySynched(SortKey sortKey, Sorter sorter) { assertNotNull(sorter); assertEquals(sortKey.getColumn(), sorter.getColumnIndex()); assertTrue(sortKey.getSortOrder().isSorted(sorter.isAscending())); assertEquals(sortKey.getSortOrder().isAscending(), sorter.isAscending()); assertSame(sortKey.getComparator(), sorter.getComparator()); } /** * test that sorter.setSortKey(..) throws the documented exceptions. * */ @Test public void testSorterSortKeyExceptions() { Sorter sorter = new ShuttleSorter(); try { sorter.setSortKey(null); fail("sorter must throw IllegalArgument for null SortKey"); } catch (IllegalArgumentException e) { // this is documented behaviour } catch (Exception e) { fail("unexpected exception for null Sortkey" + e); } try { SortKey sortKey = new SortKey(SortOrder.UNSORTED, 0, Collator.getInstance()); sorter.setSortKey(sortKey); fail("sorter must throw IllegalArgument for unsorted SortKey"); } catch (IllegalArgumentException e) { // this is documented behaviour } catch (Exception e) { fail("unexpected exception for unsorted Sortkey" + e); } } /** * initial addition. * Testing exceptions thrown in constructors */ @Test public void testSortKeyConstructorExceptions() { try { new SortKey(null, 2); fail("SortKey must throw IllegalArgument for null SortOrder"); } catch (IllegalArgumentException e) { // this is documented behaviour } catch (Exception e) { fail("unexpected exception in SortKey with null SortOrder" + e); } try { new SortKey(SortOrder.ASCENDING, -1); fail("SortKey must throw IllegalArgument for negative column"); } catch (IllegalArgumentException e) { // this is documented behaviour } catch (Exception e) { fail("unexpected exception in SortKey with negative column" + e); } } /** * initial addition, test constructors parameters. */ @Test public void testSortKeyConstructor() { int column = 3; SortOrder sortOrder = SortOrder.ASCENDING; // two parameter constructor SortKey sortKey = new SortKey(sortOrder, column); assertEquals(column, sortKey.getColumn()); assertEquals(sortOrder, sortKey.getSortOrder()); assertNull(sortKey.getComparator()); Comparator comparator = Collator.getInstance(); // three parameter constructor sortKey = new SortKey(sortOrder, column, comparator); assertEquals(column, sortKey.getColumn()); assertEquals(sortOrder, sortKey.getSortOrder()); assertSame(comparator, sortKey.getComparator()); } /** * sanity - SortOrders convenience method state. * */ @Test public void testSortOrderConvenience() { assertTrue(SortOrder.ASCENDING.isSorted()); assertTrue(SortOrder.ASCENDING.isAscending()); assertTrue(SortOrder.DESCENDING.isSorted()); assertFalse(SortOrder.DESCENDING.isAscending()); assertFalse(SortOrder.UNSORTED.isSorted()); assertFalse(SortOrder.UNSORTED.isAscending()); // wanted: ascending sort assertEquals(false, SortOrder.UNSORTED.isSorted(true)); assertEquals(false, SortOrder.DESCENDING.isSorted(true)); assertEquals(true, SortOrder.ASCENDING.isSorted(true)); // wanted: descending sort assertEquals(false, SortOrder.UNSORTED.isSorted(false)); assertEquals(true, SortOrder.DESCENDING.isSorted(false)); assertEquals(false, SortOrder.ASCENDING.isSorted(false)); } /** * test new method sorter.getSortOrder(), must be in synch with * sorter.isAscending() * */ @Test public void testSortOrder() { Sorter sorter = new ShuttleSorter(); assertSame(SortOrder.ASCENDING, sorter.getSortOrder()); Sorter other = new ShuttleSorter(0, false); assertSame(SortOrder.DESCENDING, other.getSortOrder()); other.setAscending(true); assertSame(SortOrder.ASCENDING, other.getSortOrder()); } /** * Issue #179: make sure to use the correct default collator. * */ @Test public void testCollator() { Locale defaultLocale = Locale.getDefault(); Locale western = Locale.GERMAN; Locale eastern = Locale.CHINESE; Collator westernCol = Collator.getInstance(western); Collator easternCol = Collator.getInstance(eastern); // sanity assert: collators are different assertFalse(westernCol.equals(easternCol)); Locale.setDefault(western); // sanity assert: default collator is western assertEquals(westernCol, Collator.getInstance()); Sorter sorter = new ShuttleSorter(); assertEquals("sorter must use collator default locale", Collator.getInstance(), sorter.getCollator()); Locale.setDefault(eastern); // sanity assert: default collator is eastern assertEquals(easternCol, Collator.getInstance()); sorter.toggle(); assertEquals("collator must use default locale", Collator.getInstance(), sorter.getCollator()); Locale.setDefault(defaultLocale); } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/HighlighterClientIssues.java0000644000175000017500000000756111210401722027336 0ustar tonytony/* * $Id: HighlighterClientIssues.java,v 1.3 2008/08/02 13:41:01 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.decorator; import java.awt.Color; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXTable; /** * Test to exposed known issues of Highlighter client * api in collection components. * * Ideally, there would be at least one failing test method per open * Issue in the issue tracker. Plus additional failing test methods for * not fully specified or not yet decided upon features/behaviour. * * @author Jeanette Winzenburg */ public class HighlighterClientIssues extends InteractiveTestCase { public static void main(String[] args) throws Exception { // setSystemLF(true); HighlighterClientIssues test = new HighlighterClientIssues(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Table.*"); // test.runInteractiveTests("interactive.*List.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Highlighters in JXTable must be kept on moving * the table to different container. This is a sanity test - * failed in early stages of fixing #519-swing: memory leak * with shared highlighters. * */ public void interactiveMemoryLeak() { final ColorHighlighter shared = new ColorHighlighter(Color.RED, null); JXTable first = new JXTable(10, 3); first.addHighlighter(shared); final JXTable second = new JXTable(10, 2); second.setName("second"); second.addHighlighter(shared); JXFrame firstFrame = wrapWithScrollingInFrame(first, "control"); final JXFrame secondFrame = wrapWithScrollingInFrame(second, "dependent, don't close directly"); Action close = new AbstractAction("close second") { public void actionPerformed(ActionEvent e) { secondFrame.dispose(); setEnabled(false); } }; Action open = new AbstractAction("open second") { public void actionPerformed(ActionEvent e) { JXFrame newFrame = wrapWithScrollingInFrame(second, "newly created"); newFrame.setVisible(true); } }; Action color = new AbstractAction("toggle color") { public void actionPerformed(ActionEvent e) { shared.setBackground(Color.YELLOW); } }; addAction(firstFrame, close); addAction(firstFrame, open); addAction(firstFrame, color); firstFrame.setVisible(true); secondFrame.setVisible(true); } /** * Dummy to keep the test runner happy. */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/FilterIssues.java0000644000175000017500000001257311210401722025165 0ustar tonytony/* * $Id: FilterIssues.java,v 1.11 2008/12/23 18:12:38 kschaefe Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.decorator; import java.text.Collator; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.renderer.DefaultTableRenderer; import org.jdesktop.swingx.renderer.StringValue; import org.jdesktop.swingx.renderer.StringValues; import org.jdesktop.test.AncientSwingTeam; /** * @author Jeanette Winzenburg */ public class FilterIssues extends FilterTest { public static void main(String args[]) { setSystemLF(true); FilterIssues test = new FilterIssues(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #767-swingx: PatternFilter must use string representation. */ public void interactiveHiddenColumnFilterMatch() { JXTable table = new JXTable(new AncientSwingTeam()); table.setColumnControlVisible(true); StringValue sv = new StringValue() { public String getString(Object arg0) { return "x" + StringValues.TO_STRING.getString(arg0); } }; table.getColumnExt(0).setCellRenderer(new DefaultTableRenderer(sv)); table.getColumnExt(0).setVisible(false); PatternFilter filter = new PatternFilter(".*x.*", 0, 0); table.setFilters(new FilterPipeline(filter)); JXFrame frame = wrapWithScrollingInFrame(table, "match and filters: all must be shown"); frame.setVisible(true); } public void testSortControllerToggleWithComparator() { FilterPipeline pipeline = createAssignedPipeline(true); SortController controller = pipeline.getSortController(); controller.toggleSortOrder(0, Collator.getInstance()); fail("test does nothing - revisit?"); } /** * order of filters must be retained. * */ public void testSorterOrder() { Sorter sorter = new ShuttleSorter(); assertEquals("order < 0", -1, sorter.order); Filter[] filters = new Filter[] {sorter, new ShuttleSorter(2, true)}; new FilterPipeline(filters); // JW: pipeline inverts order of sorter - why? assertOrders(filters); } /** * trying to find out how much truth is in the api doc * for the conversion methods. * * As it looks: pipeline _really_ converts all the way between * model <--> view, filter converts part of it. Between model and * "view" up to the filter. * */ public void testConvertRowIndicesToModel() { FilterPipeline pipeline = createPipeline(); Filter intermediateSorter = pipeline.last(); intermediateSorter.setColumnIndex(2); // model contains 21 rows pipeline.assign(directModelAdapter); // this is 5 int lastViewRow = pipeline.getOutputSize() - 1; // modelrow is 18 int modelRow = pipeline.convertRowIndexToModel(lastViewRow); Filter intermediateFilter1 = pipeline.previous(intermediateSorter); Filter intermediateFilter2 = pipeline.previous(intermediateFilter1); // first filter has same coordinates as pipeline assertEquals(modelRow, intermediateSorter.convertRowIndexToModel(lastViewRow)); // filter previous to sorter has same output as filter // not really: was a coincidence that un-/sorted coordiates // on last entry are the same!! // so we forced it to be different with setting the column to something else! // JW PENDING: need a better test model! // fails because expects "view" coordinates in this filter's "view" system! assertEquals(modelRow, intermediateFilter1.convertRowIndexToModel(lastViewRow)); assertEquals(modelRow, intermediateFilter2.convertRowIndexToModel(lastViewRow)); } /** * trying to find out how much truth is in the api doc * for the conversion methods. * * As it looks: pipeline _really_ converts all the way between * model <--> view, filter converts part of it (?) * */ public void testConvertRowIndicesToView() { FilterPipeline pipeline = createPipeline(); Filter intermediateSorter = pipeline.last(); intermediateSorter.setColumnIndex(2); // model contains 21 rows pipeline.assign(directModelAdapter); // this is 5 int lastViewRow = pipeline.getOutputSize() - 1; // modelrow is 18 int modelRow = pipeline.convertRowIndexToModel(lastViewRow); Filter intermediateFilter1 = pipeline.previous(intermediateSorter); Filter intermediateFilter2 = pipeline.previous(intermediateFilter1); // now the other way round assertEquals(lastViewRow, pipeline.convertRowIndexToView(modelRow)); assertEquals(lastViewRow, intermediateSorter.convertRowIndexToView(modelRow)); // each filter converts from "real" model to it's own "view" // so we fail here assertEquals(lastViewRow, intermediateFilter1.convertRowIndexToView(modelRow)); assertEquals(lastViewRow, intermediateFilter2.convertRowIndexToView(modelRow)); } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/TableColumnExtAsHighlighterClientIssues.java0000644000175000017500000000242711210401722032425 0ustar tonytony/* * $Id: TableColumnExtAsHighlighterClientIssues.java,v 1.2 2008/08/02 13:41:02 kleopatra Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.decorator; /** * Contains failing tests for TableColumnExt in its role as HighlighterClient * * @author Jeanette Winzenburg */ public class TableColumnExtAsHighlighterClientIssues extends TableColumnExtAsHighlighterClientTest { public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/decorator/FilterTest.java0000644000175000017500000010156511210401724024633 0ustar tonytony/* * $Id: FilterTest.java,v 1.36 2008/10/11 20:42:31 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.decorator; import java.awt.event.ActionEvent; import java.text.Collator; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.test.PipelineReport; import org.jdesktop.test.AncientSwingTeam; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; @RunWith(JUnit4.class) public class FilterTest extends InteractiveTestCase { public FilterTest() { super("FilterTest"); } private TableModel tableModel; protected ComponentAdapter directModelAdapter; private PipelineReport pipelineReport; @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } //----------------------- testing sorter notification //----------------------- will happen only if in pipeline so we do it here /** * test notification from sorter after setSortkey. * Guarantee refresh notification with same direction, columnIndex * but different Comparator. */ @Test public void testSorterSortKeyComparatorRefresh() { FilterPipeline pipeline = new FilterPipeline(); pipeline.assign(directModelAdapter); // create a sorter for column 0, ascending, // without explicit comparator Sorter sorter = new ShuttleSorter(); pipeline.setSorter(sorter); pipeline.addPipelineListener(pipelineReport); // create sortKey with other sort direction on column SortKey sortKey = new SortKey(SortOrder.ASCENDING, sorter.getColumnIndex(), Collator.getInstance()); sorter.setSortKey(sortKey); // sanity: sorter and sortKey synched SorterTest.assertSorterSortKeySynched(sortKey, sorter); assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED)); } /** * test notification from sorter after setSortkey. * Guarantee refresh notification with same columnIndex. */ @Test public void testSorterSortKeyRefresh() { FilterPipeline pipeline = new FilterPipeline(); pipeline.assign(directModelAdapter); // create a sorter for column 0, ascending, // without explicit comparator Sorter sorter = new ShuttleSorter(); pipeline.setSorter(sorter); pipeline.addPipelineListener(pipelineReport); // create sortKey with other sort direction on column SortKey sortKey = new SortKey(SortOrder.DESCENDING, sorter.getColumnIndex()); sorter.setSortKey(sortKey); // sanity: sorter and sortKey synched SorterTest.assertSorterSortKeySynched(sortKey, sorter); assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED)); } /** * test notification from sorter after setSortkey. * Guarantee exactly one refresh notification. */ @Test public void testSorterSortKeyOneRefresh() { FilterPipeline pipeline = new FilterPipeline(); pipeline.assign(directModelAdapter); // create a sorter for column 0, ascending, // without explicit comparator Sorter sorter = new ShuttleSorter(); pipeline.setSorter(sorter); pipeline.addPipelineListener(pipelineReport); // create sortKey with other sort direction on column SortKey sortKey = new SortKey(SortOrder.DESCENDING, sorter.getColumnIndex() +1); sorter.setSortKey(sortKey); // sanity: sorter and sortKey synched SorterTest.assertSorterSortKeySynched(sortKey, sorter); assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED)); } /** * test notification from sorter after setSortkey. * Guarantee no refresh notification on same. */ @Test public void testSorterSortKeyNoRefresh() { FilterPipeline pipeline = new FilterPipeline(); pipeline.assign(directModelAdapter); // create a sorter for column 0, ascending, // without explicit comparator Comparator comparator = Collator.getInstance(); Sorter sorter = new ShuttleSorter(0, true, comparator); pipeline.setSorter(sorter); pipeline.addPipelineListener(pipelineReport); // create sortKey with other sort direction on column SortKey sortKey = new SortKey(SortOrder.ASCENDING, sorter.getColumnIndex(), sorter.getComparator()); sorter.setSortKey(sortKey); // sanity: sorter and sortKey synched SorterTest.assertSorterSortKeySynched(sortKey, sorter); assertFalse("sorter must not refresh without state change", pipelineReport.hasEvents()); } //---------------------------------SortController/Sorter in FilterPipeline /** * creates and returns a FilterPipeline assigned to directModelAdapter. * Registers pipelineReport if withReport. * * @param withReport flag to indicate if pipelineReport should be registered. * @return FilterPipeline */ protected FilterPipeline createAssignedPipeline(boolean withReport) { FilterPipeline pipeline = new FilterPipeline(); pipeline.assign(directModelAdapter); if (withReport) { pipeline.addPipelineListener(pipelineReport); } return pipeline; } /** * Guarantee that Pipeline's Sorter and SortController are in synch * after setting properties of SortController. * */ @Test public void testSortControllerToggleUpdatesSameSorter() { FilterPipeline pipeline = createAssignedPipeline(false); int column = 2; pipeline.setSorter(new ShuttleSorter(column, false)); Sorter sorter = pipeline.getSorter(); pipeline.addPipelineListener(pipelineReport); SortController controller = pipeline.getSortController(); controller.toggleSortOrder(column); assertFalse("toggleSortOrder must have initialized sortKey", controller.getSortKeys().isEmpty()); // we assume that there's exactly one sortkey created! SortKey sortKey = controller.getSortKeys().get(0); assertTrue(pipeline.getSorter().isAscending()); assertEquals(column, sortKey.getColumn()); assertSame(sorter, pipeline.getSorter()); SorterTest.assertSorterSortKeySynched(sortKey, pipeline.getSorter()); assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED)); } /** * Guarantee that Pipeline's Sorter and SortController are in synch * after setting properties of SortController. * */ @Test public void testSortControllerToggleUpdatesSorter() { FilterPipeline pipeline = createAssignedPipeline(false); int column = 2; pipeline.setSorter(new ShuttleSorter(column, false)); pipeline.addPipelineListener(pipelineReport); SortController controller = pipeline.getSortController(); int newColumn = column - 1; controller.toggleSortOrder(newColumn); assertFalse("toggleSortOrder must have initialized sortKey", controller.getSortKeys().isEmpty()); // we assume that there's exactly one sortkey created! SortKey sortKey = controller.getSortKeys().get(0); assertTrue(pipeline.getSorter().isAscending()); SorterTest.assertSorterSortKeySynched(sortKey, pipeline.getSorter()); assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED)); } /** * Guarantee that Pipeline's Sorter is correctly initialized * after setting properties of SortController. * */ @Test public void testSortControllerToggleInitSorter() { FilterPipeline pipeline = createAssignedPipeline(true); int column = 2; SortController controller = pipeline.getSortController(); controller.toggleSortOrder(column); assertFalse("toggleSortOrder must have initialized sortKey", controller.getSortKeys().isEmpty()); // we assume that there's exactly one sortkey created! SortKey sortKey = controller.getSortKeys().get(0); SorterTest.assertSorterSortKeySynched(sortKey, pipeline.getSorter()); assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED)); } /** * Guarantee that Pipeline's Sorter and SortController are in synch * after setting properties of SortController. * */ @SuppressWarnings("unchecked") @Test public void testSortControllerResetRemovesSorter() { FilterPipeline pipeline = createAssignedPipeline(false); int column = 2; pipeline.setSorter(new ShuttleSorter(column, true)); SortController controller = pipeline.getSortController(); controller.setSortKeys(Collections.EMPTY_LIST); assertNull(pipeline.getSorter()); } /** * Guarantee that Pipeline's Sorter and SortController are in synch * after setting properties of SortController. * */ @Test public void testSortControllerSortKeysUpdatesSameSorter() { FilterPipeline pipeline = createAssignedPipeline(false); pipeline.setSorter(new ShuttleSorter()); Sorter sorter = pipeline.getSorter(); pipeline.addPipelineListener(pipelineReport); SortController controller = pipeline.getSortController(); SortKey sortKey = new SortKey(SortOrder.DESCENDING, sorter.getColumnIndex()); controller.setSortKeys(Collections.singletonList(sortKey)); assertSame(sorter, pipeline.getSorter()); SorterTest.assertSorterSortKeySynched(sortKey, pipeline.getSorter()); assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED)); } /** * Guarantee that Pipeline's Sorter and SortController are in synch * after setting properties of SortController. * */ @Test public void testSortControllerSortKeysUpdatesSorter() { FilterPipeline pipeline = createAssignedPipeline(false); int column = 2; pipeline.setSorter(new ShuttleSorter(column, true)); pipeline.addPipelineListener(pipelineReport); SortController controller = pipeline.getSortController(); int newColumn = column - 1; SortKey sortKey = new SortKey(SortOrder.DESCENDING, newColumn); controller.setSortKeys(Collections.singletonList(sortKey)); SorterTest.assertSorterSortKeySynched(sortKey, pipeline.getSorter()); assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED)); } /** * Guarantee that Pipeline's Sorter is correctly initialized * after setting properties of SortController. * */ @Test public void testSortControllerSortKeysInitSorter() { FilterPipeline pipeline = createAssignedPipeline(true); int column = 1; SortController controller = pipeline.getSortController(); SortKey sortKey = new SortKey(SortOrder.DESCENDING, column, Collator.getInstance()); controller.setSortKeys(Collections.singletonList(sortKey)); SorterTest.assertSorterSortKeySynched(sortKey, pipeline.getSorter()); SortKey createdKey = SortKey.getFirstSortKeyForColumn(controller.getSortKeys(), column); SorterTest.assertSorterSortKeySynched(createdKey, pipeline.getSorter()); assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED)); } /** * initial addition of SortController * (== basically renamed Jesse's RowSorter). * no active sorter. */ @Test public void testSortControllerWithoutSorter() { FilterPipeline pipeline = createAssignedPipeline(false); SortController controller = pipeline.getSortController(); assertNotNull(controller); // test all method if nothing is sorted assertEquals(SortOrder.UNSORTED, controller.getSortOrder(0)); assertNotNull(controller.getSortKeys()); } /** * initial addition of SortController * Guarantee that SortController getters are in synch with Sorter. */ @Test public void testSortControllerWithSorter() { FilterPipeline pipeline = createAssignedPipeline(false); int column = 2; pipeline.setSorter(new ShuttleSorter(column, true)); SortController controller = pipeline.getSortController(); assertNotNull(controller); // test all method if sorter ascending sorter on column assertEquals(SortOrder.ASCENDING, controller.getSortOrder(column)); List sortKeys = controller.getSortKeys(); assertNotNull(sortKeys); assertEquals(1, sortKeys.size()); SortKey sortKey = sortKeys.get(0); assertEquals(SortOrder.ASCENDING, sortKey.getSortOrder()); assertEquals(column, sortKey.getColumn()); // sanity: doesn't effect unsorted column assertEquals(SortOrder.UNSORTED, controller.getSortOrder(column - 1)); } @Test public void testSortOrderChangedEvent() { FilterPipeline pipeline = createAssignedPipeline(true); pipeline.setSorter(new ShuttleSorter()); assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED)); // expect 2 events: one for sortOrderChanged, one for contentsChanged // not yet implemented - has implications on other tests, so go for // one type of events only ... // assertEquals(1, pipelineReport.getEventCount(PipelineEvent.SORT_ORDER_CHANGED)); // PipelineEvent event = pipelineReport.getLastEvent(PipelineEvent.SORT_ORDER_CHANGED); // assertEquals(PipelineEvent.SORT_ORDER_CHANGED, event.getType()); } //---------------------------------- /** * reported on swingx-dev mailing list: * chained filters must AND - as they did. * Currently (10/2005) they OR ?. * * Hmm, can't reproduce - JW. */ @Test public void testAndFilter() { PatternFilter first = new PatternFilter("a", 0, 0); PatternFilter second = new PatternFilter("b", 0, 1); // FilterPipeline pipeline = new FilterPipeline(new Filter[] {first, second}); FilterPipeline pipeline = new FilterPipeline(first, second); pipeline.assign(directModelAdapter); assertTrue(pipeline.getOutputSize() > 0); for (int i = 0; i < pipeline.getOutputSize(); i++) { boolean firstMatch = first.getPattern().matcher(pipeline.getValueAt(i, 0).toString()).find(); boolean secondMatch = second.getPattern().matcher(pipeline.getValueAt(i, 1).toString()).find(); assertTrue(firstMatch); assertEquals("both matchers must find", firstMatch, secondMatch); } } /** * Issue ??-swingx * pipeline should auto-flush on assigning adapter. * */ @Test public void testFlushOnAssign() { Filter filter = new PatternFilter(".*", 0, 0); FilterPipeline pipeline = new FilterPipeline(new Filter[] { filter }); pipeline.assign(directModelAdapter); assertEquals("pipeline output size must be model count", directModelAdapter.getRowCount(), pipeline.getOutputSize()); // JW PENDING: remove necessity to explicitly flush... Object value = pipeline.getValueAt(0, 0); assertEquals("value access via sorter must return the same as via pipeline", value, pipeline.getValueAt(0, 0)); } /** * test notification on setSorter: must fire on change only. * */ @Test public void testPipelineEventOnSameSorter() { FilterPipeline pipeline = new FilterPipeline(); pipeline.assign(directModelAdapter); pipeline.addPipelineListener(pipelineReport); Sorter sorter = new ShuttleSorter(); pipeline.setSorter(sorter); assertEquals("pipeline must have fired on setSorter", 1, pipelineReport.getEventCount()); pipelineReport.clear(); pipeline.setSorter(sorter); assertEquals("pipeline must not have fired on same setSorter", 0, pipelineReport.getEventCount()); } /** * test notification on setSorter. * */ @Test public void testPipelineEventOnSetSorter() { FilterPipeline pipeline = new FilterPipeline(); pipeline.assign(directModelAdapter); pipeline.addPipelineListener(pipelineReport); pipeline.setSorter(new ShuttleSorter()); assertEquals("pipeline must have fired on setSorter", 1, pipelineReport.getEventCount()); pipelineReport.clear(); pipeline.setSorter(null); assertEquals("pipeline must have fired on setSorter null", 1, pipelineReport.getEventCount()); } /** * test notification on setSorter: must fire if assigned only. * */ @Test public void testPipelineEventOnSetSorterUnassigned() { FilterPipeline pipeline = new FilterPipeline(); pipeline.addPipelineListener(pipelineReport); pipeline.setSorter(new ShuttleSorter()); assertEquals("pipeline must not fire if unassigned", 0, pipelineReport.getEventCount()); pipelineReport.clear(); pipeline.setSorter(null); assertEquals("pipeline must not fire if unassigned", 0, pipelineReport.getEventCount()); } /** * Issue #45-swingx: * interpose should throw if trying to interpose to a pipeline * with a differnt ComponentAdapter. * */ @Test public void testSetSorterDiffComponentAdapter() { FilterPipeline pipeline = new FilterPipeline(); pipeline.assign(directModelAdapter); Sorter sorter = new ShuttleSorter(); sorter.assign(new DirectModelAdapter(new DefaultTableModel(10, 5))); try { pipeline.setSorter(sorter); fail("interposing with a different adapter must throw an IllegalStateException"); } catch (IllegalStateException ex) { } catch (Exception e) { fail("interposing with a different adapter must throw an " + "IllegalStatetException instead of " + e); } } /** * * Issue #46-swingx: * * need to clarify the behaviour of an empty pipeline. * I would expect 0 filters to result in an open pipeline * (nothing filtered). The implementation treats this case as a * closed pipeline (everything filtered). * * Arguably it could be decided either way, but returning a * outputsize > 0 and null instead of the adapter value for * all rows is a bug. * * Fixed by adding an pass-all filter internally. * */ @Test public void testEmptyPipeline() { int sortColumn = 0; FilterPipeline pipeline = new FilterPipeline(); pipeline.assign(directModelAdapter); assertEquals("size must be number of rows in adapter", directModelAdapter.getRowCount(), pipeline.getOutputSize()); Object value = pipeline.getValueAt(0, sortColumn); assertEquals(directModelAdapter.getValueAt(0, sortColumn), value); } /** * sorter in empty pipeline must behave in the same way as * an identical sorter in the pipeline's filter chain. * */ @Test public void testSorterInEmptyPipeline() { int sortColumn = 0; // prepare the reference pipeline Filter[] sorters = new Filter[] {new ShuttleSorter()}; FilterPipeline sortedPipeline = new FilterPipeline(sorters); sortedPipeline.assign(directModelAdapter); Object sortedValue = sortedPipeline.getValueAt(0, sortColumn); // prepare the empty pipeline with associated sorter FilterPipeline pipeline = new FilterPipeline(); pipeline.assign(directModelAdapter); Sorter sorter = new ShuttleSorter(); pipeline.setSorter(sorter); assertEquals("sorted values must be equal", sortedValue, pipeline.getValueAt(0, sortColumn)); } /** * sorter.getValueAt must be same as pipeline.getValueAt. * */ @Test public void testSorterInPipeline() { Filter filter = createDefaultPatternFilter(0); FilterPipeline pipeline = new FilterPipeline(new Filter[] { filter }); pipeline.assign(directModelAdapter); Sorter sorter = new ShuttleSorter(); pipeline.setSorter(sorter); assertEquals("value access via sorter must return the same as via pipeline", pipeline.getValueAt(0, 0), sorter.getValueAt(0,0)); } /** * unassigned filter/-pipeline must have size 0. * */ @Test public void testUnassignedFilter() { Filter filter = createDefaultPatternFilter(0); assertEquals(0, filter.getSize()); Filter[] filters = new Filter[] {filter}; FilterPipeline pipeline = new FilterPipeline(filters); assertEquals(0, pipeline.getOutputSize()); } @Test public void testUnassignedEmptyFilter() { FilterPipeline filters = new FilterPipeline(); assertEquals(0, filters.getOutputSize()); } /** * JW: test paranoia? * */ @Test public void testDirectComponentAdapterAccess() { FilterPipeline pipeline = createPipeline(); pipeline.assign(directModelAdapter); assertTrue("pipeline must have filtered values", pipeline.getOutputSize() < directModelAdapter.getRowCount()); } /** * order of filters must be retained. * */ @Test public void testFilterOrder() { Filter filterZero = createDefaultPatternFilter(0); Filter filterTwo = createDefaultPatternFilter(2); Sorter sorter = new ShuttleSorter(); assertEquals("order < 0", -1, sorter.order); Filter[] filters = new Filter[] {filterZero, filterTwo, sorter}; new FilterPipeline(filters); assertOrder(filterZero, filters); } /** * FilterPipeline allows maximal one sorter per column. * */ @Test public void testDuplicatedSortColumnException() { Filter[] filters = new Filter[] {new ShuttleSorter(), new ShuttleSorter()}; try { new FilterPipeline(filters); fail("trying to sort one column more than once must throw IllegalArgumentException"); } catch (IllegalArgumentException e) { // that's what we expect } catch (Exception e) { fail("trying to sort one column more than once must throw IllegalArgumentException" + "instead of " + e); } } /** * A filter can be bound to maximally one pipeline. */ @Test public void testAssignFilterPipelineBoundFilterException() { Filter filter = createDefaultPatternFilter(0); assertEquals("order < 0", -1, filter.order); Filter[] filters = new Filter[] {filter}; new FilterPipeline(filters); try { new FilterPipeline(filters); fail("sharing filters are not allowed - must throw IllegalArgumentException"); } catch (IllegalArgumentException e) { // that's what we expect } catch (Exception e) { fail("exception must be illegalArgument instead of " + e); } } /** * early binding of pipeline to filters. * */ @Test public void testAssignFilterPipeline() { Filter filter = createDefaultPatternFilter(0); Filter[] filters = new Filter[] {filter}; FilterPipeline pipeline = new FilterPipeline(filters); assertEquals("assigned to pipeline", pipeline, filter.getPipeline()); JXTable table = new JXTable(tableModel); table.setFilters(pipeline); assertEquals("assigned to table's componentadapter", table, filter.adapter.getComponent()); } private void assertOrder(Filter filter, Filter[] filters) { int position = getFilterPosition(filter, filters); assertEquals("order equals position in array", position, filter.order); } protected void assertOrders(Filter[] filters) { for (int i = 0; i < filters.length; i++) { assertEquals("order must be equal to filter position", i, filters[i].order); } } private int getFilterPosition(Filter filter, Filter[] filters) { for (int i = 0; i < filters.length; i++) { if (filters[i].equals(filter)) { return i; } } return -1; } /** * returns a pipeline with two default patternfilters on * column 0, 2 and an ascending sorter on column 0. */ protected FilterPipeline createPipeline() { Filter filterZero = createDefaultPatternFilter(0); Filter filterTwo = createDefaultPatternFilter(2); Sorter sorter = new ShuttleSorter(); Filter[] filters = new Filter[] {filterZero, filterTwo, sorter}; FilterPipeline pipeline = new FilterPipeline(filters); return pipeline; } /** returns a PatternFilter for occurences of "e" in column. * * @param column * @return a PatternFilter for occurences of "e" in column */ protected Filter createDefaultPatternFilter(int column) { Filter filterZero = new PatternFilter("e", 0, column); return filterZero; } /** * This is a test to ensure that the example in the javadoc actually works. * if the javadoc example changes, then those changes should be pasted here. */ @Test public void testJavaDocExample() { Filter[] filters = new Filter[] { new PatternFilter("^S", 0, 1), // regex, matchflags, column new ShuttleSorter(1, false), // column 1, descending new ShuttleSorter(0, true), // column 0, ascending }; FilterPipeline pipeline = new FilterPipeline(filters); JXTable table = new JXTable(); table.setFilters(pipeline); } @Override protected void setUp() throws Exception { super.setUp(); tableModel = new AncientSwingTeam(); directModelAdapter = new DirectModelAdapter(tableModel); pipelineReport = new PipelineReport(); } /** * ComponentAdapter directly on top of a TableModel. */ public static class DirectModelAdapter extends ComponentAdapter { private TableModel tableModel; public DirectModelAdapter(TableModel tableModel) { super(null); this.tableModel = tableModel; } @Override public int getColumnCount() { return tableModel.getColumnCount(); } @Override public int getRowCount() { return tableModel.getRowCount(); } @Override public String getColumnName(int columnIndex) { return tableModel.getColumnName(columnIndex); } @Override public Object getValueAt(int row, int column) { return tableModel.getValueAt(row, column); } @Override public void setValueAt(Object aValue, int row, int column) { tableModel.setValueAt(aValue, row, column); } @Override public boolean isCellEditable(int row, int column) { return tableModel.isCellEditable(row, column); } @Override public Object getFilteredValueAt(int row, int column) { return getValueAt(row, column); } @Override public Object getValue() { return getValueAt(row, column); } @Override public boolean hasFocus() { return false; } @Override public boolean isEditable() { return tableModel.isCellEditable(row, column); } @Override public boolean isSelected() { return false; } @Override public void refresh() { // do nothing } } /** * just to see the filtering effects... * */ public void interactiveTestColumnControlAndFilters() { final JXTable table = new JXTable(tableModel); table.setColumnControlVisible(true); Action toggleFilter = new AbstractAction("Toggle Filters") { boolean hasFilters; public void actionPerformed(ActionEvent e) { if (hasFilters) { table.setFilters(null); } else { table.setFilters(createPipeline()); } hasFilters = !hasFilters; } }; toggleFilter.putValue(Action.SHORT_DESCRIPTION, "filtering first column - problem if invisible "); JXFrame frame = wrapWithScrollingInFrame(table, "JXTable ColumnControl and Filters"); addAction(frame, toggleFilter); frame.setVisible(true); } /** * just to see the filtering effects... * */ public void interactiveTestAndFilter() { final JXTable table = new JXTable(tableModel); table.setColumnControlVisible(true); Action toggleFilter = new AbstractAction("Toggle Filters") { boolean hasFilters; public void actionPerformed(ActionEvent e) { if (hasFilters) { table.setFilters(null); } else { PatternFilter first = new PatternFilter("a", 0, 0); PatternFilter second = new PatternFilter("b", 0, 1); FilterPipeline pipeline = new FilterPipeline(new Filter[] {first, second}); table.setFilters(pipeline); } hasFilters = !hasFilters; } }; toggleFilter.putValue(Action.SHORT_DESCRIPTION, "Filtered rows: col(0) contains 'a' AND col(1) contains 'b'"); JXFrame frame = wrapWithScrollingInFrame(table, "JXTable ColumnControl and Filters"); addAction(frame, toggleFilter); frame.setVisible(true); } public void interactiveFilterMatch() { JXTable table = new JXTable(new AncientSwingTeam()); PatternFilter other = new PatternFilter(".*o.*", 0, 0); PatternFilter filter = new PatternFilter(".*e.*", 0, 0); table.setFilters(new FilterPipeline(filter, other)); JXFrame frame = wrapWithScrollingInFrame(table, "match and filters"); frame.setVisible(true); } @Test public void testMultipleFilter() { JXTable otherTable = new JXTable(new AncientSwingTeam()); PatternFilter otherFilter = new PatternFilter(".*eo.*", 0, 0); otherTable.setFilters(new FilterPipeline(otherFilter)); JXTable table = new JXTable(new AncientSwingTeam()); PatternFilter other = new PatternFilter(".*o.*", 0, 0); PatternFilter filter = new PatternFilter(".*e.*", 0, 0); table.setFilters(new FilterPipeline(filter, other)); assertEquals(otherTable.getValueAt(0, 0), table.getValueAt(0,0)); } /** * test if extending patternFilter (because of missing abstractFilter) * is working. */ public void interactiveFakePatternFilter() { final int threshhold = 50; final Filter filter = new PatternFilter(null, 0, 3) { @Override public boolean test(int row) { Object value = getInputValue(row, getColumnIndex()); if (value instanceof Integer) { return ((Integer) value).intValue() > threshhold; } return false; } }; final FilterPipeline pipeline = new FilterPipeline(filter); final JXTable table = new JXTable(new AncientSwingTeam()); Action action = new AbstractActionExt("toggle filter") { boolean filtered; public void actionPerformed(ActionEvent e) { if (filtered) { table.setFilters(null); } else { table.setFilters(pipeline); } filtered = !filtered; } }; JXFrame frame = wrapWithScrollingInFrame(table, "filter fake"); addAction(frame, action); frame.pack(); frame.setVisible(true); } public static void main(String args[]) { setSystemLF(true); FilterTest test = new FilterTest(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXLoginPaneVisualCheck.java0000644000175000017500000002616411210401722025023 0ustar tonytony/* * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.Locale; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.SwingUtilities; import org.jdesktop.swingx.JXLoginPane.JXLoginFrame; import org.jdesktop.swingx.JXLoginPane.SaveMode; import org.jdesktop.swingx.auth.LoginService; import org.jdesktop.swingx.auth.SimpleLoginService; import org.jdesktop.swingx.graphics.GraphicsUtilities; import org.jdesktop.swingx.painter.MattePainter; import org.jdesktop.swingx.plaf.basic.BasicLoginPaneUI; /** * Simple tests to ensure that the {@code JXLoginPane} can be instantiated and * displayed. * * @author Karl Schaefer */ public class JXLoginPaneVisualCheck extends InteractiveTestCase { public JXLoginPaneVisualCheck() { super("JXLoginPane Test"); } public static void main(String[] args) throws Exception { // setSystemLF(true); JXLoginPaneVisualCheck test = new JXLoginPaneVisualCheck(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #538-swingx Failure to set locale at runtime * */ public void interactiveDisplay() { JComponent.setDefaultLocale(Locale.FRANCE); JXLoginPane panel = new JXLoginPane(); JFrame frame = JXLoginPane.showLoginFrame(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setJMenuBar(createAndFillMenuBar(panel)); panel.setSaveMode(SaveMode.BOTH); frame.pack(); frame.setVisible(true); } /** * Issue #538-swingx Failure to set locale at runtime * */ public void interactiveDisplayFixedUser() { JComponent.setDefaultLocale(Locale.FRANCE); JXLoginPane panel = new JXLoginPane(); JFrame frame = JXLoginPane.showLoginFrame(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setJMenuBar(createAndFillMenuBar(panel)); panel.setSaveMode(SaveMode.BOTH); panel.setUserName("aGuy"); panel.setUserNameEnabled(false); frame.pack(); frame.setVisible(true); } /** * Issue #538-swingx Failure to set locale at runtime * */ public void interactiveSetBackground() { JXLoginPane panel = new JXLoginPane(); panel.setBackgroundPainter(new MattePainter(Color.RED, true)); JFrame frame = JXLoginPane.showLoginFrame(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setJMenuBar(createAndFillMenuBar(panel)); panel.setSaveMode(SaveMode.BOTH); frame.pack(); frame.setVisible(true); } /** * Issue #777-swingx Custom banner not picked up due to double updateUI() call * */ public void interactiveCustomBannerDisplay() { JXLoginPane panel = new JXLoginPane(); panel.setUI(new DummyLoginPaneUI(panel)); JFrame frame = JXLoginPane.showLoginFrame(panel); frame.setJMenuBar(createAndFillMenuBar(panel)); panel.setSaveMode(SaveMode.BOTH); frame.pack(); frame.setVisible(true); } /** * Issue #636-swingx Unexpected resize on long exception message. * */ public void interactiveError() { JComponent.setDefaultLocale(Locale.FRANCE); final JXLoginPane panel = new JXLoginPane(new LoginService() { public boolean authenticate(String name, char[] password, String server) throws Exception { if (true) { throw new Exception("Ex."); } return false; }}); final JXLoginFrame frame = JXLoginPane.showLoginFrame(panel); // if uncommented dialog will disappear immediately due to invocation of login action //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setJMenuBar(createAndFillMenuBar(panel)); panel.setErrorMessage("TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO Unexpected resize on long exception message. Unexpected resize on long exception message."); panel.setSaveMode(SaveMode.BOTH); frame.pack(); frame.setVisible(true); SwingUtilities.invokeLater(new Runnable() { public void run() { evaluateChildren(frame.getContentPane().getComponents()); }}); } /** * Issue #636-swingx Unexpected resize on long exception message. * */ public void interactiveBackground() { JComponent.setDefaultLocale(Locale.FRANCE); final JXLoginPane panel = new JXLoginPane(new LoginService() { public boolean authenticate(String name, char[] password, String server) throws Exception { if (true) { throw new Exception("Ex."); } return false; }}); final JXLoginFrame frame = JXLoginPane.showLoginFrame(panel); // if uncomented dialog will disappear immediatelly dou to invocation of login action //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setJMenuBar(createAndFillMenuBar(panel)); panel.setErrorMessage("TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO Unexpected resize on long exception message. Unexpected resize on long exception message."); panel.setSaveMode(SaveMode.BOTH); frame.getContentPane().setBackgroundPainter(new MattePainter( new GradientPaint(0, 0, Color.BLUE, 1, 0, Color.YELLOW), true)); frame.pack(); frame.setVisible(true); SwingUtilities.invokeLater(new Runnable() { public void run() { evaluateChildren(frame.getContentPane().getComponents()); }}); } /** * Progress message test. */ public void interactiveProgress() { final JXLoginPane panel = new JXLoginPane(); final JFrame frame = JXLoginPane.showLoginFrame(panel); panel.setLoginService(new LoginService() { public boolean authenticate(String name, char[] password, String server) throws Exception { panel.startLogin(); Thread.sleep(5000); return true; }}); frame.setJMenuBar(createAndFillMenuBar(panel)); panel.setSaveMode(SaveMode.BOTH); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); SwingUtilities.invokeLater(new Runnable() { public void run() { evaluateChildren(frame.getContentPane().getComponents()); }}); } private boolean evaluateChildren(Component[] components) { for (Component c: components) { if (c instanceof JButton && "login".equals(((JButton) c).getActionCommand())) { ((JButton) c).doClick(); return true; } else if (c instanceof Container) { if (evaluateChildren(((Container) c).getComponents()) ){ return true; } } } return false; } public class DummyLoginPaneUI extends BasicLoginPaneUI { public DummyLoginPaneUI(JXLoginPane dlg) { super(dlg); } @Override public Image getBanner() { Image banner = super.getBanner(); BufferedImage im = GraphicsUtilities.createCompatibleTranslucentImage(banner.getWidth(null), banner.getHeight(null)); Graphics2D g = im.createGraphics(); try { g.setComposite(AlphaComposite.Src); g.drawImage(banner, 0, 0, 100, 100, null); } finally { g.dispose(); } return im; } } @Override protected void createAndAddMenus(JMenuBar menuBar, final JComponent component) { super.createAndAddMenus(menuBar, component); JMenu menu = new JMenu("Locales"); menu.add(new AbstractAction("Change Locale") { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { if (component.getLocale() == Locale.FRANCE) { component.setLocale(Locale.ENGLISH); } else { component.setLocale(Locale.FRANCE); } }}); menuBar.add(menu); } /** * swingx-917 * @throws Exception */ public void interactiveBrokenLayoutAfterFailedLogin() throws Exception { sun.awt.AppContext.getAppContext().put("JComponent.defaultLocale", Locale.FRANCE); Map aMap = new HashMap(); aMap.put("asdf", "asdf".toCharArray()); JXLoginPane panel = new JXLoginPane(new SimpleLoginService(aMap)); panel.setSaveMode(JXLoginPane.SaveMode.BOTH); panel.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange( PropertyChangeEvent thePropertyChangeEvent) { System.err.println(thePropertyChangeEvent.getPropertyName() + " " + thePropertyChangeEvent.getOldValue() + " -> " + thePropertyChangeEvent.getNewValue()); } }); JFrame frame = JXLoginPane.showLoginFrame(panel); frame.pack(); frame.setVisible(true); } /** * Do nothing, make the test runner happy * (would output a warning without a test fixture). * */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/util/0000755000175000017500000000000011210401734020667 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/util/SwingXUtilitiesTest.java0000644000175000017500000000727411210401722025514 0ustar tonytony/* * $Id: SwingXUtilitiesTest.java,v 1.2 2008/10/11 20:42:34 rah003 Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.util; import java.awt.GraphicsEnvironment; import java.lang.reflect.InvocationTargetException; import java.util.logging.Logger; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXDatePicker; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.SwingXUtilities; import org.jdesktop.swingx.plaf.basic.BasicDatePickerUI; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * Test SwingXUtilities. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class SwingXUtilitiesTest extends InteractiveTestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger .getLogger(SwingXUtilitiesTest.class.getName()); public static void main(String[] args) { SwingXUtilitiesTest test = new SwingXUtilitiesTest(); try { test.runInteractiveTests(); } catch (Exception e) { e.printStackTrace(); } } @Test public void testDescendingNull() { assertFalse("both nulls are not descending", SwingXUtilities.isDescendingFrom(null, null)); assertFalse("null comp is not descending", SwingXUtilities.isDescendingFrom(null, new JScrollPane())); assertFalse("comp is not descending null parent", SwingXUtilities.isDescendingFrom(new JLabel(), null)); } @Test public void testDescendingSame() { JComponent comp = new JLabel(); assertTrue("same component must be interpreted as descending", SwingXUtilities.isDescendingFrom(comp, comp)); } @Test public void testDescendingPopup() throws InterruptedException, InvocationTargetException { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless"); return; } final JXDatePicker picker = new JXDatePicker(); JXFrame frame = new JXFrame("showing", false); frame.add(picker); frame.pack(); frame.setVisible(true); assertFalse(SwingXUtilities.isDescendingFrom(picker.getMonthView(), picker)); Action togglePopup = picker.getActionMap().get("TOGGLE_POPUP"); togglePopup.actionPerformed(null); SwingUtilities.invokeAndWait(new Runnable() { public void run() { assertTrue("popup visible ", ((BasicDatePickerUI) picker.getUI()).isPopupVisible()); assertTrue(SwingXUtilities.isDescendingFrom(picker.getMonthView(), picker)); } }); frame.dispose(); } } swingx-1.0-src/src/test/org/jdesktop/swingx/util/ContractTest.java0000644000175000017500000000614111210401722024146 0ustar tonytonypackage org.jdesktop.swingx.util; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; import junit.framework.TestCase; @RunWith(JUnit4.class) public class ContractTest extends TestCase { @Test public void testAsNotNull() { //expected good cases with Objects Contract.asNotNull("1", "Works"); Contract.asNotNull(new String[]{}, "Works"); Contract.asNotNull(new String[0], "Works"); Contract.asNotNull(new String[]{"1"}, "Works"); Contract.asNotNull(new String[][]{}, "Works"); Contract.asNotNull(new String[0][0], "Works"); Contract.asNotNull(new String[][]{new String[]{}}, "Works"); Contract.asNotNull(new String[][]{new String[0]}, "Works"); Contract.asNotNull(new String[][]{new String[]{"1"}}, "Works"); //expected failure cases with Objects try { Contract.asNotNull(null, "Expected failure"); fail("Expected NullPointerException"); } catch (NullPointerException e) { //success } try { Contract.asNotNull(new String[]{null}, "Expected failure"); fail("Expected NullPointerException"); } catch (NullPointerException e) { //success } try { Contract.asNotNull(new String[1], "Expected failure"); fail("Expected NullPointerException"); } catch (NullPointerException e) { //success } try { Contract.asNotNull(new String[]{"1", null}, "Expected failure"); fail("Expected NullPointerException"); } catch (NullPointerException e) { //success } try { Contract.asNotNull(new String[]{"1", null, "2"}, "Expected failure"); fail("Expected NullPointerException"); } catch (NullPointerException e) { //success } try { Contract.asNotNull(new String[][]{new String[1]}, "Expected failure"); fail("Expected NullPointerException"); } catch (NullPointerException e) { //success } //expected success with primitives Contract.asNotNull(new int[]{}, "Works"); Contract.asNotNull(new int[0], "Works"); Contract.asNotNull(new int[]{1}, "Works"); Contract.asNotNull(new int[1], "Works"); Contract.asNotNull(new int[1][0], "Works"); Contract.asNotNull(new int[1][1], "Works"); //expected failure cases with primitives int[] badArray = null; try { Contract.asNotNull(badArray, "Expected failure"); fail("Expected NullPointerException"); } catch (NullPointerException e) { //success } int[][] badArray2 = null; try { Contract.asNotNull(badArray2, "Expected failure"); fail("Expected NullPointerException"); } catch (NullPointerException e) { //success } } } swingx-1.0-src/src/test/org/jdesktop/swingx/util/WindowUtilsTest.java0000644000175000017500000000461011210401722024660 0ustar tonytony/* * Created on 19.08.2005 * */ package org.jdesktop.swingx.util; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.JTextField; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.test.EDTRunner; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(EDTRunner.class) public class WindowUtilsTest extends InteractiveTestCase { public static void main(String[] args) { WindowUtilsTest test = new WindowUtilsTest(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*HighLighters"); } catch (Exception ex) { } } public void interactiveMinimumWindowSize() { JPanel config = new JPanel(); ((FlowLayout)config.getLayout()).setAlignment(FlowLayout.LEFT); final JTextField minW = new JTextField("800"); minW.setColumns(4); minW.setHorizontalAlignment(JTextField.RIGHT); final JTextField minH = new JTextField("600"); minH.setColumns(4); minH.setHorizontalAlignment(JTextField.RIGHT); config.add(new JLabel("Min. Width")); config.add(minW); config.add(new JLabel("Min. Height")); config.add(minH); final JXFrame minSizeFrame = wrapInFrame(config, "Minimum Size"); Action apply = new AbstractAction("Apply") { public void actionPerformed(ActionEvent e) { int newW = new Integer(minW.getText()).intValue(); int newH = new Integer(minH.getText()).intValue(); WindowUtils.setMinimumSizeManager(minSizeFrame, newW, newH); // minSizeFrame.setSize(newW, newH); } }; addAction(minSizeFrame, apply); minSizeFrame.setSize(400, 200); minSizeFrame.setVisible(true); } public void interactiveCenteringTest() { JFrame frame = new JFrame("I should be centered"); frame.add(new JTable(5, 5)); frame.pack(); frame.setLocation(WindowUtils.getPointForCentering(frame)); frame.setVisible(true); } /** * TODO formally test... * */ @Test public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/color/0000755000175000017500000000000011210401734021030 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/color/ColorUtilTest.java0000644000175000017500000000131611210401722024445 0ustar tonytony/** * */ package org.jdesktop.swingx.color; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.awt.Color; import org.junit.Test; /** * @author Karl George Schaefer * */ public class ColorUtilTest { @Test public void testToHexString() { assertThat(ColorUtil.toHexString(Color.BLACK), is("#000000")); assertThat(ColorUtil.toHexString(Color.WHITE), is("#ffffff")); } @Test public void testToHexStringWithTransparentColors() { assertThat(ColorUtil.toHexString(ColorUtil.setAlpha(Color.BLACK, 0)), is("#000000")); assertThat(ColorUtil.toHexString(ColorUtil.setAlpha(Color.WHITE, 0)), is("#ffffff")); } } swingx-1.0-src/src/test/org/jdesktop/swingx/renderer/0000755000175000017500000000000011210401736021522 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/renderer/TreeRendererTest.java0000644000175000017500000004074411210401722025617 0ustar tonytony/* * $Id: TreeRendererTest.java,v 1.27 2008/12/23 18:12:37 kschaefe Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.renderer; import java.awt.Color; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Font; import java.awt.event.ActionEvent; import java.io.File; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.DefaultListModel; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.ListModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeModel; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXEditorPaneTest; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXHyperlink; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTree; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.decorator.AbstractHighlighter; import org.jdesktop.swingx.decorator.ColorHighlighter; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.HighlightPredicate; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.hyperlink.LinkModel; import org.jdesktop.swingx.test.ActionMapTreeTableModel; import org.jdesktop.swingx.test.ComponentTreeTableModel; import org.jdesktop.swingx.treetable.FileSystemModel; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests behaviour of SwingX DefaultTreeRenderer. * Contains characterization to * guarantee that it behaves similar to the standard. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class TreeRendererTest extends InteractiveTestCase { @SuppressWarnings("all") private static final Logger LOG = Logger.getLogger(TreeRendererTest.class .getName()); private DefaultTreeCellRenderer coreTreeRenderer; private DefaultTreeRenderer xTreeRenderer; @Override protected void setUp() throws Exception { // setSystemLF(true); // LOG.info("LF: " + UIManager.getLookAndFeel()); // LOG.info("Theme: " + ((MetalLookAndFeel) UIManager.getLookAndFeel()).getCurrentTheme()); // UIManager.put("Tree.drawsFocusBorderAroundIcon", Boolean.TRUE); coreTreeRenderer = new DefaultTreeCellRenderer(); xTreeRenderer = new DefaultTreeRenderer(); } public static void main(String[] args) { TreeRendererTest test = new TreeRendererTest(); try { test.runInteractiveTests(); // test.runInteractiveTests(".*Wrapper.*"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Issue #873-swingx: WrappingIconPanel - delegate font unchanged */ @Test public void testDelegateFont() { JXTree tree = new JXTree(); tree.setCellRenderer(new DefaultTreeRenderer()); final Font bold = tree.getFont().deriveFont(Font.BOLD, 20f); Highlighter hl = new AbstractHighlighter() { @Override protected Component doHighlight(Component component, ComponentAdapter adapter) { component.setFont(bold); return component; } }; tree.addHighlighter(hl); WrappingIconPanel component = (WrappingIconPanel) tree.getCellRenderer() .getTreeCellRendererComponent(tree, "something", false, false, false, 0, false); assertEquals(bold, component.getFont()); assertEquals(bold, component.delegate.getFont()); } /** * Wrapping provider: hyperlink foreground must be preserved. * */ @Test public void testTreeHyperlinkForeground() { JXTree tree = new JXTree(createTreeModelWithLinks(20)); ComponentProvider context = new HyperlinkProvider(); Color foreground = context.rendererComponent.getForeground(); tree.setCellRenderer(new DefaultTreeRenderer(new WrappingProvider(context))); tree.getCellRenderer().getTreeCellRendererComponent(tree, "something", false, false, false, -1, false); assertEquals("hyperlink color must be preserved", foreground, context.rendererComponent.getForeground()); } /** * related to Issue #22-swingx: tree background highlighting broken. * test if background color is moved down to delegate component. * */ @Test public void testDelegateBackground() { WrappingProvider provider = new WrappingProvider(); DefaultTreeRenderer renderer = new DefaultTreeRenderer(provider); Component comp = renderer.getTreeCellRendererComponent(null, "dummy", false, false, false, -1, false); assertTrue(comp instanceof WrappingIconPanel); comp.setBackground(Color.RED); // sanity assertTrue(provider.getRendererComponent(null).isBackgroundSet()); assertEquals(Color.RED, provider.getRendererComponent(null).getBackground()); // sanity assertTrue(provider.wrappee.getRendererComponent(null).isBackgroundSet()); assertEquals(Color.RED, provider.wrappee.getRendererComponent(null).getBackground()); } /** * related to Issue #22-swingx: tree background highlighting broken. * test if foreground color is moved down to delegate component. * */ @Test public void testDelegateForeground() { WrappingProvider provider = new WrappingProvider(); DefaultTreeRenderer renderer = new DefaultTreeRenderer(provider); Component comp = renderer.getTreeCellRendererComponent(null, "dummy", false, false, false, -1, false); assertTrue(comp instanceof WrappingIconPanel); comp.setForeground(Color.RED); // sanity assertTrue(provider.getRendererComponent(null).isForegroundSet()); assertEquals(Color.RED, provider.getRendererComponent(null).getForeground()); // sanity assertTrue(provider.wrappee.getRendererComponent(null).isForegroundSet()); assertEquals(Color.RED, provider.wrappee.getRendererComponent(null).getForeground()); } /** * characterize opaqueness of rendering components. * Hmm... tree-magic is different */ @Test public void testTreeOpaqueRenderer() { // sanity assertFalse(new JLabel().isOpaque()); // assertTrue(coreTreeRenderer.isOpaque()); // assertTrue(xListRenderer.getRendererComponent().isOpaque()); } /** * base existence/type tests while adding DefaultTableCellRendererExt. * */ @Test public void testTreeRendererExt() { DefaultTreeRenderer renderer = new DefaultTreeRenderer(); assertTrue(renderer instanceof TreeCellRenderer); assertTrue(renderer instanceof Serializable); } //---------------------- interactive methods /** * Example for using no node icons in the tree. * */ public void interactiveCustomIconPerNodeType() { JTree tree = new JTree(); tree.setCellRenderer(new DefaultTreeRenderer(IconValues.NONE)); final JXFrame frame = wrapWithScrollingInFrame(tree, "tree - no icons"); frame.setVisible(true); } /** * Sanity check: icons updated on LF change * */ public void interactiveDefaultIconsToggleLF() { JTree tree = new JTree(); tree.setCellRenderer(new DefaultTreeRenderer()); final JXFrame frame = wrapInFrame(tree, "tree - toggle lf", true); frame.setSize(400, 400); frame.setVisible(true); } /** * Example for using arbitrary wrappee controllers. Here: a * checkbox representing entries in ActionMap. * */ public void interactiveTreeButtonFormatting() { TreeModel model = createActionTreeModel(); JTree tree = new JTree(model); CheckBoxProvider wrappee = createButtonProvider(); tree.setCellRenderer(new DefaultTreeRenderer(new WrappingProvider(wrappee))); JList list = new JList(createActionListModel()); list.setCellRenderer(new DefaultListRenderer(wrappee)); final JXFrame frame = wrapWithScrollingInFrame(tree, list, "custom renderer - same in tree and list"); frame.setVisible(true); } /** * Custom format on JTree/JXTree (latter with highlighter). * */ public void interactiveXTreeLabelFormattingHighlighter() { TreeModel model = createComponentHierarchyModel(); JTree tree = new JTree(model); StringValue converter = new StringValue() { public String getString(Object value) { if (value instanceof Component) { return "Name: " + ((Component) value).getName(); } return StringValues.TO_STRING.getString(value); } }; tree.setCellRenderer(new DefaultTreeRenderer(converter)); JXTree xtree = new JXTree(model); xtree.setHighlighters(new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW, Color.RED, Color.YELLOW)); xtree.setRolloverEnabled(true); // share renderer xtree.setCellRenderer(tree.getCellRenderer()); final JXFrame frame = wrapWithScrollingInFrame(tree, xtree, "custom format - tree vs. xtree (+Rollover renderer)"); frame.setVisible(true); } /** * Custom tree colors in JTree. Compare core default renderer with Swingx * default renderer. * */ public void interactiveCompareTreeExtTreeColors() { JTree xtree = new JTree(); Color background = Color.MAGENTA; Color foreground = Color.YELLOW; xtree.setBackground(background); xtree.setForeground(foreground); DefaultTreeCellRenderer coreTreeCellRenderer = new DefaultTreeCellRenderer(); // to get a uniform color on both tree and node // the core default renderer needs to be configured coreTreeCellRenderer.setBackgroundNonSelectionColor(background); coreTreeCellRenderer.setTextNonSelectionColor(foreground); xtree.setCellRenderer(coreTreeCellRenderer); JTree tree = new JTree(); tree.setBackground(background); tree.setForeground(foreground); // swingx renderer uses tree colors tree.setCellRenderer(xTreeRenderer); final JXFrame frame = wrapWithScrollingInFrame(xtree, tree, "custom tree colors - core vs. ext renderer"); frame.setVisible(true); } /** * Component orientation in JTree. Compare core default renderer with Swingx * default renderer. * */ public void interactiveCompareTreeRToL() { JTree xtree = new JTree(); xtree.setCellRenderer(coreTreeRenderer); JTree tree = new JTree(); tree.setCellRenderer(xTreeRenderer); final JXFrame frame = wrapWithScrollingInFrame(xtree, tree, "orientation - core vs. ext renderer"); Action toggleComponentOrientation = new AbstractAction( "toggle orientation") { public void actionPerformed(ActionEvent e) { ComponentOrientation current = frame.getComponentOrientation(); if (current == ComponentOrientation.LEFT_TO_RIGHT) { frame.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); } else { frame.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); } } }; addAction(frame, toggleComponentOrientation); frame.setVisible(true); } /** * Format custom model. * * PENDING: editor uses default toString and looses icons - * because the renderer is not a label. */ public void interactiveDefaultWrapper() { JTree xtree = new JTree(createComponentHierarchyModel()); StringValue componentFormat = new StringValue() { public String getString(Object value) { if (value instanceof Component) { return ((Component) value).getName(); } return StringValues.TO_STRING.getString(value); }}; xtree.setCellRenderer(new DefaultTreeRenderer(componentFormat)); xtree.setEditable(true); JTree tree = new JTree(new FileSystemModel()); StringValue format = new StringValue() { public String getString(Object value) { if (value instanceof File) { return ((File) value).getName(); } return StringValues.TO_STRING.getString(value); } }; tree.setCellRenderer(new DefaultTreeRenderer(format)); final JXFrame frame = wrapWithScrollingInFrame(xtree, tree, "wrapper and different models"); frame.setVisible(true); } //-------------------------- factory methods private TreeModel createTreeModelWithLinks(int count) { DefaultMutableTreeNode root = new DefaultMutableTreeNode("Links"); for (int i = 0; i < count; i++) { try { LinkModel link = new LinkModel("a link text " + i, null, new URL("http://some.dummy.url" + i)); if (i == 1) { URL url = JXEditorPaneTest.class.getResource("resources/test.html"); link = new LinkModel("a link text " + i, null, url); } root.add(new DefaultMutableTreeNode(link)); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return new DefaultTreeModel(root); } /** * * @return a button controller specialized on ActionEntryNode. */ private CheckBoxProvider createButtonProvider() { StringValue sv = new StringValue() { public String getString(Object value) { if (value instanceof Action) { return (String) ((Action) value).getValue(Action.NAME); } return ""; } }; BooleanValue bv = new BooleanValue() { public boolean getBoolean(Object value) { if (value instanceof AbstractActionExt) { return ((AbstractActionExt) value).isSelected(); } return false; } }; CheckBoxProvider wrapper = new CheckBoxProvider(new MappedValue(sv, null, bv), JLabel.LEADING); return wrapper; } /** * @return */ private ListModel createActionListModel() { JXTable table = new JXTable(10, 10); table.setHorizontalScrollEnabled(true); ActionMap map = table.getActionMap(); Object[] keys = map.keys(); DefaultListModel model = new DefaultListModel(); for (Object object : keys) { model.addElement(map.get(object)); } return model; } /** * @return */ private TreeModel createActionTreeModel() { JXTable table = new JXTable(10, 10); table.setHorizontalScrollEnabled(true); return new ActionMapTreeTableModel(table); } /** * @return */ private TreeModel createComponentHierarchyModel() { JXFrame frame = new JXFrame("dummy"); frame.add(new JScrollPane(new JXTree())); return new ComponentTreeTableModel(frame); } } swingx-1.0-src/src/test/org/jdesktop/swingx/renderer/RendererVisualCheck.java0000644000175000017500000016723111210401722026262 0ustar tonytony/* * $Id: RendererVisualCheck.java,v 1.58 2009/01/28 08:49:15 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.renderer; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyDescriptor; import java.io.File; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.sql.Time; import java.sql.Timestamp; import java.text.DateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.AbstractListModel; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.DefaultListModel; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.ListCellRenderer; import javax.swing.ListModel; import javax.swing.SwingConstants; import javax.swing.UIDefaults; import javax.swing.border.Border; import javax.swing.event.ChangeEvent; import javax.swing.event.ListSelectionEvent; import javax.swing.event.TableColumnModelEvent; import javax.swing.event.TableColumnModelListener; import javax.swing.filechooser.FileSystemView; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeModel; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXEditorPaneTest; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXHyperlink; import org.jdesktop.swingx.JXLabel; import org.jdesktop.swingx.JXList; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTree; import org.jdesktop.swingx.JXTreeTable; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.decorator.AbstractHighlighter; import org.jdesktop.swingx.decorator.BorderHighlighter; import org.jdesktop.swingx.decorator.ColorHighlighter; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.HighlightPredicate; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.HighlighterFactory; import org.jdesktop.swingx.decorator.PainterHighlighter; import org.jdesktop.swingx.decorator.PatternPredicate; import org.jdesktop.swingx.hyperlink.EditorPaneLinkVisitor; import org.jdesktop.swingx.hyperlink.LinkModel; import org.jdesktop.swingx.hyperlink.LinkModelAction; import org.jdesktop.swingx.painter.BusyPainter; import org.jdesktop.swingx.table.ColumnControlButton; import org.jdesktop.swingx.test.ComponentTreeTableModel; import org.jdesktop.swingx.test.XTestUtils; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.swingx.treetable.TreeTableModel; import org.jdesktop.swingx.treetable.TreeTableNode; import org.jdesktop.test.AncientSwingTeam; /** * Visual check of extended Swingx renderers. * * @author Jeanette Winzenburg */ public class RendererVisualCheck extends InteractiveTestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger .getLogger(RendererVisualCheck.class.getName()); public static void main(String[] args) { setSystemLF(true); RendererVisualCheck test = new RendererVisualCheck(); try { // test.runInteractiveTests(); // test.runInteractiveTests(".*CustomIcons.*"); test.runInteractiveTests(".*TextArea.*"); // test.runInteractiveTests(".*Color.*"); // test.runInteractiveTests("interactive.*ColumnControl.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #897-swingx: Opacity issues of JRendererCheckBox - striping lost. * * Reported against Nimbus, but similar in other LAFs if combined * with Painter. */ public void interactiveCheckBoxRenderer() { JXTable table = new JXTable(new AncientSwingTeam()); table.addHighlighter(HighlighterFactory.createSimpleStriping()); table.addHighlighter(new PainterHighlighter(HighlightPredicate.ROLLOVER_ROW, new BusyPainter())); showWithScrollingInFrame(table, "Checkbox: striping lost on rollover"); } /** * List/tree filled with TreeNodes wrapping a File. * */ public void interactiveTreeNodeCustomIcons() { ListModel files = createFileListModel(); JXList table = new JXList(files); StringValue sv = new StringValue() { public String getString(Object value) { if (value instanceof File) { return FileSystemView.getFileSystemView().getSystemDisplayName((File) value) + " Type: " + FileSystemView.getFileSystemView().getSystemTypeDescription((File) value); } return StringValues.TO_STRING.getString(value); } }; IconValue iv = IconValues.FILE_ICON; table.setCellRenderer(new DefaultListRenderer(new MappedValue(sv, iv))); final JXTree tree = new JXTree(createFileNodeModel()); final DefaultTreeRenderer treeRenderer = new DefaultTreeRenderer(iv, sv); tree.setCellRenderer(treeRenderer); // string based. Note: this example is locale dependent String folderDescription = ".*ordner.*"; PatternPredicate predicate = new PatternPredicate(folderDescription, 0, -1); Highlighter hl = new ColorHighlighter(predicate, null, Color.RED); table.addHighlighter(hl); tree.addHighlighter(hl); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.YEAR, -1); final Date lastYear = calendar.getTime(); // install value based highlighter final HighlightPredicate valueBased = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { if (!(adapter.getValue() instanceof File)) return false; File file = (File) adapter.getValue(); Date date = new Date(file.lastModified()); return date.after(lastYear); } }; final ColorHighlighter back = new ColorHighlighter(valueBased, Color.YELLOW, null); table.addHighlighter(back); tree.addHighlighter(back); tree.setRolloverEnabled(true); tree.addHighlighter(new BorderHighlighter(HighlightPredicate.ROLLOVER_ROW, BorderFactory.createLineBorder(Color.BLUE))); final HighlightPredicate valueBasedUnwrap = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { File file = getUserObject(adapter.getValue()); if (file == null) return false; Date date = new Date(file.lastModified()); return date.after(lastYear); } private File getUserObject(Object value) { if (value instanceof File) return (File) value; if (value instanceof DefaultMutableTreeNode) { return getUserObject(((DefaultMutableTreeNode) value).getUserObject()); } if (value instanceof TreeTableNode) { return getUserObject(((TreeTableNode) value).getUserObject()); } return null; } }; JXFrame frame = showWithScrollingInFrame(tree, table, "Tree/List: same string/icon values "); Action toggleUnwrap = new AbstractAction("toggle unwrapUserObject") { public void actionPerformed(ActionEvent e) { WrappingProvider provider = (WrappingProvider) treeRenderer.getComponentProvider(); provider.setUnwrapUserObject(!provider.getUnwrapUserObject()); tree.revalidate(); tree.repaint(); } }; addAction(frame, toggleUnwrap); Action togglePredicate = new AbstractAction("toggle predicateUnwrap") { public void actionPerformed(ActionEvent e) { HighlightPredicate old = back.getHighlightPredicate(); back.setHighlightPredicate(old == valueBased ? valueBasedUnwrap : valueBased); } }; addAction(frame, togglePredicate); Action toggleLargeModel = new AbstractAction("toggle largeModel") { public void actionPerformed(ActionEvent e) { tree.setLargeModel(!tree.isLargeModel()); tree.revalidate(); tree.repaint(); } }; addAction(frame, toggleLargeModel); addStatusMessage(frame, "node is treeNode wrapping file - string/value based Highlighters differ"); } /** * @return */ private TreeModel createFileNodeModel() { FileSystemModel tree = new FileSystemModel(); File root = tree.getRoot(); DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(root); for (int i = 0; i < tree.getChildCount(root); i++) { rootNode.add(new DefaultMutableTreeNode(tree.getChild(root, i))); } return new DefaultTreeModel(rootNode); } /** * @return */ private ListModel createFileListModel() { FileSystemModel tree = new FileSystemModel(); DefaultListModel list = new DefaultListModel(); File root = tree.getRoot(); list.addElement(root); for (int i = 0; i < tree.getChildCount(root); i++) { list.addElement(tree.getChild(root, i)); } return list; } /** * example to configure treeTable hierarchical column (same for tree) with * custom icon and content mapping. Here the nodes are actually of type File. * * PENDING JW: * TreeTable string rep is not correctly recognized in the PatternHighlighter, * - will be correct automatically, once we make it to really use the table/model rep * - could explicitly use the treecellrenderer as stringValue in the meantime? */ public void interactiveTreeTableCustomIcons() { // modify the file model to return the file itself for the hierarchical column TreeTableModel model = new FileSystemModel() { @Override public Object getValueAt(Object node, int column) { if (column == 0) { return node; } return super.getValueAt(node, column); } }; JXTreeTable table = new JXTreeTable(model); StringValue sv = new StringValue() { public String getString(Object value) { if (value instanceof File) { return FileSystemView.getFileSystemView().getSystemDisplayName((File) value) + " Type: " + FileSystemView.getFileSystemView().getSystemTypeDescription((File) value) ; } return StringValues.TO_STRING.getString(value); } }; IconValue iv = new IconValue() { public Icon getIcon(Object value) { if (value instanceof File) { return FileSystemView.getFileSystemView().getSystemIcon((File) value); } return null; }}; final DefaultTreeRenderer treeRenderer = new DefaultTreeRenderer(iv, sv); table.setTreeCellRenderer(treeRenderer); final JXTree tree = new JXTree(model); tree.setCellRenderer(treeRenderer); tree.setRolloverEnabled(true); tree.addHighlighter(new BorderHighlighter(HighlightPredicate.ROLLOVER_ROW, BorderFactory.createLineBorder(Color.BLUE))); // string based. Note: this example is locale dependent String folderDescription = ".*ordner.*"; PatternPredicate predicate = new PatternPredicate(folderDescription, 0, -1); Highlighter hl = new ColorHighlighter(predicate, null, Color.RED); table.addHighlighter(hl); tree.addHighlighter(hl); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.YEAR, -1); final Date lastYear = calendar.getTime(); // install value based highlighter HighlightPredicate valueBased = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { if (!(adapter.getValue() instanceof File)) return false; File file = (File) adapter.getValue(); Date date = new Date(file.lastModified()); return date.after(lastYear); } }; ColorHighlighter back = new ColorHighlighter(valueBased, Color.YELLOW, null); table.addHighlighter(back); tree.addHighlighter(back); JXFrame frame =showWithScrollingInFrame(tree, table, "Tree/Table: same string/icon value"); addStatusMessage(frame, "node is File - string/value based highlighters same"); } /** * Use formatting from sql date/time classes. * */ public void interactiveTableSQLDateTime() { Date date = new Date(); java.sql.Date sqlDate = new java.sql.Date(date.getTime()); Timestamp stamp = new Timestamp(date.getTime()); Time time = new Time(date.getTime()); DefaultTableModel model = new DefaultTableModel(1, 5) { @Override public Class getColumnClass(int columnIndex) { if (getRowCount() > 0) { Object value = getValueAt(0, columnIndex); if (value != null) { return value.getClass(); } } return super.getColumnClass(columnIndex); } }; model.setColumnIdentifiers(new Object[]{"Date - normal", "SQL Date", "SQL Timestamp", "SQL Time", "Date - as time"}); model.setValueAt(date, 0, 0); model.setValueAt(sqlDate, 0, 1); model.setValueAt(stamp, 0, 2); model.setValueAt(time, 0, 3); model.setValueAt(date, 0, 4); JXTable table = new JXTable(model); // right align to see the difference to normal date renderer DefaultTableRenderer renderer = new DefaultTableRenderer( new LabelProvider(SwingConstants.RIGHT)); table.setDefaultRenderer(Timestamp.class, renderer); table.setDefaultRenderer(Time.class, renderer); table.setDefaultRenderer(java.sql.Date.class, renderer); // format the given Date as short time table.getColumnExt(4).setCellRenderer(new DefaultTableRenderer( new FormatStringValue(DateFormat.getTimeInstance(DateFormat.SHORT)))); showWithScrollingInFrame(table, "normal/sql date formatting"); } /** * Quick example of using a JTextArea as rendering component and * dynamically adjust table row height to max pref height of the * cells in a row. * */ public void interactiveTextAreaRendererTable() { DefaultTableModel model = new DefaultTableModel(0, 2); model.addRow(new String[]{"some really, maybe really really long text - " + "wrappit .... where needed ", "some really, maybe really really long text - " + "wrappit .... where needed "}); model.addRow(new String[]{"another really, maybe really really long text - " + "with nothing but junk. wrappit .... where needed", "some really, maybe really really long text - " + "wrappit .... where needed "}); JXTable table = new JXTable(model); table.setColumnControlVisible(true); table.setDefaultRenderer(Object.class, new DefaultTableRenderer(new TextAreaProvider())); table.addHighlighter(HighlighterFactory.createSimpleStriping()); installDynamicRowHeights(table); showWithScrollingInFrame(table, "textArea as rendering comp"); } /** * Configures the table to allow individual row heights based on rendering components * pref size and inits the sizes. Installs an extended column model listener to * update the rowHeights on changes to the column widths. * * NOTE: this is not complete - real-world methods must * - listen to the TableModel to update the rowHeight * - listen to table's property changes for its Table/ColumnModel to * re-wire the appropriate listeners. * - be prepared to handle performance problems for large models * * @param table */ private void installDynamicRowHeights(final JXTable table) { table.setRowHeightEnabled(true); updateRowHeight(table); TableColumnModelListener columnListener = new TableColumnModelListener() { public void columnAdded(TableColumnModelEvent e) { updateRowHeight(table); } public void columnMarginChanged(ChangeEvent e) { // here we rely on an implementation detail of DefaultTableColumnModel: // which fires a marginChanged is column widths are changed updateRowHeight(table); } public void columnMoved(TableColumnModelEvent e) { } public void columnRemoved(TableColumnModelEvent e) { updateRowHeight(table); } public void columnSelectionChanged(ListSelectionEvent e) { } }; table.getColumnModel().addColumnModelListener(columnListener); } /** * Sets per-row rowHeight based on the rendering component's preferred height. * * @param table */ private void updateRowHeight(final JXTable table) { for (int row = 0; row < table.getRowCount(); row++) { int rowHeight = 0; for (int column = 0; column < table.getColumnCount(); column++) { Component comp = table.prepareRenderer(table .getCellRenderer(row, column), row, column); rowHeight = Math.max(rowHeight, comp.getPreferredSize().height); } table.setRowHeight(row, rowHeight); } } /** * use a JTextArea as rendering component. */ public static class TextAreaProvider extends ComponentProvider { @Override protected void configureState(CellContext context) { int columnWidth = getPreferredAreaWidth(context); if (columnWidth > 0) { rendererComponent.setSize(columnWidth, Short.MAX_VALUE); } } /** * @param context * @return */ private int getPreferredAreaWidth(CellContext context) { if (context.getComponent() instanceof JXTable) { JXTable table = (JXTable) context.getComponent(); return table.getColumn(context.getColumn()).getWidth(); } if (context.getComponent() instanceof JTree) { // TODO: implement width and depth based initial width } if (context.getComponent() != null) { // pending: accont for insets // doesn't really work for a JList in a scrollPane // need to track.. return context.getComponent().getWidth(); } // comp is null - not much we can do return -1; } @Override protected JTextArea createRendererComponent() { JTextArea area = new JTextArea(); area.setLineWrap(true); area.setWrapStyleWord(true); area.setOpaque(true); return area; } @Override protected void format(CellContext context) { rendererComponent.setText(getValueAsString(context)); } } /** * Quick example of using a JXLabel as rendering component. * Looks funny .. wrapping jumps? */ public void interactiveXLabelRenderer() { DefaultTableModel model = new DefaultTableModel(0, 1); model.addRow(new String[] {"some really, maybe really really long text - " + "wrappit .... where needed "}); model.addRow(new String[] {"another really, maybe really really long text - " + "with nothing but junk. wrappit .... where needed"}); JXTable table = new JXTable(model); table.setVisibleRowCount(4); table.setVisibleColumnCount(2); table.setColumnControlVisible(true); table.getColumnExt(0).setCellRenderer(new DefaultTableRenderer(new XLabelProvider())); table.addHighlighter( HighlighterFactory.createAlternateStriping()); table.setRowHeight(50); showWithScrollingInFrame(table, "textArea as rendering comp"); } /** * Use a JXLabel as rendering component. */ public static class XLabelProvider extends ComponentProvider { @Override protected void configureState(CellContext context) { } @Override protected JXLabel createRendererComponent() { JXLabel label = new JXLabel(); label.setOpaque(true); label.setLineWrap(true); return label; } @Override protected void format(CellContext context) { rendererComponent.setText(getValueAsString(context)); } } /** * Check disabled appearance. * */ public void interactiveListDisabledIconRenderer() { final TableModel model = createTableModelWithDefaultTypes(); // ListModel listModel = new AbstractListModel() { public Object getElementAt(int index) { if (index == 0) { return "dummy"; } return model.getValueAt(index - 1, 4); } public int getSize() { return model.getRowCount() + 1; } }; final JList standard = new JList(listModel); final JList enhanced = new JList(listModel); enhanced.setCellRenderer(new DefaultListRenderer()); AbstractAction action = new AbstractAction("toggle disabled") { public void actionPerformed(ActionEvent e) { standard.setEnabled(!standard.isEnabled()); enhanced.setEnabled(!enhanced.isEnabled()); } }; JXFrame frame = wrapWithScrollingInFrame(standard, enhanced, "Disabled - compare renderers: default <--> enhanced"); addAction(frame, action); frame.setVisible(true); } /** * Check disabled appearance for all renderers. * */ public void interactiveTableDefaultRenderers() { TableModel model = createTableModelWithDefaultTypes(); final JTable standard = new JTable(model); // used as source for swingx renderers final JXTable xTable = new JXTable(); final JTable enhanced = new JTable(model) { @Override protected void createDefaultRenderers() { defaultRenderersByColumnClass = new UIDefaults(); setDefaultRenderer(Object.class, xTable.getDefaultRenderer(Object.class)); setDefaultRenderer(Number.class, xTable.getDefaultRenderer(Number.class)); setDefaultRenderer(Date.class, xTable.getDefaultRenderer(Date.class)); setDefaultRenderer(Icon.class, xTable.getDefaultRenderer(Icon.class)); setDefaultRenderer(ImageIcon.class, xTable.getDefaultRenderer(ImageIcon.class)); setDefaultRenderer(Boolean.class, xTable.getDefaultRenderer(Boolean.class)); } }; AbstractAction action = new AbstractAction("toggle disabled") { public void actionPerformed(ActionEvent e) { standard.setEnabled(!standard.isEnabled()); enhanced.setEnabled(!enhanced.isEnabled()); } }; JXFrame frame = wrapWithScrollingInFrame(standard, enhanced, "Disabled Compare renderers: default <--> enhanced"); addAction(frame, action); frame.setVisible(true); } /** * @return */ private TableModel createTableModelWithDefaultTypes() { String[] names = {"Object", "Number", "Double", "Date", "ImageIcon", "Boolean"}; final Class[] types = {Object.class, Number.class, Double.class, Date.class, ImageIcon.class, Boolean.class}; DefaultTableModel model = new DefaultTableModel(names, 0) { @Override public Class getColumnClass(int columnIndex) { return types[columnIndex]; } }; Date today = new Date(); Icon icon = XTestUtils.loadDefaultIcon(); for (int i = 0; i < 10; i++) { Object[] values = new Object[] {"row " + i, i, Math.random() * 100, new Date(today.getTime() + i * 1000000), icon, i % 2 == 0}; model.addRow(values); } return model; } /** * Compare core table using core default renderer vs. swingx default renderer.

* Unselected background of lead is different for editable/not-editable cells. */ @SuppressWarnings("deprecation") public void interactiveTableCompareFocusedCellBackground() { TableModel model = new AncientSwingTeam() { @Override public boolean isCellEditable(int row, int column) { return column != 0; } }; JTable xtable = new JTable(model); xtable.setBackground(HighlighterFactory.NOTEPAD); // ledger JTable table = new JTable(model); table.setBackground(new Color(0xF5, 0xFF, 0xF5)); // ledger TableCellRenderer renderer = new DefaultTableRenderer(); table.setDefaultRenderer(Object.class, renderer); JXFrame frame = wrapWithScrollingInFrame(xtable, table, "JTable: Unselected focused background: core/ext renderer"); addStatusComponent(frame, new JLabel("background for unselected lead: first column is not-editable")); show(frame); } /** * Compare xtable using core default renderer vs. swingx default renderer.

* Obsolete - swingx renderers registered by default. * * Unselected background of lead is different for editable/not-editable cells. * With core renderer: can't because LegacyHighlighter hack jumps in. * */ public void interactiveXTableCompareFocusedCellBackground() { // TableModel model = new AncientSwingTeam() { // public boolean isCellEditable(int row, int column) { // return column != 0; // } // }; // // JXTable xtable = new JXTable(model); // xtable.setBackground(LegacyHighlighter.notePadBackground.getBackground()); // ledger // JXTable table = new JXTable(model) { // // @Override // protected void createDefaultRenderers() { // defaultRenderersByColumnClass = new UIDefaults(); // setDefaultRenderer(Object.class, new DefaultTableRenderer()); // LabelProvider controller = new LabelProvider(FormatStringValue.NUMBER_TO_STRING); // controller.setHorizontalAlignment(JLabel.RIGHT); // setDefaultRenderer(Number.class, new DefaultTableRenderer(controller)); // setDefaultRenderer(Date.class, new DefaultTableRenderer( // FormatStringValue.DATE_TO_STRING)); // TableCellRenderer renderer = new DefaultTableRenderer(new LabelProvider(JLabel.CENTER)); // setDefaultRenderer(Icon.class, renderer); // setDefaultRenderer(ImageIcon.class, renderer); // setDefaultRenderer(Boolean.class, new DefaultTableRenderer(new ButtonProvider())); // } // // }; // table.setBackground(xtable.getBackground()); // ledger // JXFrame frame = wrapWithScrollingInFrame(xtable, table, "JXTable: Unselected focused background: core/ext renderer"); // getStatusBar(frame).add(new JLabel("different background for unselected lead: first column is not-editable")); // frame.pack(); // frame.setVisible(true); } /** * Issue #282-swingx: compare disabled appearance of * collection views. * Check if extended renderers behave correctly. Still open: header * renderer disabled. */ public void interactiveDisabledCollectionViews() { final JXTable table = new JXTable(new AncientSwingTeam()); // table.setDefaultRenderer(Object.class, new DefaultTableRenderer()); table.setEnabled(false); final JXList list = new JXList(new String[] {"one", "two", "and something longer"}); list.setEnabled(false); // list.setCellRenderer(new DefaultListRenderer()); final JXTree tree = new JXTree(new FileSystemModel()); tree.setEnabled(false); JComponent box = Box.createHorizontalBox(); box.add(new JScrollPane(table)); box.add(new JScrollPane(list)); box.add(new JScrollPane(tree)); JXFrame frame = wrapInFrame(box, "disabled collection views"); AbstractAction action = new AbstractAction("toggle disabled") { public void actionPerformed(ActionEvent e) { table.setEnabled(!table.isEnabled()); list.setEnabled(!list.isEnabled()); tree.setEnabled(!tree.isEnabled()); } }; addAction(frame, action); frame.setVisible(true); } /** * * Example for custom StringValue: bound to bean property. * * A column of xtable and the xlist share the same component controller.

* * */ public void interactiveTableAndListCustomRenderer() { final ListModel players = createPlayerModel(); TableModel tableModel = new AbstractTableModel() { String[] columnNames = {"Name", "Score", "Player.toString"}; public int getColumnCount() { return 3; } public int getRowCount() { return players.getSize(); } public Object getValueAt(int rowIndex, int columnIndex) { return players.getElementAt(rowIndex); } @Override public Class getColumnClass(int columnIndex) { return Player.class; } @Override public String getColumnName(int column) { return columnNames[column]; } }; JXTable xtable = new JXTable(tableModel); PropertyStringValue converter = new PropertyStringValue("name"); LabelProvider nameController = new LabelProvider(converter); xtable.getColumn(0).setCellRenderer(new DefaultTableRenderer(nameController)); PropertyStringValue scoreConverter = new PropertyStringValue("score"); xtable.getColumn(1).setCellRenderer(new DefaultTableRenderer(scoreConverter)); xtable.packAll(); JXList list = new JXList(players); // we share the component controller between table and list list.setCellRenderer(new DefaultListRenderer(nameController)); showWithScrollingInFrame(xtable, list, "JXTable/JXList: Custom property renderer"); } /** * Simple example to bind a toStringConverter to a single property of the value. */ public static class PropertyStringValue implements StringValue { private String property; public PropertyStringValue(String property) { this.property = property; } /** * {@inheritDoc}

* Implemented to return the toString of the named property value. */ public String getString(Object value) { try { PropertyDescriptor desc = getPropertyDescriptor(value.getClass(), property); return StringValues.TO_STRING.getString(getValue(value, desc)); } catch (Exception e) { // nothing much we can do here... } return ""; } } /** * Use custom converter for Dimension/Point (from demo) * */ public void interactiveTableCustomRenderer() { JXTable table = new JXTable(); StringValue converter = new StringValue() { public String getString(Object value) { if (value instanceof Point) { Point p = (Point) value; return createString(p.x, p.y); } else if (value instanceof Dimension) { Dimension dim = (Dimension) value; return createString(dim.width, dim.height); } return ""; } private String createString(int width, int height) { return "(" + width + ", " + height + ")"; } }; TableCellRenderer renderer = new DefaultTableRenderer(converter); table.setDefaultRenderer(Point.class, renderer); table.setDefaultRenderer(Dimension.class, renderer); JXFrame frame = showWithScrollingInFrame(table, "custom renderer (from demo) for Point/Dimension"); ComponentTreeTableModel model = new ComponentTreeTableModel(frame); JXTreeTable treeTable = new JXTreeTable(model); treeTable.expandAll(); table.setModel(treeTable.getModel()); } //---------------- hyperlink rendering /** * extended link renderer in table. * */ public void interactiveTestTableLinkRenderer() { EditorPaneLinkVisitor visitor = new EditorPaneLinkVisitor(); JXTable table = new JXTable(createModelWithLinks()); LinkModelAction action = new LinkModelAction(visitor); ComponentProvider controller = new HyperlinkProvider(action, LinkModel.class); table.setDefaultRenderer(LinkModel.class, new DefaultTableRenderer(controller)); JFrame frame = wrapWithScrollingInFrame(table, visitor.getOutputComponent(), "show link renderer in table"); frame.setVisible(true); } /** * extended link renderer in list. * */ public void interactiveTestListLinkRenderer() { EditorPaneLinkVisitor visitor = new EditorPaneLinkVisitor(); JXList list = new JXList(createListModelWithLinks(20)); list.setRolloverEnabled(true); LinkModelAction action = new LinkModelAction(visitor); ComponentProvider context = new HyperlinkProvider(action, LinkModel.class); list.setCellRenderer(new DefaultListRenderer(context)); JFrame frame = wrapWithScrollingInFrame(list, visitor.getOutputComponent(), "show link renderer in list"); frame.setVisible(true); } /** * extended link renderer in tree. * */ public void interactiveTestTreeLinkRenderer() { EditorPaneLinkVisitor visitor = new EditorPaneLinkVisitor(); JXTree tree = new JXTree(createTreeModelWithLinks(20)); tree.setRolloverEnabled(true); LinkModelAction action = new LinkModelAction(visitor); ComponentProvider context = new HyperlinkProvider(action, LinkModel.class); tree.setCellRenderer(new DefaultTreeRenderer(new WrappingProvider(context))); JFrame frame = wrapWithScrollingInFrame(tree, visitor.getOutputComponent(), "show link renderer in list"); frame.setVisible(true); } //----------------------- experiments with "CheckList" fakes /** * Use a custom button controller to show both checkbox icon and text to * render Actions in a JXList. */ public void interactiveCheckListColumnControl() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); table.setColumnControlVisible(true); JXList list = new JXList(); // quick-fill and hook to table columns' visibility state configureList(list, table, true); StringValue sv = new StringValue() { public String getString(Object value) { if (value instanceof AbstractActionExt) { return ((AbstractActionExt) value).getName(); } return StringValues.TO_STRING.getString(value); } }; BooleanValue bv = new BooleanValue() { public boolean getBoolean(Object value) { if (value instanceof AbstractActionExt) { return ((AbstractActionExt) value).isSelected(); } return false; } }; CheckBoxProvider provider = new CheckBoxProvider(new MappedValue(sv, null, bv), JLabel.LEADING); list.setCellRenderer(new DefaultListRenderer(provider)); JXFrame frame = showWithScrollingInFrame(table, list, "rollover checkbox list-renderer"); addStatusMessage(frame, "CheckList renderer (not completely active - no hotspot, doubleclick only)"); } /** * Fills the list with a collection of actions (as returned from the * table's column control). Binds space and double-click to toggle * the action's selected state. * * note: this is just an example to show-off the button renderer in a list! * ... it's very dirty!! * * @param list * @param table */ private void configureList(final JXList list, final JXTable table, boolean useRollover) { final List actions = new ArrayList(); // quick and dirty access to column visibility actions @SuppressWarnings("all") ColumnControlButton columnControl = new ColumnControlButton(table) { @Override protected void addVisibilityActionItems() { actions.addAll(Collections .unmodifiableList(getColumnVisibilityActions())); } }; list.setModel(createListeningListModel(actions)); // action toggling selected state of selected list item final Action toggleSelected = new AbstractActionExt( "toggle column visibility") { public void actionPerformed(ActionEvent e) { if (list.isSelectionEmpty()) return; AbstractActionExt selectedItem = (AbstractActionExt) list .getSelectedValue(); selectedItem.setSelected(!selectedItem.isSelected()); } }; if (useRollover) { list.setRolloverEnabled(true); } else { // bind action to space list.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "toggleSelectedActionState"); } list.getActionMap().put("toggleSelectedActionState", toggleSelected); // bind action to double-click MouseAdapter adapter = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { toggleSelected.actionPerformed(null); } } }; list.addMouseListener(adapter); } /** * Creates and returns a ListModel containing the given actions. * Registers a PropertyChangeListener with each action to get * notified and fire ListEvents. * * @param actions the actions to add into the model. * @return the filled model. */ private ListModel createListeningListModel(final List actions) { final DefaultListModel model = new DefaultListModel() { DefaultListModel reallyThis = this; @Override public void addElement(Object obj) { super.addElement(obj); ((Action) obj).addPropertyChangeListener(l); } PropertyChangeListener l = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { int index = indexOf(evt.getSource()); if (index >= 0) { fireContentsChanged(reallyThis, index, index); } } }; }; for (Action action : actions) { model.addElement(action); } return model; } //--------------- experiments with color renderer (content directly related to visuals) /** * Compare xtable using custom color renderer - standard vs. ext.

* */ public void interactiveTableCustomColorRenderer() { TableModel model = new AncientSwingTeam(); JXTable xtable = new JXTable(model); xtable.setDefaultRenderer(Color.class, new ColorRenderer(true)); JXTable table = new JXTable(model); TableCellRenderer renderer = createColorRendererExt(); table.setDefaultRenderer(Color.class, renderer); showWithScrollingInFrame(xtable, table, "JXTable: Custom color renderer - standard/ext"); } /** * Compare xtable using custom color renderer - standard vs. ext.

* Adds highlighter ... running amok. */ public void interactiveTableCustomColorRendererWithHighlighter() { TableModel model = new AncientSwingTeam(); JXTable xtable = new JXTable(model); xtable.addHighlighter( HighlighterFactory.createSimpleStriping(HighlighterFactory.GENERIC_GRAY)); xtable.setDefaultRenderer(Color.class, new ColorRenderer(true)); JXTable table = new JXTable(model); table.addHighlighter( HighlighterFactory.createSimpleStriping(HighlighterFactory.GENERIC_GRAY)); TableCellRenderer renderer = createColorRendererExt(); table.setDefaultRenderer(Color.class, renderer); JXFrame frame = wrapWithScrollingInFrame(xtable, table, "JXTable/highlighter: Custom color renderer - standard/ext"); addStatusMessage(frame, "Highlighter hide custom color renderer background for unselected"); frame.setVisible(true); } /** * Compare xtable using custom color renderer - standard vs. ext.

* Adds highlighter which respects renderer's dont touch. */ public void interactiveTableCustomColorRendererWithHighlighterDontTouch() { TableModel model = new AncientSwingTeam(); JXTable xtable = new JXTable(model); Highlighter highlighter = createPropertyRespectingHighlighter( HighlighterFactory.createSimpleStriping(HighlighterFactory.GENERIC_GRAY)); xtable.addHighlighter(highlighter); xtable.setDefaultRenderer(Color.class, new ColorRenderer(true)); JXTable table = new JXTable(model); table.addHighlighter(highlighter); TableCellRenderer renderer = createColorRendererExt(); table.setDefaultRenderer(Color.class, renderer); JXFrame frame = wrapWithScrollingInFrame(xtable, table, "JXTable/highlighter dont-touch: Custom color renderer - standard/ext"); addStatusMessage(frame, "Highlighter doesn't touch custom color renderer visual properties"); frame.pack(); frame.setVisible(true); } /** * Creates and returns a LegacyHighlighter which does nothing if the * rendererComponent has the dont-touch property set. Otherwise * delegates highlighting to the delegate. * * @param delegate * @return */ private Highlighter createPropertyRespectingHighlighter(final Highlighter delegate) { HighlightPredicate predicate = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { return ((JComponent) renderer).getClientProperty("renderer-dont-touch") == null; } }; Highlighter highlighter = new AbstractHighlighter(predicate) { @Override public Component doHighlight(Component renderer, ComponentAdapter adapter) { return delegate.highlight(renderer, adapter); } }; return highlighter; } /** * xtable/xlist using the same custom component controller.

* */ public void interactiveTableAndListCustomColorRenderingController() { TableModel tableModel = new AncientSwingTeam(); ComponentProvider controller = createColorRenderingLabelController(); JXTable xtable = new JXTable(tableModel); xtable.setDefaultRenderer(Color.class, new DefaultTableRenderer(controller)); ListModel model = createListColorModel(); JXList list = new JXList(model); ListCellRenderer renderer = new DefaultListRenderer(controller); list.setCellRenderer(renderer); JXFrame frame = wrapWithScrollingInFrame(xtable, list, "JXTable/JXList: Custom color renderer - sharing the component controller"); addMessage(frame, "share provider in normally in different comps is okay?"); frame.pack(); frame.setVisible(true); } /** * xtable/xlist using the same custom component controller.

* */ public void interactiveTableAndTreeCustomColorRenderingController() { TableModel tableModel = new AncientSwingTeam(); ComponentProvider controller = createColorRenderingLabelController(); JXTable xtable = new JXTable(tableModel); xtable.setDefaultRenderer(Color.class, new DefaultTableRenderer(controller)); TreeModel model = createTreeColorModel(); JTree tree = new JTree(model); ComponentProvider wrapper = new WrappingProvider(controller); //;createColorRenderingLabelController()); TreeCellRenderer renderer = new DefaultTreeRenderer(wrapper); tree.setCellRenderer(renderer); JXFrame frame = wrapWithScrollingInFrame(xtable, tree, "JXTable/JXTree: Custom color renderer - sharing the component controller"); addMessage(frame, "share provider in table and in wrappingProvider does not work?"); frame.pack(); frame.setVisible(true); } /** * creates and returns a color ext renderer. * @return */ protected TableCellRenderer createColorRendererExt() { ComponentProvider context = createColorRenderingLabelController(); TableCellRenderer renderer = new DefaultTableRenderer(context); return renderer; } /** * creates and returns a color ext renderer. * @return */ protected ListCellRenderer createListColorRendererExt() { ComponentProvider context = createColorRenderingLabelController(); ListCellRenderer renderer = new DefaultListRenderer(context); return renderer; } /** * Creates and returns a component controller specialized on Color values.

* Note: this implementation set's the tooltip * @return */ private ComponentProvider createColorRenderingLabelController() { ComponentProvider context = new LabelProvider() { Border selectedBorder; @Override protected void format(CellContext context) { super.format(context); Object value = context.getValue(); if (value instanceof Color) { rendererComponent.setBackground((Color) value); rendererComponent.putClientProperty("renderer-dont-touch", "color"); } else { rendererComponent.putClientProperty("renderer-dont-touch", null); } } /** * * @param context */ @Override protected void configureState(CellContext context) { Object value = context.getValue(); if (value instanceof Color) { Color newColor = (Color) value; rendererComponent.setToolTipText("RGB value: " + newColor.getRed() + ", " + newColor.getGreen() + ", " + newColor.getBlue()); } else { rendererComponent.setToolTipText(null); } if (context.isSelected()) { selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5, context.getSelectionBackground()); } else { selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5, context.getBackground()); } rendererComponent.setBorder(selectedBorder); } }; return context; } //--------------------- utility private ListModel createListModelWithLinks(int count) { DefaultListModel model = new DefaultListModel(); for (int i = 0; i < count; i++) { try { LinkModel link = new LinkModel("a link text " + i, null, new URL("http://some.dummy.url" + i)); if (i == 1) { URL url = JXEditorPaneTest.class.getResource("resources/test.html"); link = new LinkModel("a link text " + i, null, url); } model.addElement(link); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return model; } private TreeModel createTreeModelWithLinks(int count) { DefaultMutableTreeNode root = new DefaultMutableTreeNode("Links"); for (int i = 0; i < count; i++) { try { LinkModel link = new LinkModel("a link text " + i, null, new URL("http://some.dummy.url" + i)); if (i == 1) { URL url = JXEditorPaneTest.class.getResource("resources/test.html"); link = new LinkModel("a link text " + i, null, url); } root.add(new DefaultMutableTreeNode(link)); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return new DefaultTreeModel(root); } private TableModel createModelWithLinks() { String[] columnNames = { "text only", "Link editable", "Link not-editable", "Bool editable", "Bool not-editable" }; DefaultTableModel model = new DefaultTableModel(columnNames, 0) { @Override public Class getColumnClass(int columnIndex) { return getValueAt(0, columnIndex).getClass(); } @Override public boolean isCellEditable(int row, int column) { return !getColumnName(column).contains("not"); } }; for (int i = 0; i < 4; i++) { try { LinkModel link = new LinkModel("a link text " + i, null, new URL("http://some.dummy.url" + i)); if (i == 1) { URL url = JXEditorPaneTest.class .getResource("resources/test.html"); link = new LinkModel("a link text " + i, null, url); } model.addRow(new Object[] { "text only " + i, link, link, Boolean.TRUE, Boolean.TRUE }); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return model; } /** * * @return a ListModel wrapped around the AncientSwingTeam's Color column. */ private ListModel createListColorModel() { AncientSwingTeam tableModel = new AncientSwingTeam(); int colorColumn = 2; DefaultListModel model = new DefaultListModel(); for (int i = 0; i < tableModel.getRowCount(); i++) { model.addElement(tableModel.getValueAt(i, colorColumn)); } return model; } /** * @return a TreeModel with tree nodes of type Color. */ private TreeModel createTreeColorModel() { final AncientSwingTeam tableModel = new AncientSwingTeam(); final int colorColumn = 2; DefaultMutableTreeNode root = new DefaultMutableTreeNode("Colors"); for (int row = 0; row < tableModel.getRowCount(); row++) { root.add(new DefaultMutableTreeNode(tableModel.getValueAt(row, colorColumn))); } return new DefaultTreeModel(root); } /** * copied from sun's tutorial. */ public static class ColorRenderer extends JLabel implements TableCellRenderer { Border unselectedBorder = null; Border selectedBorder = null; boolean isBordered = true; public ColorRenderer(boolean isBordered) { this.isBordered = isBordered; setOpaque(true); // MUST do this for background to show up. putClientProperty("renderer-dont-touch", "color"); } public Component getTableCellRendererComponent(JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int column) { Color newColor = (Color) color; setBackground(newColor); if (isBordered) { if (isSelected) { if (selectedBorder == null) { selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5, table.getSelectionBackground()); } setBorder(selectedBorder); } else { if (unselectedBorder == null) { unselectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5, table.getBackground()); } setBorder(unselectedBorder); } } setToolTipText("RGB value: " + newColor.getRed() + ", " + newColor.getGreen() + ", " + newColor.getBlue()); return this; } } public static class Player { String name; int score; public Player(String name, int score) { this.name = name; this.score = score; } @Override public String toString() { return name + " has score: " + score; } public String getName() { return name; } public int getScore() { return score; } } /** * create and returns a ListModel containing Players. * @return */ private ListModel createPlayerModel() { DefaultListModel model = new DefaultListModel(); model.addElement(new Player("Henry", 10)); model.addElement(new Player("Berta", 112)); model.addElement(new Player("Dave", 20)); return model; } /** * c&p'd from JGoodies BeanUtils. * * Looks up and returns a PropertyDescriptor for the * given Java Bean class and property name using the standard * Java Bean introspection behavior. * * @param beanClass the type of the bean that holds the property * @param propertyName the name of the Bean property * @return the PropertyDescriptor associated with the given * bean and property name as returned by the Bean introspection * * @throws IntrospectionException if an exception occurs during * introspection. * @throws NullPointerException if the beanClass or propertyName is null * * @since 1.1.1 */ public static PropertyDescriptor getPropertyDescriptor( Class beanClass, String propertyName) throws IntrospectionException { BeanInfo info = Introspector.getBeanInfo(beanClass); PropertyDescriptor[] descriptors = info.getPropertyDescriptors(); for (int i = 0; i < descriptors.length; i++) { if (propertyName.equals(descriptors[i].getName())) return descriptors[i]; } throw new IntrospectionException( "Property '" + propertyName + "' not found in bean " + beanClass); } /** * c&p'd from JGoodies BeanUtils. * * Returns the value of the specified property of the given non-null bean. * This operation is unsupported if the bean property is read-only.

* * If the read access fails, a PropertyAccessException is thrown * that provides the Throwable that caused the failure. * * @param bean the bean to read the value from * @param propertyDescriptor describes the property to be read * @return the bean's property value * * @throws NullPointerException if the bean is null * @throws UnsupportedOperationException if the bean property is write-only * @throws PropertyAccessException if the new value could not be read */ public static Object getValue(Object bean, PropertyDescriptor propertyDescriptor) { if (bean == null) throw new NullPointerException("The bean must not be null."); Method getter = propertyDescriptor.getReadMethod(); if (getter == null) { throw new UnsupportedOperationException( "The property '" + propertyDescriptor.getName() + "' is write-only."); } try { return getter.invoke(bean); } catch (Exception e) { throw new RuntimeException("can't access property: " + propertyDescriptor.getName()); } // } catch (IllegalAccessException e) { // throw PropertyAccessException.createWriteAccessException( // bean, newValue, propertyDescriptor, e); // } catch (IllegalArgumentException e) { // throw PropertyAccessException.createWriteAccessException( // bean, newValue, propertyDescriptor, e); // } } /** * do-nothing method - suppress warning if there are no other * test fixtures to run. * */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/renderer/HighlighterClientVisualCheck.java0000644000175000017500000007120411210401722030103 0ustar tonytony/* * $Id: HighlighterClientVisualCheck.java,v 1.31 2009/04/23 09:31:41 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.renderer; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Font; import java.awt.Point; import java.awt.event.ActionEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import javax.swing.AbstractAction; import javax.swing.AbstractListModel; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.ListModel; import javax.swing.table.TableModel; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXList; import org.jdesktop.swingx.JXSearchPanel; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTree; import org.jdesktop.swingx.JXTreeTable; import org.jdesktop.swingx.decorator.AbstractHighlighter; import org.jdesktop.swingx.decorator.BorderHighlighter; import org.jdesktop.swingx.decorator.ColorHighlighter; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.CompoundHighlighter; import org.jdesktop.swingx.decorator.HighlightPredicate; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.HighlighterFactory; import org.jdesktop.swingx.decorator.PatternMatcher; import org.jdesktop.swingx.decorator.PatternPredicate; import org.jdesktop.swingx.decorator.ShadingColorHighlighter; import org.jdesktop.swingx.decorator.HighlightPredicate.ColumnHighlightPredicate; import org.jdesktop.swingx.renderer.PainterVisualCheck.ValueBasedGradientHighlighter; import org.jdesktop.swingx.rollover.RolloverProducer; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.test.AncientSwingTeam; /** * visual checks of highlighter clients. Mostly by example of JXTable. * * @author Jeanette Winzenburg */ public class HighlighterClientVisualCheck extends InteractiveTestCase { protected TableModel tableModel; protected Color background = Color.RED; protected Color foreground = Color.BLUE; public static void main(String args[]) { // setSystemLF(true); HighlighterClientVisualCheck test = new HighlighterClientVisualCheck(); try { // test.runInteractiveTests(); // test.runInteractiveTests(".*Tool.*"); // test.runInteractiveTests("interactive.*Search.*"); test.runInteractiveTests("interactive.*BorderHighlighter"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Show variants of border Highlighters. * */ public void interactiveTableBorderHighlighter() { JXTable table = new JXTable(tableModel); table.setVisibleRowCount(table.getRowCount()); table.setVisibleColumnCount(7); table.packAll(); table.setColumnControlVisible(true); BorderHighlighter outer = new BorderHighlighter(new HighlightPredicate.ColumnHighlightPredicate(1), BorderFactory.createLineBorder(Color.RED, 3)); BorderHighlighter inner = new BorderHighlighter(new HighlightPredicate.ColumnHighlightPredicate(2), BorderFactory.createLineBorder(Color.RED, 3), true, true); BorderHighlighter replace = new BorderHighlighter(new HighlightPredicate.ColumnHighlightPredicate(0), BorderFactory.createLineBorder(Color.RED, 3), false, true); table.setHighlighters(outer, inner, replace); showWithScrollingInFrame(table, "Border Highlighters"); } /** * Show variants of border Highlighters. * */ public void interactiveTreeBorderHighlighter() { JXTree tree = new JXTree(); tree.expandAll(); tree.setVisibleRowCount(tree.getRowCount()); // need SwingX highlighter tree.setCellRenderer(new DefaultTreeRenderer()); tree.setHighlighters(new BorderHighlighter(BorderFactory.createLineBorder(Color.GREEN, 1))); showWithScrollingInFrame(tree, "Border Highlighters"); } /** * Multiple Highlighters (shown as example in Javapolis 2007). * */ public void interactiveTablePatternHighlighterJP() { JXTable table = new JXTable(tableModel); table.setVisibleRowCount(table.getRowCount()); table.setVisibleColumnCount(7); table.packAll(); table.setColumnControlVisible(true); Font font = table.getFont().deriveFont(Font.BOLD | Font.ITALIC); Highlighter simpleStriping = HighlighterFactory.createSimpleStriping(); PatternPredicate patternPredicate = new PatternPredicate("^M", 1); ColorHighlighter magenta = new ColorHighlighter(patternPredicate, null, Color.MAGENTA, null, Color.MAGENTA); FontHighlighter derivedFont = new FontHighlighter(patternPredicate, font); Highlighter gradient = new ValueBasedGradientHighlighter(); Highlighter shading = new ShadingColorHighlighter( new HighlightPredicate.ColumnHighlightPredicate(1)); table.setHighlighters(simpleStriping, magenta, derivedFont, shading, gradient); showWithScrollingInFrame(table, "Multiple Highlighters"); } /** * Simulates table by one-list per column. * * NOTE: the only purpose is to demonstrate the similarity * of highlighter usage across collection components! * (shown as example in Javapolis 2007) * * @see #interactiveTablePatternHighlighterJP() */ public void interactiveListPatternHighlighterJP() { JXTable source = new JXTable(tableModel); source.toggleSortOrder(3); Font font = source.getFont().deriveFont(Font.BOLD | Font.ITALIC); Highlighter simpleStriping = HighlighterFactory.createSimpleStriping(); String pattern = "^M"; PatternPredicate patternPredicate = new PatternPredicate(pattern, 0); ColorHighlighter magenta = new ColorHighlighter(patternPredicate, null, Color.MAGENTA, null, Color.MAGENTA); FontHighlighter derivedFont = new FontHighlighter(patternPredicate, font); Highlighter gradient = new ValueBasedGradientHighlighter(true); Highlighter shading = new ShadingColorHighlighter( new HighlightPredicate.ColumnHighlightPredicate(0)); // create and configure one JXList per column. List lists = new ArrayList(); // first name JXList list0 = new JXList(createListModel(source, 0)); list0.setHighlighters(simpleStriping); lists.add(list0); // last name JXList list1 = new JXList(createListModel(source, 1)); list1.setHighlighters(simpleStriping, magenta, derivedFont, shading); lists.add(list1); // color JXList listc = new JXList(createListModel(source, 2)); listc.setHighlighters(simpleStriping); lists.add(listc); // number JXList listn = new JXList(createListModel(source, 3)); listn.setCellRenderer(new DefaultListRenderer( StringValues.NUMBER_TO_STRING, JLabel.RIGHT)); listn.setHighlighters(simpleStriping, gradient); lists.add(listn); // boolean JXList listb = new JXList(createListModel(source, 4)); listb.setCellRenderer(new DefaultListRenderer(new CheckBoxProvider())); listb.setFixedCellHeight(list0.getPreferredSize().height / source.getRowCount()); listb.setHighlighters(simpleStriping, magenta, derivedFont, gradient); lists.add(listb); JComponent panel = Box.createHorizontalBox(); for (JXList l : lists) { listb.setVisibleRowCount(source.getRowCount()); l.setFont(source.getFont()); panel.add(new JScrollPane(l)); } showInFrame(panel, "Multiple Highlighters"); } /** * @param tableModel2 * @param i * @return */ private ListModel createListModel(final JXTable tableModel, final int i) { ListModel listModel = new AbstractListModel(){ public Object getElementAt(int index) { return tableModel.getValueAt(index, i); } public int getSize() { return tableModel.getRowCount(); }}; return listModel ; } public static class FontHighlighter extends AbstractHighlighter { private Font font; public FontHighlighter(HighlightPredicate predicate, Font font) { super(predicate); this.font = font; } @Override protected Component doHighlight(Component component, ComponentAdapter adapter) { component.setFont(font); return component; } } /** * Example from forum requirement: highlight all rows of a given group * if mouse if over one of them. * * PENDING: need to track row view-model coordinates mapping after * filtering/sorting. * */ public void interactiveRolloverRowGroup() { TableModel model = new AncientSwingTeam(); final List rowSet = new ArrayList(); for (int i = 0; i < model.getRowCount(); i++) { if ((Integer)model.getValueAt(i, 3) > 10) { rowSet.add(i); } } final HighlightPredicate predicate = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { return rowSet.contains(adapter.row); } }; final ColorHighlighter highlighter = new ColorHighlighter(HighlightPredicate.NEVER, Color.YELLOW, null); JXTable table = new JXTable(model); table.addHighlighter(highlighter); PropertyChangeListener l = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { Point location = (Point) evt.getNewValue(); int row = -1; if (location != null) { row = location.y; } if (rowSet.contains(row)) { highlighter.setHighlightPredicate(predicate); } else { highlighter.setHighlightPredicate(HighlightPredicate.NEVER); } } }; table.addPropertyChangeListener(RolloverProducer.ROLLOVER_KEY, l); showWithScrollingInFrame(table, "rollover highlight of row groups"); } /** * Example to highlight against a value/color map. * Here the control is in predicate.

* */ public void interactiveColorValueMappedHighlighterPredicate() { JXTable table = new JXTable(new AncientSwingTeam()); // build a quick color lookup to simulate multi-value value-based // coloring final int numberColumn = 3; table.toggleSortOrder(numberColumn); Color[] colors = new Color[] { Color.YELLOW, Color.CYAN, Color.MAGENTA, Color.GREEN }; int rowsPerColor = (table.getRowCount() - 5) / colors.length; Map map = new HashMap(); for (int i = 0; i < colors.length; i++) { List values = new ArrayList(); for (int j = 0; j < rowsPerColor; j++) { values.add((Integer) table.getValueAt(i * rowsPerColor + j, numberColumn)); } map.put(colors[i], new ValueMappedHighlightPredicate(values, numberColumn)); } // create one ColorHighlighter for each color/predicate pair and // add to a compoundHighlighter CompoundHighlighter chl = new CompoundHighlighter(); for (Color color : colors) { chl.addHighlighter(new ColorHighlighter(map.get(color), color, null)); } table.resetSortOrder(); table.addHighlighter(chl); showWithScrollingInFrame(table, "compound highlighter with value-based color mapping predicate"); } /** * Custom predicate which returns true if the filtered cell value * of a given testColumn is contained in a list of values. * PENDING: logic similar to search/pattern, enough to abstract? */ public static class ValueMappedHighlightPredicate implements HighlightPredicate { private List values; private int testColumn; public ValueMappedHighlightPredicate(List values, int testColumn) { this.values = values; this.testColumn = testColumn; } public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { return values.contains(adapter.getValue(testColumn)); } } /** * Example to highlight against a value/color map.

* Here the Highlighter takes full control. Which is a bit * on the border line of * the intended distribution of responsibility between * Highlighter and HighlighterPredicate. */ public void interactiveColorValueMappedHighlighter() { JXTable table = new JXTable(new AncientSwingTeam()); // build a quick color lookup to simulate multi-value value-based // coloring final int numberColumn = 3; table.toggleSortOrder(numberColumn); final Map lookup = new HashMap(); Color[] colors = new Color[] { Color.YELLOW, Color.CYAN, Color.MAGENTA, Color.GREEN }; int rowsPerColor = (table.getRowCount() - 5) / colors.length; for (int i = 0; i < colors.length; i++) { for (int j = 0; j < rowsPerColor; j++) { lookup.put((Integer) table.getValueAt(i * rowsPerColor + j, numberColumn), colors[i]); } } table.resetSortOrder(); // PENDING JW: add and use HighlightPredicate.SELECTED/UN_SELECTED Highlighter hl = new ColorHighlighter() { @Override protected void applyBackground(Component renderer, ComponentAdapter adapter) { if (adapter.isSelected()) return; Color background = lookup.get(adapter.getValue(numberColumn)); if (background != null) { renderer.setBackground(background); } } }; table.addHighlighter(hl); showWithScrollingInFrame(table, "conditional highlighter with value-based color mapping"); } /** * test to see searchPanel functionality in new Highlighter api * */ public void interactiveSearchPanel() { JXTable table = new JXTable(tableModel); final ColorHighlighter cl = new ColorHighlighter(new PatternPredicate((Pattern) null, 0), null, Color.RED); table.addHighlighter(cl); JXSearchPanel searchPanel = new JXSearchPanel(); PatternMatcher patternMatcher = new PatternMatcher() { public Pattern getPattern() { return getPatternPredicate().getPattern(); } public void setPattern(Pattern pattern) { PatternPredicate old = getPatternPredicate(); cl.setHighlightPredicate(new PatternPredicate(pattern, old .getTestColumn(), old.getHighlightColumn())); } private PatternPredicate getPatternPredicate() { return (PatternPredicate) cl.getHighlightPredicate(); } }; searchPanel.addPatternMatcher(patternMatcher); JXFrame frame = wrapWithScrollingInFrame(table, "Pattern highlighting col 0"); addStatusComponent(frame, searchPanel); show(frame); } //----------------- custom PatternMatcher /** * columm shading (was: hierarchicalColumnHighlighter) * */ public void interactiveColumnShading() { JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()); // simulate hierarchicalColumnHighlighter int hierarchicalColumn = 0; for (int i = 0; i < treeTable.getColumnCount(); i++) { if (treeTable.isHierarchical(i)) { hierarchicalColumn = i; break; } } treeTable.addHighlighter(new ShadingColorHighlighter(new ColumnHighlightPredicate(hierarchicalColumn))); showWithScrollingInFrame(treeTable, "hierarchical column"); } /** * Classic lineprinter striping and hyperlink (LF only, no action). * */ public void interactiveTableAlternateAndHyperlink() { JXTable table = new JXTable(tableModel); table.setRowHeight(22); table.getColumn(1).setCellRenderer( new DefaultTableRenderer(new HyperlinkProvider())); table.addHighlighter(HighlighterFactory .createSimpleStriping(HighlighterFactory.CLASSIC_LINE_PRINTER)); JFrame frame = wrapWithScrollingInFrame(table, "classic lineprinter and hyperlink on column 1"); frame.setVisible(true); } /** * LinePrinter striping and rollover. * */ public void interactiveTableAlternateAndRollover() { JXTable table = new JXTable(tableModel); table.setRowHeight(22); table.setHighlighters( HighlighterFactory.createSimpleStriping(HighlighterFactory.LINE_PRINTER), new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW, Color.YELLOW, null)); showWithScrollingInFrame(table, "LinePrinter plus yellow rollover"); } /** * Foreground highlight on column 1 and 3. * */ public void interactiveColumnForeground() { JXTable table = new JXTable(tableModel); HighlightPredicate predicate = new ColumnHighlightPredicate(1, 3); table.addHighlighter(new ColorHighlighter(predicate, null, Color.BLUE)); showWithScrollingInFrame(table, "Foreground highlight col 1 and 3"); } /** * ColorHighlighter with pattern predicate * */ public void interactiveTablePatternHighlighter() { JXTable table = new JXTable(tableModel); table.setColumnControlVisible(true); table.addHighlighter(new ColorHighlighter(new PatternPredicate("^M", 1), null, Color.red)); showWithScrollingInFrame(table, "Pattern: highlight row if ^M col 1"); } /** * Issue #258-swingx: Background LegacyHighlighter must not change custom * foreground. *

* * Use SwingX extended default renderer. */ public void interactiveTableCustomRendererColor() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); DefaultTableRenderer renderer = new DefaultTableRenderer(); renderer.setForeground(foreground); renderer.setBackground(background); table.addHighlighter(HighlighterFactory.createAlternateStriping(Color.WHITE, HighlighterFactory.GENERIC_GRAY)); table.setDefaultRenderer(Object.class, renderer); JXTable nohighlight = new JXTable(model); nohighlight.setDefaultRenderer(Object.class, renderer); showWithScrollingInFrame(table, nohighlight, "ext: custom colored renderer with bg highlighter <--> shared without highl"); } /** * Requirement from forum: value based color and tooltip. * * Here the tooltip is regarded as visual decoration and * set in a specialized Highlighter. * */ public void interactiveValueBasedToolTipAndColorOnHighlighter() { JXTable table = new JXTable(new AncientSwingTeam()); HighlightPredicate predicate = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { if (!(adapter.getValue() instanceof Number)) return false; return ((Number) adapter.getValue()).intValue() < 10; } }; ColorHighlighter hl = new ColorHighlighter( predicate, null, Color.RED, null, Color.RED); // THINK this is possible, but maybe not the correct place // ... more on the what-side of "what vs. how" ? Highlighter tl = new AbstractHighlighter(predicate) { @Override protected Component doHighlight(Component component, ComponentAdapter adapter) { String text = "low on luck: " + ((JLabel) component).getText(); ((JComponent) component).setToolTipText(text); return component; } @Override protected boolean canHighlight(Component component, ComponentAdapter adapter) { return component instanceof JLabel; } }; table.setHighlighters(HighlighterFactory.createSimpleStriping(HighlighterFactory.GENERIC_GRAY), hl, tl); showWithScrollingInFrame(table, "Value-based Tooltip ... on Highlighter"); } /** * Requirement from forum: value based color and tooltip.

* * Here the tooltip is regarded as belonging more to the "what" * of rendering and set in a custom provider. The implication * is that the logic (whether to show the tooltip or not) is * duplicated (in the predicate and the provider. * * */ public void interactiveValueBasedToolTipAndColorOnProvider() { JXTable table = new JXTable(new AncientSwingTeam()); HighlightPredicate predicate = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { if (!(adapter.getValue() instanceof Number)) return false; return ((Number) adapter.getValue()).intValue() < 10; } }; ColorHighlighter hl = new ColorHighlighter( predicate, null, Color.RED, null, Color.RED); table.setHighlighters(HighlighterFactory.createSimpleStriping(HighlighterFactory.GENERIC_GRAY), hl); //, tl); // here: set's value based .. this duplicates logic of // predicate LabelProvider provider = new LabelProvider() { @Override protected void configureState(CellContext context) { super.configureState(context); rendererComponent.setToolTipText(getToolTipText(context)); } private String getToolTipText(CellContext context) { if ((context.getValue() instanceof Number)) { int luck = ((Number) context.getValue()).intValue(); if (luck < 10) { return "low on luck: " + luck; } } return null; } }; provider.setHorizontalAlignment(JLabel.RIGHT); table.setDefaultRenderer(Number.class, new DefaultTableRenderer(provider)); showWithScrollingInFrame(table, "Value-based Tooltip ... on provider"); } /** * Example of custom predicate based on the component's value, * (as opposed to on the value of the adapter). * * */ public void interactiveTableColorBasedOnComponentValue() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); table.setForeground(Color.GREEN); HighlightPredicate predicate = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { if (!(renderer instanceof JLabel)) return false; String text = ((JLabel) renderer).getText(); return text.contains("y"); } }; ColorHighlighter hl = new ColorHighlighter(predicate, null, Color.RED); table.addHighlighter(HighlighterFactory.createSimpleStriping(HighlighterFactory.GENERIC_GRAY)); table.addHighlighter(hl); showWithScrollingInFrame(table, "component value-based rendering (label text contains y) "); } //------------------ rollover /** * Issue #503-swingx: custom cursor respected when rollover? * Seems okay for table, */ public void interactiveRolloverHighlightCustomCursor() { JXTable table = new JXTable(tableModel); table.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); table.addHighlighter(new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW, Color.YELLOW, null)); showWithScrollingInFrame(table, "rollover highlight, custom cursor"); } /** * Plain RolloverHighlighter. * Issue #513-swingx: no rollover effect for disabled table. * */ public void interactiveRolloverHighlight() { final JXTable table = new JXTable(tableModel); ColorHighlighter colorHighlighter = new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW, Color.YELLOW, null); table.addHighlighter(colorHighlighter); Action action = new AbstractAction("toggle table enabled") { public void actionPerformed(ActionEvent e) { table.setEnabled(!table.isEnabled()); } }; JXFrame frame = showWithScrollingInFrame(table, "rollover highlight, enabled/disabled table"); addAction(frame, action); frame.pack(); } //--------------------- factory /** * shows the effect of a simple striping highlighter on a * colored table. * */ public void interactiveSimpleStriping() { JXTable table = new JXTable(tableModel); table.setVisibleRowCount(table.getRowCount() + 3); table.setBackground(Color.YELLOW); table.addHighlighter(HighlighterFactory.createSimpleStriping(Color.LIGHT_GRAY)); showWithScrollingInFrame(table, "Simple gray striping"); } /** * shows the effect of a simple striping highlighter on a * colored table. * */ public void interactiveSimpleStripingGroup() { JXTable table = new JXTable(tableModel); table.setVisibleRowCount(table.getRowCount() + 3); table.setBackground(Color.YELLOW); table.addHighlighter(HighlighterFactory.createSimpleStriping(Color.LIGHT_GRAY, 3)); showWithScrollingInFrame(table, "Simple gray striping, grouped by 3"); } /** * shows the effect of a simple striping highlighter on a * colored table. * */ public void interactiveAlternateStriping() { JXTable table = new JXTable(tableModel); table.setVisibleRowCount(table.getRowCount() + 3); table.setBackground(Color.YELLOW); table.addHighlighter(HighlighterFactory.createAlternateStriping(Color.WHITE, Color.LIGHT_GRAY)); showWithScrollingInFrame(table, "Alternate white/gray striping"); } /** * shows the effect of a simple striping highlighter on a * colored table. * */ public void interactiveAlternateStripingGroup() { JXTable table = new JXTable(tableModel); table.setVisibleRowCount(table.getRowCount() + 3); table.setBackground(Color.YELLOW); table.addHighlighter(HighlighterFactory.createAlternateStriping(Color.WHITE, Color.LIGHT_GRAY, 3)); showWithScrollingInFrame(table, "Alternate white/gray striping"); } @Override protected void setUp() throws Exception { super.setUp(); tableModel = new AncientSwingTeam(); } /** * Do nothing, make the test runner happy * (would output a warning without a test fixture). * */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/renderer/PainterVisualCheck.java0000644000175000017500000011271711210401722026115 0ustar tonytony/* * $Id: PainterVisualCheck.java,v 1.38 2009/03/10 14:36:27 kschaefe Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.renderer; import java.awt.Color; import java.awt.Component; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Logger; import javax.swing.Action; import javax.swing.DefaultListModel; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.KeyStroke; import javax.swing.ListModel; import javax.swing.Timer; import javax.swing.table.TableModel; import javax.swing.tree.TreeModel; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXList; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTree; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.action.ActionContainerFactory; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.HighlightPredicate; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.HighlighterFactory; import org.jdesktop.swingx.decorator.PainterHighlighter; import org.jdesktop.swingx.decorator.HighlightPredicate.ColumnHighlightPredicate; import org.jdesktop.swingx.decorator.HighlightPredicate.NotHighlightPredicate; import org.jdesktop.swingx.painter.AbstractLayoutPainter; import org.jdesktop.swingx.painter.AbstractPainter; import org.jdesktop.swingx.painter.BusyPainter; import org.jdesktop.swingx.painter.ImagePainter; import org.jdesktop.swingx.painter.MattePainter; import org.jdesktop.swingx.painter.Painter; import org.jdesktop.swingx.painter.ShapePainter; import org.jdesktop.swingx.painter.AbstractLayoutPainter.HorizontalAlignment; import org.jdesktop.swingx.painter.AbstractLayoutPainter.VerticalAlignment; import org.jdesktop.swingx.painter.effects.InnerGlowPathEffect; import org.jdesktop.swingx.table.ColumnControlButton; import org.jdesktop.swingx.test.XTestUtils; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.test.AncientSwingTeam; /** * Experiments with highlighters using painters.

* * Links *

* * * @author Jeanette Winzenburg */ public class PainterVisualCheck extends InteractiveTestCase { @SuppressWarnings("all") private static final Logger LOG = Logger .getLogger(PainterVisualCheck.class.getName()); public static void main(String args[]) { // setSystemLF(true); PainterVisualCheck test = new PainterVisualCheck(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Gradient.*"); // test.runInteractiveTests("interactive.*Icon.*"); // test.runInteractiveTests("interactive.*Animated.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } public void interactiveTriangleRenderer() { JXTable table = new JXTable(new AncientSwingTeam()); ShapePainter painter = new ShapePainter(); Shape polygon = new Polygon(new int[] { 0, 5, 5 }, new int[] { 0, 0, 5 }, 3); painter.setShape(polygon); painter.setFillPaint(Color.RED); painter.setStyle(ShapePainter.Style.FILLED); painter.setPaintStretched(false); // hmm.. how to make this stick to the trailing upper corner? painter.setHorizontalAlignment(HorizontalAlignment.RIGHT); painter.setVerticalAlignment(VerticalAlignment.TOP); Highlighter hl = new PainterHighlighter(new ColumnHighlightPredicate(3), painter); table.addHighlighter(hl); showWithScrollingInFrame(table, "Renderer with Triangle marker"); } /** * Use Painter for an underline-rollover effect. */ public void interactiveRolloverPainter() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); MattePainter matte = new MattePainter(getTransparentColor(Color.RED, 80)); RelativePainter painter = new RelativePainter(matte); painter.setYFactor(0.2); painter.setVerticalAlignment(VerticalAlignment.BOTTOM); Highlighter hl = new PainterHighlighter(HighlightPredicate.ROLLOVER_ROW, painter); table.addHighlighter(hl); JXFrame frame = wrapWithScrollingInFrame(table, "painter-aware renderer rollover"); addStatusComponent(frame, new JLabel("gradient background of cells with value's containing 'y'")); show(frame); } /** * Creates and returns a predicate for filtering labels whose text * property contains the given text. * @return */ private HighlightPredicate createComponentTextBasedPredicate(final String substring) { HighlightPredicate predicate = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { if (!(renderer instanceof JLabel)) return false; String text = ((JLabel) renderer).getText(); return text.contains(substring); } }; return predicate; } /** * Use ?? for fixed portion background highlighting * Use SwingX extended default renderer. */ public void interactiveTableBarHighlight() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); MattePainter p = new MattePainter(getTransparentColor(Color.BLUE, 125)); RelativePainter relativePainter = new RelativePainter(p); relativePainter.setXFactor(.5); Highlighter hl = new PainterHighlighter(createComponentTextBasedPredicate("y"), relativePainter); table.addHighlighter(hl); JXFrame frame = wrapWithScrollingInFrame(table, "painter-aware renderer with value-based highlighting"); addMessage(frame, "bar in cells with value containing y"); show(frame); } //------------------------ Transparent painter aware button as rendering component /** * Use a custom button controller to show both checkbox icon and text to * render Actions in a JXList. Apply striping and a simple gradient highlighter. */ public void interactiveTableWithListColumnControl() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); JXList list = new JXList(); Highlighter highlighter = HighlighterFactory.createSimpleStriping(HighlighterFactory.LINE_PRINTER); table.addHighlighter(highlighter); Painter gradient = createGradientPainter(Color.YELLOW, .7f, true); list.setHighlighters(highlighter, new PainterHighlighter(gradient)); // quick-fill and hook to table columns' visibility state configureList(list, table, false); // a custom rendering button controller showing both checkbox and text StringValue sv = new StringValue() { public String getString(Object value) { if (value instanceof AbstractActionExt) { return ((AbstractActionExt) value).getName(); } return ""; } }; BooleanValue bv = new BooleanValue() { public boolean getBoolean(Object value) { if (value instanceof AbstractActionExt) { return ((AbstractActionExt) value).isSelected(); } return false; } }; CheckBoxProvider wrapper = new CheckBoxProvider(new MappedValue(sv, null, bv), JLabel.LEADING); list.setCellRenderer(new DefaultListRenderer(wrapper)); JXFrame frame = showWithScrollingInFrame(table, list, "checkbox list-renderer - striping and gradient"); addStatusMessage(frame, "fake editable list: space/doubleclick on selected item toggles column visibility"); frame.pack(); } /** * Creates and returns a Painter with a gradient paint starting with * startColor to WHITE. * * @param startColor * @param percentage * @param transparent * @return */ protected Painter createGradientPainter(Color startColor, float end, boolean transparent) { startColor = getTransparentColor(startColor, transparent ? 125 : 254); Color endColor = getTransparentColor(Color.WHITE, 0); GradientPaint paint = new GradientPaint( new Point2D.Double(0, 0), startColor, new Point2D.Double(1000, 0), endColor); MattePainter painter = new MattePainter(paint); painter.setPaintStretched(true); // not entirely successful - the relative stretching is on // top of a .5 stretched gradient in matte RelativePainter wrapper = new RelativePainter(painter); wrapper.setXFactor(end); return wrapper; } private static Color getTransparentColor(Color base, int transparency) { return new Color(base.getRed(), base.getGreen(), base.getBlue(), transparency); } // ------------------------ /** * Use highlighter with background image painter. Shared by table and list. */ public void interactiveIconPainterHighlight() throws Exception { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); ComponentProvider controller = new LabelProvider( JLabel.RIGHT); table.getColumn(0).setCellRenderer( new DefaultTableRenderer(controller)); final ImagePainter imagePainter = new ImagePainter(XTestUtils.loadDefaultImage()); HighlightPredicate predicate = new ColumnHighlightPredicate(0); Highlighter iconHighlighter = new PainterHighlighter(predicate, imagePainter ); Highlighter alternateRowHighlighter = HighlighterFactory.createSimpleStriping(); table.addHighlighter(alternateRowHighlighter); table.addHighlighter(iconHighlighter); // re-use component controller and highlighter in a JXList JXList list = new JXList(createListNumberModel(), true); list.setCellRenderer(new DefaultListRenderer(controller)); list.addHighlighter(alternateRowHighlighter); list.addHighlighter(iconHighlighter); list.toggleSortOrder(); final JXFrame frame = showWithScrollingInFrame(table, list, "image highlighting plus striping"); frame.pack(); } /** * Use highlighter with image painter which is positioned relative to * cell value. */ public void interactivePositionedIconPainterHighlight() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); final ImagePainter imagePainter = new ImagePainter(XTestUtils.loadDefaultImage("green-orb.png")); imagePainter.setHorizontalAlignment(HorizontalAlignment.RIGHT); imagePainter.setAreaEffects(new InnerGlowPathEffect()); ValueBasedPositionalHighlighter iconHighlighter = new ValueBasedPositionalHighlighter(); iconHighlighter.setDelegatePainter(imagePainter); iconHighlighter.setHorizontalAlignment(HorizontalAlignment.LEFT); table.getColumnExt(3).addHighlighter(iconHighlighter); // re-use component controller and highlighter in a JXList JXList list = new JXList(createListNumberModel(), true); list.setCellRenderer(new DefaultListRenderer(new LabelProvider(JLabel.RIGHT))); list.addHighlighter(iconHighlighter); list.toggleSortOrder(); showWithScrollingInFrame(table, list, "value-based image position highlighting"); } /** * Use highlighter with image painter which is positioned relative to * cell value. */ public void interactiveAnimatedIconPainterHighlight() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); ImagePainter imagePainter = new ImagePainter(XTestUtils.loadDefaultImage("green-orb.png")); imagePainter.setHorizontalAlignment(HorizontalAlignment.RIGHT); final RelativePainter painter = new RelativePainter(imagePainter); PainterHighlighter iconHighlighter = new PainterHighlighter(); iconHighlighter.setHighlightPredicate(HighlightPredicate.ROLLOVER_ROW); iconHighlighter.setPainter(painter); ActionListener l = new ActionListener() { public void actionPerformed(ActionEvent e) { double fraction = painter.getXFactor(); fraction = fraction > 1 ? 0.0 : fraction + 0.1; painter.setXFactor(fraction); } }; table.addHighlighter(iconHighlighter); showWithScrollingInFrame(table, "Animated highlighter: marching icon on rollover"); Timer timer = new Timer(100, l); timer.start(); } /** * Use highlighter with BusyPainter. */ public void interactiveAnimatedBusyPainterHighlight() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); table.getColumn(0).setCellRenderer(new DefaultTableRenderer( new HyperlinkProvider())); final BusyPainter busyPainter = new BusyPainter() { /** * Overridden to fix Issue #861-swingx: must notify on change * @param frame */ @Override public void setFrame(int frame) { int old = getFrame(); super.setFrame(frame); firePropertyChange("frame", old, getFrame()); } }; // JW: how do we ask for the height of the painter? table.setRowHeight(26); PainterHighlighter iconHighlighter = new PainterHighlighter(); iconHighlighter.setHighlightPredicate(HighlightPredicate.ROLLOVER_ROW); iconHighlighter.setPainter(busyPainter); ActionListener l = new ActionListener() { public void actionPerformed(ActionEvent e) { int frame = busyPainter.getFrame(); frame = (frame+1)%busyPainter.getPoints(); busyPainter.setFrame(frame); } }; table.addHighlighter(iconHighlighter); showWithScrollingInFrame(table, "Animated highlighter: BusyPainter on Rollover"); Timer timer = new Timer(100, l); timer.start(); } /** * Issue #862-swingx: SwingX rendering components should be PainterAware. * * Currently this works only with a local version which has WrappingIconPanel * implement the PainterAware by delegating to its content delegate. */ public void interactiveAnimatedIconPainterHighlightTree() { TreeModel model = new FileSystemModel(); JXTree tree = new JXTree(model); tree.setRolloverEnabled(true); tree.setCellRenderer(new DefaultTreeRenderer(StringValues.FILE_NAME)); ImagePainter imagePainter = new ImagePainter(XTestUtils.loadDefaultImage("green-orb.png")); imagePainter.setHorizontalAlignment(HorizontalAlignment.RIGHT); final RelativePainter painter = new RelativePainter(imagePainter); PainterHighlighter iconHighlighter = new PainterHighlighter(); iconHighlighter.setHighlightPredicate(HighlightPredicate.ROLLOVER_ROW); iconHighlighter.setPainter(painter); ActionListener l = new ActionListener() { public void actionPerformed(ActionEvent e) { double fraction = painter.getXFactor(); fraction = fraction > 1 ? 0.0 : fraction + 0.1; painter.setXFactor(fraction); } }; tree.addHighlighter(iconHighlighter); showWithScrollingInFrame(tree, "Animated highlighter: marching icon on rollover"); Timer timer = new Timer(100, l); timer.start(); } /** * Use custom painter and highlighter for per-row image decoration. * * @throws IOException */ public void interactivePerRowImage() throws IOException { JXTable table = new JXTable(new AncientSwingTeam()); table.setForeground(Color.MAGENTA); table.setSelectionForeground(Color.BLUE); table.setColumnControlVisible(true); table.setRowHeight(25); final BufferedImage moon = XTestUtils.loadDefaultImage("moon.jpg"); final BufferedImage rocket = XTestUtils.loadDefaultImage("500by500.png"); HighlightPredicate rocketPredicate = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { return ((Integer) adapter.getValue(3)).intValue() < 50; } }; HighlightPredicate moonPredicate = new NotHighlightPredicate(rocketPredicate); table.setHighlighters( new SubImagePainterHighlighter(rocketPredicate, new SubImagePainter(rocket)) , new SubImagePainterHighlighter(moonPredicate, new SubImagePainter(moon)) ); JXFrame frame = wrapWithScrollingInFrame(table, "painter in renderer"); show(frame); } /** * Custom PainterHighlighter configures a SubImagePainter. * */ public static class SubImagePainterHighlighter extends PainterHighlighter { public SubImagePainterHighlighter(HighlightPredicate predicate, SubImagePainter painter) { super(predicate, painter); } @Override protected Component doHighlight(Component component, ComponentAdapter adapter) { Rectangle cellRect = getCellBounds(adapter); ((SubImagePainter) getPainter()).setImageClip(cellRect); return super.doHighlight(component, adapter); } private Rectangle getCellBounds(ComponentAdapter adapter) { // PENDING JW: add method to adapter JXTable table = (JXTable) adapter.getComponent(); Rectangle cellRect = table.getCellRect(adapter.row, adapter.column, false); return cellRect; } @Override protected boolean canHighlight(Component component, ComponentAdapter adapter) { return super.canHighlight(component, adapter) && (adapter.getComponent() instanceof JTable); } } /** * Simple Painter for subimage. */ public static class SubImagePainter extends AbstractPainter { BufferedImage image; Rectangle imageClip; public SubImagePainter(BufferedImage image) { super(false); this.image = image; } public void setImageClip(Rectangle imageClip) { this.imageClip = imageClip; } @Override protected void doPaint(Graphics2D g, Object object, int width, int height) { if ((imageClip == null) || (imageClip.width <= 0) || (imageClip.height <= 0)) return; if (imageClip.x + width >= image.getWidth()) return; if (imageClip.y + height >= image.getWidth()) return; Image subImage = image.getSubimage( imageClip.x, imageClip.y, width, height); g.drawImage(subImage, 0, 0, width, height, null); } } // ----------------- Transparent gradient on default (swingx) rendering label /** * Use transparent gradient painter for value-based background highlighting * with SwingX extended default renderer. Shared by table and list with * striping. */ public void interactiveNumberProportionalGradientHighlightPlusStriping() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); ComponentProvider controller = new LabelProvider( JLabel.RIGHT) ; final ValueBasedGradientHighlighter gradientHighlighter = createTransparentGradientHighlighter(); gradientHighlighter.setHorizontalAlignment(HorizontalAlignment.RIGHT); Highlighter alternateRowHighlighter = HighlighterFactory.createSimpleStriping(); table.addHighlighter(alternateRowHighlighter); table.addHighlighter(gradientHighlighter); // re-use component controller and highlighter in a JXList JXList list = new JXList(createListNumberModel(), true); list.setCellRenderer(new DefaultListRenderer(controller)); list.addHighlighter(alternateRowHighlighter); list.addHighlighter(gradientHighlighter); list.toggleSortOrder(); final JXFrame frame = wrapWithScrollingInFrame(table, list, "transparent value relative highlighting plus striping"); addStatusMessage(frame, "uses a PainterAwareLabel in renderer"); // crude binding to play with options - the factory is incomplete... addStatusComponent(frame, createTransparencyToggle(gradientHighlighter)); show(frame); } /** * Use transparent gradient painter for value-based background highlighting * with SwingX extended default renderer. Shared by table and list with * background color. */ public void interactiveNumberProportionalGradientHighlight() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); table.setBackground(HighlighterFactory.LEDGER); ComponentProvider controller = new LabelProvider( JLabel.RIGHT); // table.setDefaultRenderer(Number.class, new DefaultTableRenderer( // controller)); ValueBasedGradientHighlighter gradientHighlighter = createTransparentGradientHighlighter(); gradientHighlighter.setHorizontalAlignment(HorizontalAlignment.RIGHT); table.addHighlighter(gradientHighlighter); // re-use component controller and highlighter in a JXList JXList list = new JXList(createListNumberModel(), true); list.setBackground(table.getBackground()); list.setCellRenderer(new DefaultListRenderer(controller)); list.addHighlighter(gradientHighlighter); list.toggleSortOrder(); JXFrame frame = wrapWithScrollingInFrame(table, list, "transparent value relative highlighting"); addStatusMessage(frame, "uses the default painter-aware label in renderer"); // crude binding to play with options - the factory is incomplete... addStatusComponent(frame, createTransparencyToggle(gradientHighlighter)); show(frame); } //--------- hack around missing size proportional painters public static class RelativePainter extends AbstractLayoutPainter { private Painter painter; private double xFactor; private double yFactor; public RelativePainter() { this(null); } public void setPainter(Painter painter) { Object old = getPainter(); this.painter = painter; firePropertyChange("painter", old, getPainter()); } public Painter getPainter() { return painter; } public RelativePainter(Painter delegate) { this.painter = delegate; } public void setXFactor(double xPercent) { double old = getXFactor(); this.xFactor = xPercent; firePropertyChange("xFactor", old, getXFactor()); } /** * @return */ private double getXFactor() { return xFactor; } public void setYFactor(double yPercent) { this.yFactor = yPercent; } @Override protected void doPaint(Graphics2D g, T object, int width, int height) { if (painter == null) return; // use epsilon if (xFactor != 0.0) { int oldWidth = width; width = (int) (xFactor * width); if (getHorizontalAlignment() == HorizontalAlignment.RIGHT) { g.translate(oldWidth - width, 0); } } if (yFactor != 0.0) { int oldHeight = height; height = (int) (yFactor * height); if (getVerticalAlignment() == VerticalAlignment.BOTTOM) { g.translate(0, oldHeight - height); } } painter.paint(g, object, width, height); } } // -------------------- Value-based transparent gradient highlighter /** * A Highlighter which applies a value-proportional gradient to PainterAware * rendering components if the value is a Number. The gradient is a simple * red to red.brigther paint. The red can be toggled to * half-transparent.

* */ public static class ValueBasedGradientHighlighter extends PainterHighlighter { float maxValue = 100; private boolean yellowTransparent; public ValueBasedGradientHighlighter() { this(false); } /** * @param b */ public ValueBasedGradientHighlighter(boolean b) { super(new RelativePainter()); setYellowTransparent(b); } /** * Overridden to do nothing if it's not a RelativePainter. We * roll our own. */ @Override public void setPainter(Painter painter) { if (!(painter instanceof RelativePainter)) return; super.setPainter(painter); } @Override public RelativePainter getPainter() { return (RelativePainter) super.getPainter(); } @Override protected Component doHighlight(Component renderer, ComponentAdapter adapter) { float end = getEndOfGradient((Number) adapter.getValue()); if (end > 1) { renderer.setBackground(Color.RED.darker()); renderer.setForeground(Color.WHITE); } else if (end > 0.02) { Painter painter = getPainter(end); ((PainterAware) renderer).setPainter(painter); } return renderer; } @Override protected boolean canHighlight(Component component, ComponentAdapter adapter) { return (adapter.getValue() instanceof Number) && super.canHighlight(component, adapter); } /** * @param yellowTransparent */ public void setYellowTransparent(boolean yellowTransparent) { if (this.yellowTransparent == yellowTransparent) return; this.yellowTransparent = yellowTransparent; getPainter().setPainter(null); fireStateChanged(); } public void setHorizontalAlignment(HorizontalAlignment align) { getPainter().setHorizontalAlignment(align); fireStateChanged(); } public HorizontalAlignment getHorizontalAlignment() { return getPainter().getHorizontalAlignment(); } private Painter getPainter(float end) { if (getPainter().getPainter() == null) { Color startColor = getTransparentColor(Color.RED, yellowTransparent ? 125 : 254); Color endColor = getTransparentColor(Color.RED.brighter(), 0); boolean isRightAligned = HorizontalAlignment.RIGHT == getHorizontalAlignment(); GradientPaint paint = new GradientPaint(new Point2D.Double(0, 0), isRightAligned ? endColor : startColor, new Point2D.Double(100, 0), isRightAligned ? startColor : endColor); MattePainter painter = new MattePainter(paint); painter.setPaintStretched(true); getPainter().setPainter(painter); } getPainter().setXFactor(end); return getPainter(); } private Color getTransparentColor(Color base, int transparency) { return new Color(base.getRed(), base.getGreen(), base.getBlue(), transparency); } private float getEndOfGradient(Number number) { float end = number.floatValue() / maxValue; return end; } } /** * A Highlighter which applies a value-proportional gradient to PainterAware * rendering components if the value is a Number. The gradient is a simple * red to red.brigther paint. The red can be toggled to * half-transparent.

* */ public static class ValueBasedPositionalHighlighter extends PainterHighlighter { float maxValue = 100; public ValueBasedPositionalHighlighter() { super(new RelativePainter()); } /** * Overridden to do nothing if it's not a RelativePainter. We * roll our own. */ @Override public void setPainter(Painter painter) { if (!(painter instanceof RelativePainter)) return; super.setPainter(painter); } @Override public RelativePainter getPainter() { return (RelativePainter) super.getPainter(); } public void setDelegatePainter(Painter painter) { getPainter().setPainter(painter); } @Override protected Component doHighlight(Component renderer, ComponentAdapter adapter) { float end = getEndOfGradient((Number) adapter.getValue()); if (end > 1) { renderer.setBackground(Color.RED.darker()); renderer.setForeground(Color.WHITE); } else if (end > 0.02) { Painter painter = getPainter(end); ((PainterAware) renderer).setPainter(painter); } return renderer; } @Override protected boolean canHighlight(Component component, ComponentAdapter adapter) { return (adapter.getValue() instanceof Number) && super.canHighlight(component, adapter); } public void setHorizontalAlignment(HorizontalAlignment align) { getPainter().setHorizontalAlignment(align); fireStateChanged(); } public HorizontalAlignment getHorizontalAlignment() { return getPainter().getHorizontalAlignment(); } private Painter getPainter(float end) { getPainter().setXFactor(end); return getPainter(); } private float getEndOfGradient(Number number) { float end = number.floatValue() / maxValue; return end; } } /** * creates and returns a highlighter with a value-based transparent gradient * if the cell content type is a Number. * * @return */ private ValueBasedGradientHighlighter createTransparentGradientHighlighter() { return new ValueBasedGradientHighlighter(); } /** * Creates and returns a checkbox to toggle the gradient's yellow * transparency. * * @param gradientHighlighter * @return */ private JCheckBox createTransparencyToggle( final ValueBasedGradientHighlighter gradientHighlighter) { ActionContainerFactory factory = new ActionContainerFactory(); // toggle opaque optimatization AbstractActionExt toggleTransparent = new AbstractActionExt( "yellow transparent") { public void actionPerformed(ActionEvent e) { gradientHighlighter.setYellowTransparent(isSelected()); } }; toggleTransparent.setStateAction(); JCheckBox box = new JCheckBox(); factory.configureButton(box, toggleTransparent, null); return box; } //----------------- Utility /** * * @return a ListModel wrapped around the AncientSwingTeam's Number column. */ private ListModel createListNumberModel() { AncientSwingTeam tableModel = new AncientSwingTeam(); int colorColumn = 3; DefaultListModel model = new DefaultListModel(); for (int i = 0; i < tableModel.getRowCount(); i++) { model.addElement(tableModel.getValueAt(i, colorColumn)); } return model; } /** * Fills the list with a collection of actions (as returned from the * table's column control). Binds space and double-click to toggle * the action's selected state. * * note: this is just an example to show-off the button renderer in a list! * ... it's very dirty!! * * @param list * @param table */ private void configureList(final JXList list, final JXTable table, boolean useRollover) { final List actions = new ArrayList(); @SuppressWarnings("all") ColumnControlButton columnControl = new ColumnControlButton(table) { @Override protected void addVisibilityActionItems() { actions.addAll(Collections .unmodifiableList(getColumnVisibilityActions())); } }; list.setModel(createListeningListModel(actions)); // action toggling selected state of selected list item final Action toggleSelected = new AbstractActionExt( "toggle column visibility") { public void actionPerformed(ActionEvent e) { if (list.isSelectionEmpty()) return; AbstractActionExt selectedItem = (AbstractActionExt) list .getSelectedValue(); selectedItem.setSelected(!selectedItem.isSelected()); } }; if (useRollover) { list.setRolloverEnabled(true); } else { // bind action to space list.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "toggleSelectedActionState"); } list.getActionMap().put("toggleSelectedActionState", toggleSelected); // bind action to double-click MouseAdapter adapter = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { toggleSelected.actionPerformed(null); } } }; list.addMouseListener(adapter); } /** * Creates and returns a ListModel containing the given actions. * Registers a PropertyChangeListener with each action to get * notified and fire ListEvents. * * @param actions the actions to add into the model. * @return the filled model. */ private ListModel createListeningListModel(final List actions) { final DefaultListModel model = new DefaultListModel() { DefaultListModel reallyThis = this; @Override public void addElement(Object obj) { super.addElement(obj); ((Action) obj).addPropertyChangeListener(l); } PropertyChangeListener l = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { int index = indexOf(evt.getSource()); if (index >= 0) { fireContentsChanged(reallyThis, index, index); } } }; }; for (Action action : actions) { model.addElement(action); } return model; } /** * do-nothing method - suppress warning if there are no other * test fixtures to run. * */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/renderer/StringValuesTest.java0000644000175000017500000000470311210401722025652 0ustar tonytony/* * $Id: StringValuesTest.java,v 1.4 2009/03/11 13:45:10 kleopatra Exp $ * * Copyright 2008 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.renderer; import java.io.File; import junit.framework.TestCase; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * * @author Karl George Schaefer */ @RunWith(JUnit4.class) public class StringValuesTest extends TestCase { @Test public void testFileNameWithNonFile() { Object o = new Object(); assertEquals(StringValues.TO_STRING.getString(o), StringValues.FILE_NAME.getString(o)); } //not asserting the output of file name just that it isn't empty // PENDING JW: don't quite understand what we are testing here - need to update to // TO_STRING as of fixing #972? @Test public void testFileNameWithFile() throws Exception { File f = File.createTempFile("svt", "tmp"); f.deleteOnExit(); assertNotSame(StringValues.EMPTY.getString(f), StringValues.FILE_NAME.getString(f)); } @Test public void testFileTypeWithNonFile() { Object o = new Object(); assertEquals(StringValues.TO_STRING.getString(o), StringValues.FILE_TYPE.getString(o)); } //not asserting the output of file type just that it isn't empty @Test public void testFileTypeWithFile() throws Exception { File f = File.createTempFile("svt", "tmp"); f.deleteOnExit(); assertNotSame(StringValues.EMPTY.getString(f), StringValues.FILE_TYPE.getString(f)); } } swingx-1.0-src/src/test/org/jdesktop/swingx/renderer/ListRendererTest.java0000644000175000017500000003276011210401724025634 0ustar tonytony/* * $Id: ListRendererTest.java,v 1.15 2008/10/11 20:42:32 rah003 Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.renderer; import java.awt.Color; import java.awt.Component; import java.io.Serializable; import java.text.DateFormat; import java.util.logging.Logger; import javax.swing.DefaultListCellRenderer; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; import javax.swing.UIManager; import javax.swing.border.Border; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.test.XTestUtils; import org.jdesktop.test.SerializableSupport; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; import com.sun.java.swing.plaf.motif.MotifLookAndFeel; /** * Tests behaviour of SwingX renderers. Currently: mostly characterization to * guarantee that they behave similar to the standard. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class ListRendererTest extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(ListRendererTest.class .getName()); private DefaultListCellRenderer coreListRenderer; private DefaultListRenderer xListRenderer; private JList list; @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } @Override protected void setUp() throws Exception { setSystemLF(true); list = new JList(new Object[] {1, 2, 3}); coreListRenderer = new DefaultListCellRenderer(); xListRenderer = new DefaultListRenderer(); } /** * Test constructors: here convenience with alignment and converter * */ @Test public void testConstructor() { FormatStringValue sv = new FormatStringValue(DateFormat.getTimeInstance()); int align = JLabel.RIGHT; DefaultListRenderer renderer = new DefaultListRenderer(sv, align); assertEquals(sv, renderer.componentController.getStringValue()); assertEquals(align, renderer.componentController.getHorizontalAlignment()); } /** * test if default icon/text handling in DefaultListRenderer * is the same as core default. * */ @Test public void testIcon() { Icon icon = XTestUtils.loadDefaultIcon(); String text = "dummy"; JList list = new JList(new Object[] {icon, text}); coreListRenderer.getListCellRendererComponent(list, icon, 0, false, false); JLabel label = (JLabel) xListRenderer.getListCellRendererComponent(null, icon, 0, false, false); assertEquals("sanity: core shows icon", icon, coreListRenderer.getIcon()); assertEquals("sanity: core shows empty string", "", coreListRenderer.getText()); assertEquals("swingx renderer same icon as core", coreListRenderer.getIcon(), label.getIcon()); assertEquals("swingx renderer same text as core", coreListRenderer.getText(), label.getText()); coreListRenderer.getListCellRendererComponent(list, text, 1, false, false); label = (JLabel) xListRenderer.getListCellRendererComponent(null, text, 1, false, false); assertNull("sanity: core has null icon", coreListRenderer.getIcon()); assertEquals("sanity: core shows text", text, coreListRenderer.getText()); assertEquals("swingx renderer same same icon as core", coreListRenderer.getIcon(), label.getIcon()); assertEquals("swingx renderer same text as core", coreListRenderer.getText(), label.getText()); } /** * test serializable of default renderer. * */ @Test public void testSerializeListRenderer() { ListCellRenderer xListRenderer = new DefaultListRenderer(); try { SerializableSupport.serialize(xListRenderer); } catch (Exception e) { fail("not serializable " + e); } } /** * base interaction with list: focused, not-selected uses UI border. */ @Test public void testListFocusSelectedBorder() { // sanity to see test test validity // UIManager.put("List.focusSelectedCellHighlightBorder", new LineBorder(Color.red)); // access ui colors Border selectedFocusBorder = getFocusBorder(true); // sanity if (selectedFocusBorder == null) { LOG.info("cannot run focusSelectedBorder - UI has no selected focus border"); return; } LOG.info("selectedBorder: " + selectedFocusBorder); // need to prepare directly - focus is true only if list is focusowner JComponent coreComponent = (JComponent) coreListRenderer.getListCellRendererComponent(list, null, 0, true, true); // sanity: known standard behaviour assertEquals(selectedFocusBorder, coreComponent.getBorder()); // prepare extended JComponent xComponent = (JComponent) xListRenderer.getListCellRendererComponent(list, null, 0, true, true); // assert behaviour same as standard assertEquals(coreComponent.getBorder(), xComponent.getBorder()); } private Border getFocusBorder(boolean lookup) { Border selectedFocusBorder = UIManager.getBorder("List.focusSelectedCellHighlightBorder"); if (lookup && (selectedFocusBorder == null)) { selectedFocusBorder = UIManager.getBorder("List.focusCellHighlightBorder"); } return selectedFocusBorder; } /** * base interaction with list: focused, not-selected uses UI border. * * TODO: fix and reinstate the test * JW Done, partly: the new server seems to have MotifLF * as systemLF? - so backing out early. * Still open: Need to think about the validity of this test anway */ @Test public void testListFocusBorder() { if (UIManager.getLookAndFeel() instanceof MotifLookAndFeel) { LOG.info("can't run test - MotifLF uses the same focusBorder for list and table"); return; } // access ui colors Border focusBorder = UIManager.getBorder("List.focusCellHighlightBorder"); // sanity assertNotNull(focusBorder); // JW: this looks suspicious ... // RAH: line below makes hudson fail the test tho it runs fine locally ... assertNotSame(focusBorder, UIManager.getBorder("Table.focusCellHighlightBorder")); // need to prepare directly - focus is true only if list is focusowner JComponent coreComponent = (JComponent) coreListRenderer.getListCellRendererComponent(list, null, 0, false, true); // sanity: known standard behaviour assertEquals(focusBorder, coreComponent.getBorder()); // prepare extended JComponent xComponent = (JComponent) xListRenderer.getListCellRendererComponent(list, null, 0, false, true); // assert behaviour same as standard assertEquals(coreComponent.getBorder(), xComponent.getBorder()); } /** * base interaction with table: custom color of renderer precedes * table color. * */ @Test public void testListRendererExtCustomColor() { Color background = Color.MAGENTA; Color foreground = Color.YELLOW; // // prepare standard - not applicable for core default list renderer // coreListRenderer.setBackground(background); // coreListRenderer.setForeground(foreground); // Component coreComponent = coreListRenderer.getListCellRendererComponent(list, // null, 0, false, false); // prepare extended xListRenderer.setBackground(background); xListRenderer.setForeground(foreground); Component xComponent = xListRenderer.getListCellRendererComponent(list, null, 0, false, false); // assert behaviour same as standard assertEquals(background, xComponent.getBackground()); assertEquals(foreground, xComponent.getForeground()); } /** * base interaction with list: renderer uses list's selection color. * */ @Test public void testListRendererExtSelectedColors() { // select first row list.setSelectedIndex(0); // prepare standard Component coreComponent = coreListRenderer.getListCellRendererComponent(list, null, 0, true, false); // sanity: known standard behaviour assertEquals(list.getSelectionBackground(), coreComponent.getBackground()); assertEquals(list.getSelectionForeground(), coreComponent.getForeground()); // prepare extended Component xComponent = xListRenderer.getListCellRendererComponent(list, null, 0, true, false); // assert behaviour same as standard assertEquals(coreComponent.getBackground(), xComponent.getBackground()); assertEquals(coreComponent.getForeground(), xComponent.getForeground()); } /** * base interaction with list: renderer uses list's custom selection color. * */ @Test public void testListRendererExtListSelectedColors() { Color background = Color.MAGENTA; Color foreground = Color.YELLOW; list.setSelectionBackground(background); list.setSelectionForeground(foreground); // select first row list.setSelectedIndex(0); // prepare standard Component coreComponent = coreListRenderer.getListCellRendererComponent(list, null, 0, true, false); // sanity: known standard behaviour assertEquals(list.getSelectionBackground(), coreComponent.getBackground()); assertEquals(list.getSelectionForeground(), coreComponent.getForeground()); // prepare extended Component xComponent = xListRenderer.getListCellRendererComponent(list, null, 0, true, false); // assert behaviour same as standard assertEquals(coreComponent.getBackground(), xComponent.getBackground()); assertEquals(coreComponent.getForeground(), xComponent.getForeground()); } /** * base interaction with list: renderer uses list's unselected custom colors * * */ @Test public void testListRendererExtListColors() { Color background = Color.MAGENTA; Color foreground = Color.YELLOW; list.setBackground(background); list.setForeground(foreground); // prepare standard Component coreComponent = coreListRenderer.getListCellRendererComponent(list, null, 0, false, false); // sanity: known standard behaviour assertEquals(list.getBackground(), coreComponent.getBackground()); assertEquals(list.getForeground(), coreComponent.getForeground()); // prepare extended Component xComponent = xListRenderer.getListCellRendererComponent(list, null, 0, false, false); // assert behaviour same as standard assertEquals(coreComponent.getBackground(), xComponent.getBackground()); assertEquals(coreComponent.getForeground(), xComponent.getForeground()); } /** * base interaction with list: renderer uses list's unselected colors * * */ @Test public void testListRendererExtColors() { // prepare standard Component coreComponent = coreListRenderer.getListCellRendererComponent(list, null, 0, false, false); // sanity: known standard behaviour assertEquals(list.getBackground(), coreComponent.getBackground()); assertEquals(list.getForeground(), coreComponent.getForeground()); // prepare extended Component xComponent = xListRenderer.getListCellRendererComponent(list, null, 0, false, false); // assert behaviour same as standard assertEquals(coreComponent.getBackground(), xComponent.getBackground()); assertEquals(coreComponent.getForeground(), xComponent.getForeground()); } /** * characterize opaqueness of rendering components. * */ @Test public void testListOpaqueRenderer() { // sanity assertFalse(new JLabel().isOpaque()); assertTrue(coreListRenderer.isOpaque()); // assertTrue(xListRenderer.getRendererComponent().isOpaque()); } /** * base existence/type tests while adding DefaultTableCellRendererExt. * */ @Test public void testListRendererExt() { DefaultListRenderer renderer = new DefaultListRenderer(); assertTrue(renderer instanceof ListCellRenderer); assertTrue(renderer instanceof Serializable); } } swingx-1.0-src/src/test/org/jdesktop/swingx/renderer/RenderingTest.java0000644000175000017500000013750411210401722025147 0ustar tonytony/* * $Id: RenderingTest.java,v 1.43 2009/03/11 10:50:51 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.renderer; import java.awt.Color; import java.awt.Dimension; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.MouseListener; import java.text.DateFormat; import java.util.logging.Logger; import javax.swing.AbstractButton; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.ToolTipManager; import javax.swing.tree.DefaultMutableTreeNode; import junit.framework.TestCase; import org.jdesktop.swingx.JXHyperlink; import org.jdesktop.swingx.JXPanel; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTreeTable; import org.jdesktop.swingx.hyperlink.AbstractHyperlinkAction; import org.jdesktop.swingx.icon.EmptyIcon; import org.jdesktop.swingx.painter.ShapePainter; import org.jdesktop.swingx.table.TableColumnExt; import org.jdesktop.swingx.test.ComponentTreeTableModel; import org.jdesktop.swingx.test.XTestUtils; import org.jdesktop.test.PropertyChangeReport; import org.jdesktop.test.TestUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests swingx rendering infrastructure: ComponentProvider, CellContext, * .. * * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class RenderingTest extends TestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger.getLogger(RenderingTest.class .getName()); /** * Issue #766-swingx: flickering cursor on drop over. * * test hack configuration (arrrggg ...) */ @Test public void testWrappingIconPanelDropHackDefault() { JXPanel sanity = new JXPanel(); assertEquals("visible by default", true, sanity.isVisible()); WrappingIconPanel panel = new WrappingIconPanel(); assertEquals("invisible by default", false, panel.isVisible()); panel.setDropHackEnabled(false); assertEquals("disabled hack", true, panel.isVisible()); } /** * Issue #766-swingx: flickering cursor on drop over. * * test hack configuration (arrrggg ...) */ @Test public void testWrappingIconPanelDropHackConstructor() { JXPanel sanity = new JXPanel(); assertEquals("visible by default", true, sanity.isVisible()); WrappingIconPanel panel = new WrappingIconPanel(false); assertEquals("invisible by default", true, panel.isVisible()); panel.setDropHackEnabled(true); assertEquals("disabled hack", false, panel.isVisible()); } /** * Issue #863-swingx: SwingX renderering components must be PainterAware. * Here: test Hyperlink */ @Test public void testHyperlinkPainterAware() { HyperlinkProvider provider = new HyperlinkProvider(); assertTrue("hyperlink as rendering comp must be PainterAware", provider.getRendererComponent(null) instanceof PainterAware); } /** * Issue #863-swingx: SwingX renderering components must be PainterAware. * Here: test WrappingIconPanel */ @Test public void testWrappingIconPanelPainterAware() { DefaultTreeRenderer renderer = new DefaultTreeRenderer(); JComponent rendererComponent = renderer.getComponentProvider().getRendererComponent(null); assertTrue("wrappingIconPanel as rendering comp must be PainterAware", rendererComponent instanceof PainterAware); } /** * Issue #840-swingx: hyperlink foreground unreadable for dark selection colors. * * Test that selected foreground is same as table. * */ @Test public void testHyperlinkProviderForeground() { JXTable table = new JXTable(20, 2); HyperlinkProvider provider = new HyperlinkProvider(); JXHyperlink hyperlink = provider.getRendererComponent(null); Color unclicked = hyperlink.getUnclickedColor(); table.setDefaultRenderer(Object.class, new DefaultTableRenderer(provider)); table.prepareRenderer(table.getCellRenderer(0, 0), 0, 0); assertEquals("hyperlink foreground set to unclicked", unclicked, hyperlink.getForeground()); table.setRowSelectionInterval(0, 0); // JW: had been failing before because I forgot to re-prepare :-) table.prepareRenderer(table.getCellRenderer(0, 0), 0, 0); assertEquals("hyperlink foreground set to table's selection foreground", table.getSelectionForeground(), hyperlink.getForeground()); } /** * Issue #842-swingx: HyperlinkProvider getString doesn't serve its contract. * */ @Test public void testHyperlinkStringValue() { AbstractHyperlinkAction linkAction = new AbstractHyperlinkAction() { public void actionPerformed(ActionEvent e) { // nothing } @Override protected void installTarget() { setName("pref" + String.valueOf(target)); } }; HyperlinkProvider provider = new HyperlinkProvider(linkAction, Object.class); Object target = null; assertEquals("pref" + String.valueOf(target), provider.getString(target)); } /** * Issue ?? swingx: support to configure the auto-unwrap of tree/table/xx/nodes. * * Initial default is true. */ @Test public void testWrappingProviderUnwrapContructor() { LabelProvider delegate = new LabelProvider(); WrappingProvider provider = new WrappingProvider(delegate, false); assertWrappingProviderState(provider, null, null, delegate, false); } /** * Issue ?? swingx: support to configure the auto-unwrap of tree/table/xx/nodes. * * Initial default is true. */ @Test public void testWrappingProviderUserObjectUnwrapInitial() { WrappingProvider provider = new WrappingProvider(); assertEquals(true, provider.getUnwrapUserObject()); } /** * Issue ?? swingx: support to configure the auto-unwrap of tree/table/xx/nodes. * setter sets */ @Test public void testWrappingProviderUserObjectUnwrapSet() { WrappingProvider provider = new WrappingProvider(); boolean unwrap = !provider.getUnwrapUserObject(); provider.setUnwrapUserObject(unwrap); assertEquals(unwrap, provider.getUnwrapUserObject()); } /** * Issue ?? swingx: support to configure the auto-unwrap of tree/table/xx/nodes. * Respect unwrap flag in getString. */ @Test public void testWrappingProviderUserObjectUnwrapRespectString() { StringValue sv = new StringValue() { public String getString(Object value) { if (value instanceof Point) { return "x of Point: " + ((Point) value).x; } return StringValues.TO_STRING.getString(value); } }; CellContext context = new TableCellContext(); Point p = new Point(10, 20); context.replaceValue(new DefaultMutableTreeNode(p)); WrappingProvider provider = new WrappingProvider(sv); provider.setUnwrapUserObject(false); assertEquals("must not unwrap the user object", sv.getString(context.getValue()), provider.getString(context.getValue())); } /** * Issue ?? swingx: support to configure the auto-unwrap of tree/table/xx/nodes. * Respect unwrap flag in configuring a renderer. */ @Test public void testWrappingProviderUserObjectUnwrapRespectRenderer() { StringValue sv = new StringValue() { public String getString(Object value) { if (value instanceof Point) { return "x of Point: " + ((Point) value).x; } return StringValues.TO_STRING.getString(value); } }; CellContext context = new TableCellContext(); Point p = new Point(10, 20); context.replaceValue(new DefaultMutableTreeNode(p)); WrappingProvider provider = new WrappingProvider(sv); provider.setUnwrapUserObject(false); LabelProvider wrappee = (LabelProvider) provider.getWrappee(); // configure provider.getRendererComponent(context); assertEquals("must not unwrap the user object", sv.getString(context.getValue()), wrappee.rendererComponent.getText()); } /** * Issue #790-swingx: rendering comps must not be registered with the tooltip manager. * * Here: TreeTableCellRenderer (the tree used for rendering the hierarchical * column) * */ @Test public void testToolTipManagerTreeTableTreeRenderer() { JXTreeTable treeTable = new JXTreeTable(new ComponentTreeTableModel(new JXPanel())); JComponent label = (JComponent) treeTable.prepareRenderer(treeTable.getCellRenderer(0, 0), 0, 0); String tip = "some tip"; PropertyChangeReport report = new PropertyChangeReport(); label.addPropertyChangeListener(report); label.setToolTipText(tip); TestUtils.assertPropertyChangeEvent(report, JComponent.TOOL_TIP_TEXT_KEY, null, tip); assertToolTipManagerNotRegistered(label); } /** * Issue #790-swingx: rendering comps must not be registered with the * tooltip manager. * * Here: Hyperlink in provider */ @Test public void testToolTipManagerHyperlinkProvider() { AbstractHyperlinkAction linkAction = new AbstractHyperlinkAction() { public void actionPerformed(ActionEvent e) { // do nothing } @Override protected void installTarget() { super.installTarget(); setShortDescription(getName()); } }; HyperlinkProvider provider = new HyperlinkProvider(linkAction, Object.class); CellContext context = new TableCellContext(); context.replaceValue("dummy"); JXHyperlink label = provider.getRendererComponent(context); assertEquals("sanity - tooltip is set to value", "dummy", label .getToolTipText()); assertToolTipManagerNotRegistered(label); } /** * Issue #790-swingx: rendering comps must not be registered with the tooltip manager. * * Here: JRendererCheckBox- */ @Test public void testToolTipManagerRendererCheckBox() { JRendererCheckBox label = new JRendererCheckBox(); assertNull("sanity - no tooltip", label.getToolTipText()); String tip = "some tip"; PropertyChangeReport report = new PropertyChangeReport(); label.addPropertyChangeListener(report); label.setToolTipText(tip); // JRendererCheckBox is optimized to not fire any property changes assertEquals(0, report.getEventCount()); // nevertheless, we want the tip set ;-) assertEquals(tip, label.getToolTipText()); assertToolTipManagerNotRegistered(label); } /** * Issue #790-swingx: rendering comps must not be registered with the tooltip manager. * * Here: JRendererLabel. * */ @Test public void testToolTipManagerRendererLabel() { JRendererLabel label = new JRendererLabel(); assertNull("sanity - no tooltip", label.getToolTipText()); String tip = "some tip"; PropertyChangeReport report = new PropertyChangeReport(); label.addPropertyChangeListener(report); label.setToolTipText(tip); // JRendererLabel is optimized to not fire any property changes assertEquals(0, report.getEventCount()); // nevertheless, we want the tip set ;-) assertEquals(tip, label.getToolTipText()); assertToolTipManagerNotRegistered(label); } /** * Issue #790-swingx: rendering comps must not be registered with the tooltip manager. * * Sanity: cross-check the "normal" effect of setToolTipText which is that the * ToolTipManager registers itself as mouseListener with the component. * */ @Test public void testToolTipManagerJLabel() { JLabel label = new JLabel(); assertNull("sanity - no tooltip", label.getToolTipText()); String tip = "some tip"; PropertyChangeReport report = new PropertyChangeReport(); label.addPropertyChangeListener(report); label.setToolTipText(tip); TestUtils.assertPropertyChangeEvent(report, JComponent.TOOL_TIP_TEXT_KEY, null, tip); assertToolTipManagerRegistered(label); } /** * Asserts that the component is not registered with the ToolTipManager. * There's no direct api to check, so we loop through the mouseListeners and * assert that none of them is a ToolTipManager.

* * This is inherently unsafe, as we rely on the implementation detail that * the manager registers itself as listener (instead of delegating). That's why * we cross-check a "normal" component's behaviour - if that fails one day, the * implementation detail changed. * * @param label the component to assert. */ private void assertToolTipManagerNotRegistered(JComponent label) { MouseListener[] listeners = label.getMouseListeners(); for (MouseListener l : listeners) { assertEquals("registered with tooltipManager", false, l instanceof ToolTipManager); } } /** * Asserts that the component is registered with the ToolTipManager. * There's no direct api to check, so we loop through the mouseListeners and * assert that none of them is a ToolTipManager.

* * This is inherently unsafe, as we rely on the implementation detail that * the manager registers itself as listener (instead of delegating). That's why * we cross-check a "normal" component's behaviour - if that fails one day, the * implementation detail changed. * * @param label the component to assert. */ private void assertToolTipManagerRegistered(JComponent label) { MouseListener[] listeners = label.getMouseListeners(); int managerCount = 0; for (MouseListener l : listeners) { if (l instanceof ToolTipManager) { managerCount++; } } assertEquals("registered with tooltipManager", 1, managerCount); } /** * Issue #768-swingx: cleanup access to string representation of provider. * */ @Test public void testLabelProviderGetString() { StringValue sv = new StringValue() { public String getString(Object value) { return "funnyconstant ... haha"; } }; CellContext context = new TableCellContext(); ComponentProvider provider = new LabelProvider(sv); JLabel label = provider.getRendererComponent(context); assertEquals(sv.getString(context.getValue()), label.getText()); assertEquals(sv.getString(context.getValue()), provider.getString(context.getValue())); } /** * Issue #768-swingx: cleanup access to string representation of provider. * */ @Test public void testButtonProviderGetString() { StringValue sv = new StringValue() { public String getString(Object value) { return "funnyconstant ... haha"; } }; CellContext context = new TableCellContext(); ComponentProvider provider = new CheckBoxProvider(sv); AbstractButton label = provider.getRendererComponent(context); assertEquals(sv.getString(context.getValue()), label.getText()); assertEquals(sv.getString(context.getValue()), provider.getString(context.getValue())); } /** * Issue #768-swingx: cleanup access to string representation of provider. * */ @Test public void testWrappingProviderGetString() { StringValue sv = new StringValue() { public String getString(Object value) { return "funnyconstant ... haha"; } }; CellContext context = new TableCellContext(); ComponentProvider provider = new WrappingProvider(sv); assertEquals(sv.getString(context.getValue()), provider.getString(context.getValue())); } /** * Issue #768-swingx: cleanup access to string representation of provider. * * WrappingProvider must do the same "unwrapping" magic in getString as in * getRendereringComponent. */ @Test public void testWrappingProviderGetStringFromNode() { StringValue sv = new StringValue() { public String getString(Object value) { if (value instanceof Point) { return "x of Point: " + ((Point) value).x; } return StringValues.TO_STRING.getString(value); } }; CellContext context = new TableCellContext(); Point p = new Point(10, 20); context.value = new DefaultMutableTreeNode(p); WrappingProvider provider = new WrappingProvider(sv); assertEquals(sv.getString(p), provider.getString(context.getValue())); } /** * Issue #768-swingx: cleanup access to string representation of provider. * */ @Test public void testWrappingProviderGetStringNotNullValue() { StringValue sv = new StringValue() { public String getString(Object value) { return String.valueOf(value) + "added ... "; } }; CellContext context = new TableCellContext(); context.value = "dummy"; ComponentProvider provider = new WrappingProvider(sv); assertEquals(sv.getString(context.getValue()), provider.getString(context.getValue())); } /** * Issue #769-swingx: support null icons. * * enhance WrappingProvider to allow real null values. * */ @Test public void testWrappingProviderNullIcon() { CellContext context = new TreeCellContext(); WrappingProvider provider = new WrappingProvider(IconValues.NONE); WrappingIconPanel comp = provider.getRendererComponent(context); assertEquals(null, comp.getIcon()); } /** * Added pref/min/max size to list of properties which * must be reset by the DefaultVisuals. */ @Test public void testResetPreferredSize() { DefaultVisuals visuals = new DefaultVisuals(); JComponent label = new JLabel("somevalue"); visuals.configureVisuals(label, new TableCellContext()); Dimension prefSize = label.getPreferredSize(); Dimension newPrefSize = new Dimension(prefSize.width + 100, prefSize.height + 100); label.setPreferredSize(newPrefSize); visuals.configureVisuals(label, new TableCellContext()); assertEquals("default visual config must reset prefSize", prefSize, label.getPreferredSize()); } /** * Test provider respect converter. * * Here: must show the * description instead of setting the icon. * * PENDING JW: revisit .. Icon.EMPTY vs. Icon.NONE: what exactly is the expected * behaviour? */ @Test public void testLabelProviderRespectStringValueNoIcon() { ImageIcon icon = (ImageIcon) XTestUtils.loadDefaultIcon(); icon.setDescription("description"); LabelProvider provider = new LabelProvider( new MappedValue(StringValues.TO_STRING, IconValues.NONE)); TableCellContext context = new TableCellContext(); context.value = icon; JLabel label = provider.getRendererComponent(context); Icon i = label.getIcon(); assertTrue("icon must be empty", i instanceof EmptyIcon); assertEquals("icon must have no width", 0, i.getIconWidth()); assertEquals("icon must have no height", 0, i.getIconHeight()); assertEquals("label text must be default to-string", StringValues.TO_STRING.getString(icon), label.getText()); } /** * Test provider respect converter. * * Here: must show the icon and empty text. * */ @Test public void testLabelProviderRespectIconValueNoString() { ImageIcon icon = (ImageIcon) XTestUtils.loadDefaultIcon(); icon.setDescription("description"); LabelProvider provider = new LabelProvider( new MappedValue(StringValues.EMPTY, IconValues.ICON)); TableCellContext context = new TableCellContext(); context.value = icon; JLabel label = provider.getRendererComponent(context); assertEquals(icon, label.getIcon()); assertEquals("label text must be empty", StringValues.EMPTY.getString(icon), label.getText()); } /** * Test provider respect converter. * * Here: must show both description and icon. * */ @Test public void testLabelProviderRespectStringIconValueBoth() { ImageIcon icon = (ImageIcon) XTestUtils.loadDefaultIcon(); icon.setDescription("description"); LabelProvider provider = new LabelProvider( new MappedValue(StringValues.TO_STRING, IconValues.ICON)); TableCellContext context = new TableCellContext(); context.value = icon; JLabel label = provider.getRendererComponent(context); assertEquals(icon, label.getIcon()); assertEquals(StringValues.TO_STRING.getString(icon), label.getText()); } /** * WrappingProvider: test custom icon */ @Test public void testWrappingProviderIcon() { final Icon icon = XTestUtils.loadDefaultIcon(); IconValue iv = new IconValue() { public Icon getIcon(Object value) { return icon; }}; WrappingProvider provider = new WrappingProvider(iv); CellContext context = new TreeCellContext(); WrappingIconPanel iconPanel = provider.getRendererComponent(context); assertEquals(icon, iconPanel.getIcon()); // NOTE: do not test type of wrapper's stringValue - it's a mappedValue if icon present! assertEquals("", provider.getStringValue().getString(icon)); } /** * WrappingProvider: test custom icon */ @Test public void testWrappingProviderIconAndContent() { final Icon icon = XTestUtils.loadDefaultIcon(); IconValue iv = new IconValue() { public Icon getIcon(Object value) { return icon; }}; WrappingProvider provider = new WrappingProvider(iv, StringValues.DATE_TO_STRING); CellContext context = new TreeCellContext(); WrappingIconPanel iconPanel = provider.getRendererComponent(context); assertEquals(icon, iconPanel.getIcon()); // NOTE: do not test type of wrapper's stringValue - it's a mappedValue if icon present! assertEquals("", provider.getStringValue().getString(icon)); } /** * WrappingProvider: * test wrappee and its state after instantiation. */ @Test public void testWrappingProviderWrappeeConstructors() { IconValue iv = IconValues.FILE_ICON; LabelProvider delegate = new LabelProvider(StringValues.DATE_TO_STRING); assertWrappingProviderState(new WrappingProvider(delegate), null, null, delegate, true); assertWrappingProviderState(new WrappingProvider(delegate, false), null, null, delegate, false); assertWrappingProviderState(new WrappingProvider(iv, delegate, false), iv, null, delegate, false); assertWrappingProviderState(new WrappingProvider(iv, (ComponentProvider) null, false), iv, null, null, false); assertWrappingProviderState(new WrappingProvider(null, (ComponentProvider) null, false), null, null, null, false); } /** * WrappingProvider: * test wrappee and its state after instantiation. */ @Test public void testWrappingProviderWrappeeStringValueConstructors() { IconValue iv = IconValues.FILE_ICON; StringValue sv = StringValues.DATE_TO_STRING; assertWrappingProviderState(new WrappingProvider(iv), iv, null, null, true); assertWrappingProviderState(new WrappingProvider(iv, sv), iv, sv, null, true); assertWrappingProviderState(new WrappingProvider(sv), null, sv, null, true); assertWrappingProviderState(new WrappingProvider(null, sv), null, sv, null, true); assertWrappingProviderState(new WrappingProvider(iv, null), iv, null, null, true); assertWrappingProviderState(new WrappingProvider(null, null), null, null, null, true); // assertWrappingProviderState(new WrappingProvider(false, iv), // iv, null, null, false); } /** * WrappingProvider: * test provider's state after instantiation with empty constructor. */ @Test public void testWrappingProviderEmptyConstructor() { assertWrappingProviderState(new WrappingProvider(), null, null, null, true); // assertWrappingProviderState(new WrappingProvider(false), // null, null, null, false); } private void assertWrappingProviderState(WrappingProvider provider, IconValue iv, StringValue sv, ComponentProvider delegate, boolean unwrap) { if (iv == null) { assertEquals("default StringValue must be empty", StringValues.EMPTY, provider.getStringValue()); } else { assertTrue("provider's StringValue must be a MappedValue containing the IconValue, but" + "was " + provider.getStringValue().getClass(), provider.getStringValue() instanceof MappedValue); // can't access MappedValue's delegates - usually don't need to // assertEquals(iv, ((MappedValue) provider.getStringValue()).iconDelegate); } if (delegate == null) { assertTrue("default wrappee must be LabelProvider but was " + provider.getWrappee().getClass(), provider.getWrappee() instanceof LabelProvider); } else { assertEquals("wrappee must be set", delegate, provider.getWrappee()); } if (sv != null) { assertEquals("wrappee's StringValue must be configured to given", sv, provider.getWrappee().getStringValue()); } assertEquals(unwrap, provider.getUnwrapUserObject()); } /** * Test text and boolean taken from MappedValue */ @Test public void testButtonProviderCustomValue() { // some object to map String identifier = "dummyID"; final TableColumnExt column = new TableColumnExt(); column.setTitle(identifier); BooleanValue bv = new BooleanValue(){ public boolean getBoolean(Object value) { return column.isVisible(); } }; StringValue sv = new StringValue() { public String getString(Object value) { return column.getTitle(); } }; CheckBoxProvider provider = new CheckBoxProvider(new MappedValue(sv, null, bv)); TableCellContext context = new TableCellContext(); context.value = column; AbstractButton button = provider.getRendererComponent(context); assertEquals(column.isVisible(), button.isSelected()); assertEquals(column.getTitle(), button.getText()); } /** * safety net for addition of BooleanValue. Defaults to * selected from boolean value, text empty. * * here: constructor with null stringValue and align * */ @Test public void testButtonProviderDefaultsTwoConstructor() { CheckBoxProvider provider = new CheckBoxProvider(null, JLabel.RIGHT); TableCellContext context = new TableCellContext(); AbstractButton button = provider.getRendererComponent(context); // empty context assertFalse(button.isSelected()); assertEquals("", button.getText()); // boolean true context.value = true; provider.getRendererComponent(context); assertEquals(context.value, button.isSelected()); assertEquals("", button.getText()); // non-boolean context.value = "dummy"; provider.getRendererComponent(context); assertFalse(button.isSelected()); assertEquals("", button.getText()); } /** * safety net for addition of BooleanValue. Defaults to * selected from boolean value, text empty. * * here: constructor with null stringValue * */ @Test public void testButtonProviderDefaultsOneConstructor() { CheckBoxProvider provider = new CheckBoxProvider(null); TableCellContext context = new TableCellContext(); AbstractButton button = provider.getRendererComponent(context); // empty context assertFalse(button.isSelected()); assertEquals("", button.getText()); // boolean true context.value = true; provider.getRendererComponent(context); assertEquals(context.value, button.isSelected()); assertEquals("", button.getText()); // non-boolean context.value = "dummy"; provider.getRendererComponent(context); assertFalse(button.isSelected()); assertEquals("", button.getText()); } /** * safety net for addition of BooleanValue. Defaults to * selected from boolean value, text empty. * * here: parameterless constructor * */ @Test public void testButtonProviderDefaultsEmptyConstructor() { CheckBoxProvider provider = new CheckBoxProvider(); TableCellContext context = new TableCellContext(); AbstractButton button = provider.getRendererComponent(context); // empty context assertFalse(button.isSelected()); assertEquals("", button.getText()); // boolean true context.value = true; provider.getRendererComponent(context); assertEquals(context.value, button.isSelected()); assertEquals("", button.getText()); // non-boolean context.value = "dummy"; provider.getRendererComponent(context); assertFalse(button.isSelected()); assertEquals("", button.getText()); } /** * test ButtonProvider default constructor and properties. * */ @Test public void testButtonProviderConstructor() { ComponentProvider provider = new CheckBoxProvider(); assertEquals(JLabel.CENTER, provider.getHorizontalAlignment()); assertEquals(StringValues.EMPTY, provider.getStringValue()); } /** * Test provider property reset: borderPainted. * */ @Test public void testButtonProviderBorderPainted() { CheckBoxProvider provider = new CheckBoxProvider(); TableCellContext context = new TableCellContext(); AbstractButton button = provider.getRendererComponent(context); assertEquals(provider.isBorderPainted(), button.isBorderPainted()); button.setBorderPainted(!provider.isBorderPainted()); provider.getRendererComponent(context); assertEquals(provider.isBorderPainted(), button.isBorderPainted()); } /** * Test provider property reset: horizontal. * */ @Test public void testButtonProviderHorizontalAlignment() { CheckBoxProvider provider = new CheckBoxProvider(); CellContext context = new TableCellContext(); AbstractButton button = provider.getRendererComponent(context); assertEquals(provider.getHorizontalAlignment(), button.getHorizontalAlignment()); button.setHorizontalAlignment(JLabel.TRAILING); provider.getRendererComponent(context); assertEquals(provider.getHorizontalAlignment(), button.getHorizontalAlignment()); } /** * use convenience constructor where appropriate: * test clients code (default renderers in JXTable). * * */ @Test public void testConstructorClients() { JXTable table = new JXTable(); // Number DefaultTableRenderer numberRenderer = (DefaultTableRenderer) table.getDefaultRenderer(Number.class); JLabel label = (JLabel) numberRenderer.getTableCellRendererComponent(table, null, false, false, 0, 0); assertEquals(JLabel.RIGHT, label.getHorizontalAlignment()); assertEquals(StringValues.NUMBER_TO_STRING, numberRenderer.componentController.getStringValue()); // icon DefaultTableRenderer iconRenderer = (DefaultTableRenderer) table.getDefaultRenderer(Icon.class); JLabel iconLabel = (JLabel) iconRenderer.getTableCellRendererComponent(table, null, false, false, 0, 0); assertEquals(JLabel.CENTER, iconLabel.getHorizontalAlignment()); // JW: wrong assumption after starting to fix #590-swingx // LabelProvider should respect formatter // assertEquals(StringValue.TO_STRING, iconRenderer.componentController.getToStringConverter()); } /** * Test constructors: convenience constructor. */ @Test public void testConstructorConvenience() { FormatStringValue sv = new FormatStringValue(DateFormat.getTimeInstance()); int align = JLabel.RIGHT; LabelProvider provider = new LabelProvider(sv, align); assertEquals(align, provider.getHorizontalAlignment()); assertEquals(sv, provider.getStringValue()); } /** * Test constructors: parameterless. */ @Test public void testConstructorDefault() { LabelProvider provider = new LabelProvider(); assertEquals(JLabel.LEADING, provider.getHorizontalAlignment()); assertEquals(StringValues.TO_STRING, provider.getStringValue()); } /** * Test constructors: convenience constructor. */ @Test public void testConstructorAlignment() { int align = JLabel.RIGHT; LabelProvider provider = new LabelProvider(align); assertEquals(align, provider.getHorizontalAlignment()); assertEquals(StringValues.TO_STRING, provider.getStringValue()); } /** * Test constructors: convenience constructor. */ @Test public void testConstructorStringValue() { FormatStringValue sv = new FormatStringValue(DateFormat.getTimeInstance()); LabelProvider provider = new LabelProvider(sv); assertEquals(JLabel.LEADING, provider.getHorizontalAlignment()); assertEquals(sv, provider.getStringValue()); } /** * test that default visual config clears the tooltip. * */ @Test public void testResetTooltip() { DefaultVisuals visuals = new DefaultVisuals(); JComponent label = new JLabel("somevalue"); label.setToolTipText("tooltip"); visuals.configureVisuals(label, new TableCellContext()); assertNull("default visual config must clear tooltiptext", label.getToolTipText()); } /** * Test if all collaborators can cope with null component on CellContext. * */ @Test public void testEmptyContext() { // test LabelProvider // same for list and table assertEmptyContext(new LabelProvider()); assertEmptyContext(new CheckBoxProvider()); assertEmptyContext(new HyperlinkProvider()); } private void assertEmptyContext(ComponentProvider provider) { DefaultListRenderer renderer = new DefaultListRenderer(provider); renderer.getListCellRendererComponent(null, null, -1, false, false); // treeRenderer - use the same provider, can't do in real life, // the providers component is added to the wrapping provider's component. DefaultTreeRenderer treeRenderer = new DefaultTreeRenderer(provider); treeRenderer.getTreeCellRendererComponent(null, null, false, false, false, -1, false); // had an NPE in TreeCellContext focus border treeRenderer.getTreeCellRendererComponent(null, null, false, false, false, -1, true); // random test - the input parameters don't map to a legal state treeRenderer.getTreeCellRendererComponent(null, new Object(), false, true, false, 2, true); } /** * Test doc'ed constructor behaviour of default tree renderer. * */ @Test public void testDefaultTreeRendererConstructors() { DefaultTreeRenderer renderer = new DefaultTreeRenderer(); assertTrue(renderer.componentController instanceof WrappingProvider); renderer = new DefaultTreeRenderer(StringValues.DATE_TO_STRING); assertTrue(renderer.componentController instanceof WrappingProvider); // wrong assumption - we are wrapping... // assertSame(FormatStringValue.DATE_TO_STRING, renderer.componentController.formatter); assertSame(StringValues.DATE_TO_STRING, ((WrappingProvider) renderer.componentController).wrappee.formatter); ComponentProvider controller = new CheckBoxProvider(); renderer = new DefaultTreeRenderer(controller); assertSame(controller, renderer.componentController); } /** * Test doc'ed constructor behaviour of default list renderer. * */ @Test public void testDefaultListRendererConstructors() { DefaultListRenderer renderer = new DefaultListRenderer(); assertTrue(renderer.componentController instanceof LabelProvider); renderer = new DefaultListRenderer(StringValues.DATE_TO_STRING); assertTrue(renderer.componentController instanceof LabelProvider); assertSame(StringValues.DATE_TO_STRING, renderer.componentController.formatter); ComponentProvider controller = new CheckBoxProvider(); renderer = new DefaultListRenderer(controller); assertSame(controller, renderer.componentController); } /** * Issue 970-swingx: add convenience constructors with IconValues * Test doc'ed constructor behaviour of default list renderer. * */ @Test public void testDefaultListRendererConstructorWithIconValue() { DefaultListRenderer renderer = new DefaultListRenderer(StringValues.TO_STRING, IconValues.ICON); assertTrue(renderer.componentController instanceof LabelProvider); LabelProvider provider = (LabelProvider) renderer.componentController; ImageIcon icon = (ImageIcon) XTestUtils.loadDefaultIcon(); icon.setDescription("description"); TableCellContext context = new TableCellContext(); context.value = icon; JLabel label = provider.getRendererComponent(context); assertEquals(icon, label.getIcon()); assertEquals(StringValues.TO_STRING.getString(icon), label.getText()); } /** * Issue #970-swingx: add convenience constructors with IconValues * Test doc'ed constructor behaviour of default list renderer. * */ @Test public void testDefaultListRendererConstructorWithIconValueAndAlign() { DefaultListRenderer renderer = new DefaultListRenderer(StringValues.TO_STRING, IconValues.ICON, JLabel.TRAILING); assertTrue(renderer.componentController instanceof LabelProvider); LabelProvider provider = (LabelProvider) renderer.componentController; ImageIcon icon = (ImageIcon) XTestUtils.loadDefaultIcon(); icon.setDescription("description"); TableCellContext context = new TableCellContext(); context.value = icon; JLabel label = provider.getRendererComponent(context); assertEquals(icon, label.getIcon()); assertEquals(StringValues.TO_STRING.getString(icon), label.getText()); assertEquals(JLabel.TRAILING, label.getHorizontalAlignment()); } /** * Test doc'ed constructor behaviour of default table renderer. * */ @Test public void testDefaultTableRendererConstructors() { DefaultTableRenderer renderer = new DefaultTableRenderer(); assertTrue(renderer.componentController instanceof LabelProvider); renderer = new DefaultTableRenderer(StringValues.DATE_TO_STRING); assertTrue(renderer.componentController instanceof LabelProvider); assertSame(StringValues.DATE_TO_STRING, renderer.componentController.formatter); ComponentProvider controller = new CheckBoxProvider(); renderer = new DefaultTableRenderer(controller); assertSame(controller, renderer.componentController); } /** * Issue #970-swingx: text constructors with IconValues * Test doc'ed constructor behaviour of default table renderer. * */ @Test public void testDefaultTableRendererConstructorWithIconValue() { DefaultTableRenderer renderer = new DefaultTableRenderer(StringValues.TO_STRING, IconValues.ICON); assertTrue(renderer.componentController instanceof LabelProvider); LabelProvider provider = (LabelProvider) renderer.componentController; ImageIcon icon = (ImageIcon) XTestUtils.loadDefaultIcon(); icon.setDescription("description"); TableCellContext context = new TableCellContext(); context.value = icon; JLabel label = provider.getRendererComponent(context); assertEquals(icon, label.getIcon()); assertEquals(StringValues.TO_STRING.getString(icon), label.getText()); } /** * Issue #970-swingx: text constructors with IconValues * Test doc'ed constructor behaviour of default table renderer. * */ @Test public void testDefaultTableRendererConstructorWithIconValueAndAlign() { DefaultTableRenderer renderer = new DefaultTableRenderer(StringValues.TO_STRING, IconValues.ICON, JLabel.TRAILING); assertTrue(renderer.componentController instanceof LabelProvider); LabelProvider provider = (LabelProvider) renderer.componentController; ImageIcon icon = (ImageIcon) XTestUtils.loadDefaultIcon(); icon.setDescription("description"); TableCellContext context = new TableCellContext(); context.value = icon; JLabel label = provider.getRendererComponent(context); assertEquals(icon, label.getIcon()); assertEquals(StringValues.TO_STRING.getString(icon), label.getText()); assertEquals(JLabel.TRAILING, label.getHorizontalAlignment()); } /** * public methods of ComponentProvider must cope * with null context. Here: test getRenderingComponent in WrappingProvider. * */ @Test public void testGetWrappingComponentNullContext() { WrappingProvider provider = new WrappingProvider(); assertEquals(provider.rendererComponent, provider.getRendererComponent(null)); } /** * public methods of ComponentProvider must cope * with null context. Here: test getRenderingComponent in LabelProvider. */ @Test public void testGetComponentNullContext() { ComponentProvider controller = new LabelProvider(); assertEquals(controller.rendererComponent, controller.getRendererComponent(null)); } /** * test doc'ed behaviour on defaultVisuals configure: * NPE on null context. * */ @Test public void testConfigureVisualsNullContext() { DefaultVisuals controller = new DefaultVisuals(); try { controller.configureVisuals(new JLabel(), null); fail("renderer controller must throw NPE on null context"); } catch (NullPointerException e) { // this is what we expect } catch (Exception e) { fail("renderer controller must throw NPE on null context - instead: " + e); } } /** * test doc'ed behaviour on defaultVisuals configure: * NPE on null component. * */ @Test public void testConfigureVisualsNullComponent() { DefaultVisuals controller = new DefaultVisuals(); try { controller.configureVisuals(null, new TableCellContext()); fail("renderer controller must throw NPE on null component"); } catch (NullPointerException e) { // this is what we expect } catch (Exception e) { fail("renderer controller must throw NPE on null component - instead: " + e); } } /** * RendererLabel NPE with null Graphics. * Fail-fast NPE in label.paintComponentWithPainter. * */ @Test public void testLabelNPEPaintComponentOpaqueWithPainter() { JRendererLabel label = new JRendererLabel(); label.setOpaque(true); label.setPainter(new ShapePainter()); try { label.paintComponent(null); fail("invoke paintComponent with null graphics must throw NPE"); } catch (NullPointerException e) { // basically the right thing - but how to test the fail-fast? } catch (Exception e) { fail("unexpected exception invoke paintcomponent with null" + e); } } /** * RendererLabel NPE with null Graphics. * Fail-fast NPE in paintPainter. * */ @Test public void testLabelNPEPaintComponentWithPainter() { JRendererLabel label = new JRendererLabel(); label.setOpaque(false); label.setPainter(new ShapePainter()); try { label.paintComponent(null); fail("invoke paintComponent with null graphics must throw NPE"); } catch (NullPointerException e) { // basically the right thing - but how to test the fail-fast? } catch (Exception e) { fail("unexpected exception invoke paintcomponent with null" + e); } } /** * RendererLabel NPE with null Graphics. * NPE in label.paintComponentWithPainter finally block. * */ @Test public void testButtonNPEPaintComponentOpaqueWithPainter() { JRendererCheckBox checkBox = new JRendererCheckBox(); checkBox.setOpaque(true); checkBox.setPainter(new ShapePainter()); try { checkBox.paintComponent(null); fail("invoke paintComponent with null graphics must throw NPE"); } catch (NullPointerException e) { // basically the right thing - but how to test the fail-fast? } catch (Exception e) { fail("unexpected exception invoke paintcomponent with null" + e); } } /** * RendererCheckBox NPE with null Graphics. NPE in * label.paintComponentWithPainter finally block. * */ @Test public void testButtonNPEPaintComponentWithPainter() { JRendererCheckBox checkBox = new JRendererCheckBox(); checkBox.setOpaque(false); checkBox.setPainter(new ShapePainter()); try { checkBox.paintComponent(null); fail("invoke paintComponent with null graphics must throw NPE"); } catch (NullPointerException e) { // basically the right thing - but how to test the fail-fast? } catch (Exception e) { fail("unexpected exception invoke paintcomponent with null" + e); } } } swingx-1.0-src/src/test/org/jdesktop/swingx/renderer/DNDRendererVisualCheck.java0000644000175000017500000001417611210401722026607 0ustar tonytony/* * Created on 26.06.2008 * */ package org.jdesktop.swingx.renderer; import java.awt.Component; import java.awt.datatransfer.DataFlavor; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.TransferHandler; import javax.swing.table.TableCellRenderer; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTree; import org.jdesktop.swingx.JXTreeTable; import org.jdesktop.swingx.renderer.DefaultTableRenderer; import org.jdesktop.swingx.renderer.DefaultTreeRenderer; import org.jdesktop.swingx.renderer.HyperlinkProvider; import org.jdesktop.swingx.renderer.WrappingProvider; import org.jdesktop.swingx.test.ComponentTreeTableModel; import org.jdesktop.test.AncientSwingTeam; /** * * * @author Jeanette Winzenburg */ public class DNDRendererVisualCheck extends InteractiveTestCase { public static void main(String[] args) { DNDRendererVisualCheck test = new DNDRendererVisualCheck(); try { test.runInteractiveTests(); } catch (Exception e) { e.printStackTrace(); } } /** * Issue #766-swingx: drop image is blinking over hierarchical column. * * Core bug: #6700748 * * Hacks around, use one or other: * - the usual performance optimization (override validate etc to do nothing) * - rendering component return false on isVisible */ public void interactiveDropOnHierachicalColumnBlinks() { JXTreeTable xTable = new JXTreeTable(new ComponentTreeTableModel( new JXFrame())); installTransferHandler(xTable); xTable.putClientProperty(JXTreeTable.DROP_HACK_FLAG_KEY, Boolean.TRUE); xTable.expandAll(); xTable.setVisibleColumnCount(10); JXFrame frame = wrapWithScrollingInFrame(xTable, "TreeTable hierarchical: blink on drop over?"); JTextField textField = new JTextField( "drag me over hierarchical column .."); textField.setDragEnabled(true); addStatusComponent(frame, textField); frame.setVisible(true); } /** * Issue #766-swingx: drop image is blinking over hierarchical column. * * Check WrappingIconPanel in tree: blinking. Can't override the validate * because it's needed to layout the component correctly. */ public void interactiveDropOnWrappingIconPanelTree() { JXTree xTable = new JXTree(new ComponentTreeTableModel(new JXFrame())); installTransferHandler(xTable); xTable.setCellRenderer(new DefaultTreeRenderer()); xTable.expandAll(); JXFrame frame = wrapWithScrollingInFrame(xTable, "Wrapping renderer: blink on drop over?"); JTextField textField = new JTextField("drag me over tree ...."); textField.setDragEnabled(true); addStatusComponent(frame, textField); frame.setVisible(true); } /** * Issue #766-swingx: drop image is blinking over hierarchical column. * * Check Hyperlink in Table: okay, because it has the validate et al methods * overridden to do nothing. */ public void interactiveDropOnHyperlinkTableBlinks() { JXTable xTable = new JXTable(new AncientSwingTeam()); installTransferHandler(xTable); xTable.getColumn(0).setCellRenderer( new DefaultTableRenderer(new HyperlinkProvider())); JXFrame frame = wrapWithScrollingInFrame(xTable, "Hyperlink as renderer: blink on drop over?"); JTextField textField = new JTextField("drag me over hyperlink...."); textField.setDragEnabled(true); addStatusComponent(frame, textField); frame.setVisible(true); } /** * Issue #766-swingx: drop image is blinking over hierarchical column. * * Test WrappingIconPanel in Table. */ public void interactiveDropOnWrappingIconPanelTableBlinks() { JXTable xTable = new JXTable(new AncientSwingTeam()); installTransferHandler(xTable); xTable.getColumn(0).setCellRenderer( new DefaultTableRenderer(new WrappingProvider())); JXFrame frame = wrapWithScrollingInFrame(xTable, "WrappingIconPanel as renderer: blink on drop over?"); JTextField textField = new JTextField("drag me over first column...."); textField.setDragEnabled(true); addStatusComponent(frame, textField); frame.setVisible(true); } /** * Issue #766-swingx: drop image is blinking over hierarchical column. * * Check plain JLabel as renderer in Table. */ public void interactiveDropOnPlainLabelTableBlinks() { JXTable xTable = new JXTable(new AncientSwingTeam()); installTransferHandler(xTable); TableCellRenderer renderer = new TableCellRenderer() { JLabel label = new JLabel(); public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { label.setText(String.valueOf(value)); return label; } }; xTable.getColumn(0).setCellRenderer(renderer); JXFrame frame = wrapWithScrollingInFrame(xTable, "Plain label as renderer: blink on drop over?"); JTextField textField = new JTextField("drag me over first column...."); textField.setDragEnabled(true); addStatusComponent(frame, textField); frame.setVisible(true); } private void installTransferHandler(JComponent xTable) { TransferHandler tableTransfer = new TransferHandler() { @Override public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) { return true; } }; xTable.setTransferHandler(tableTransfer); } public void testDummy() { // do nothing - placeholder for empty issues } } swingx-1.0-src/src/test/org/jdesktop/swingx/renderer/RendererIssues.java0000644000175000017500000007024011210401722025325 0ustar tonytony/* * $Id: RendererIssues.java,v 1.31 2009/03/10 12:13:43 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.renderer; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.io.File; import java.util.Calendar; import java.util.Date; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.AbstractButton; import javax.swing.AbstractListModel; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.DefaultListCellRenderer; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.ListCellRenderer; import javax.swing.ListModel; import javax.swing.LookAndFeel; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.border.Border; import javax.swing.filechooser.FileSystemView; import javax.swing.plaf.basic.BasicTreeUI; import javax.swing.table.TableCellRenderer; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreePath; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXButton; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXList; import org.jdesktop.swingx.JXPanel; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTree; import org.jdesktop.swingx.JXTreeTable; import org.jdesktop.swingx.border.DropShadowBorder; import org.jdesktop.swingx.color.ColorUtil; import org.jdesktop.swingx.decorator.ColorHighlighter; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.HighlightPredicate; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.PainterHighlighter; import org.jdesktop.swingx.decorator.PatternPredicate; import org.jdesktop.swingx.painter.MattePainter; import org.jdesktop.swingx.rollover.RolloverProducer; import org.jdesktop.swingx.rollover.RolloverRenderer; import org.jdesktop.swingx.test.ComponentTreeTableModel; import org.jdesktop.swingx.test.XTestUtils; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.swingx.treetable.TreeTableModel; import org.jdesktop.test.AncientSwingTeam; import com.sun.java.swing.plaf.motif.MotifLookAndFeel; /** * Test around known issues of SwingX renderers.

* * Ideally, there would be at least one failing test method per open * Issue in the issue tracker. Plus additional failing test methods for * not fully specified or not yet decided upon features/behaviour. * * @author Jeanette Winzenburg */ public class RendererIssues extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(RendererIssues.class .getName()); public static void main(String[] args) { setSystemLF(true); RendererIssues test = new RendererIssues(); try { // test.runInteractiveTests(); test.runInteractiveTests("interactive.*Alpha.*"); // test.runInteractiveTests(".*XLabel.*"); // test.runInteractiveTests(".*Color.*"); // test.runInteractiveTests("interactive.*ColumnControl.*"); // test.runInteractiveTests("interactive.*Hyperlink.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue ??-swingx: Boolean renderer background is slightly darker if * background color is part-transparent. * * Not only checkbox as renderer - there seem to be subtle differences * when painting buttons, labels, ... plus it's laf dependent. * */ public void interactiveAlphaBackground() { Color color = ColorUtil.setAlpha(Color.ORANGE, 60); JCheckBox check = new JCheckBox("what's my color?"); // check.setOpaque(true); // check.setContentAreaFilled(true); check.setBackground(color); JLabel label = new JLabel("and mine?"); label.setOpaque(true); label.setBackground(color ); JButton button = new JButton("the new kid on the block"); button.setBackground(color); JRadioButton radio = new JRadioButton("radio, raadio .."); radio.setBackground(color); JTextField field = new JTextField(40); field.setBackground(color); JComponent box = Box.createVerticalBox(); box.setOpaque(true); box.setBackground(Color.WHITE); box.add(check); box.add(radio); box.add(label); box.add(button); box.add(field); JXFrame frame = wrapInFrame(box, "alpha in plain ..", true); show(frame, 400, 200); } /** * Issue ??-swingx: Boolean renderer background is slightly darker if * background color is part-transparent. * */ public void interactiveCheckBoxAlpha() { JXTable table = new JXTable(new org.jdesktop.test.AncientSwingTeam()); table.addHighlighter(new RowHighlighter(new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { return ((Boolean) adapter.getValue(4)).booleanValue(); } })); showWithScrollingInFrame(table, "boolean renderer and alpha background"); } static class RowHighlighter extends ColorHighlighter { Font BOLD_FONT; RowHighlighter(HighlightPredicate predicate) { super(predicate, ColorUtil.setAlpha(Color.ORANGE, 60), Color.RED); setSelectedForeground(getForeground()); } @Override protected Component doHighlight(Component renderer, ComponentAdapter adapter) { if (BOLD_FONT == null) { BOLD_FONT = renderer.getFont().deriveFont(Font.BOLD); } renderer.setFont(BOLD_FONT); return super.doHighlight(renderer, adapter); } } /** * example to configure treeTable hierarchical column with * custom icon and content mapping. The nodes are actually of type File. * * Problem: * painting on resizing tree column sluggish, especially if the PatternHighlighter * is on. Reason seems to be the FileSystemView - prepare time increases with * number of accesses. */ public void interactiveTreeTableCustomIconsPerformance() { // modify the file model to return the file itself for the hierarchical column TreeTableModel model = new FileSystemModel() { @Override public Object getValueAt(Object node, int column) { if (column == 0) { return node; } return super.getValueAt(node, column); } }; final JXTreeTable table = new JXTreeTable(model); table.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF); StringValue sv = new StringValue() { public String getString(Object value) { if (value instanceof File) { return FileSystemView.getFileSystemView().getSystemDisplayName((File) value) + " Type: " + FileSystemView.getFileSystemView().getSystemTypeDescription((File) value) ; } return StringValues.TO_STRING.getString(value); } }; IconValue iv = new IconValue() { public Icon getIcon(Object value) { if (value instanceof File) { return FileSystemView.getFileSystemView().getSystemIcon((File) value); } return null; }}; final DefaultTreeRenderer treeRenderer = new DefaultTreeRenderer(iv, sv); table.setTreeCellRenderer(treeRenderer); // string based. Note: this example is locale dependent String folderDescription = ".*ordner.*"; PatternPredicate predicate = new PatternPredicate(folderDescription, 0, -1); final Highlighter hl = new ColorHighlighter(predicate, null, Color.RED); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.YEAR, -1); final Date lastYear = calendar.getTime(); // install value based highlighter HighlightPredicate valueBased = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { if (!(adapter.getValue() instanceof File)) return false; File file = (File) adapter.getValue(); Date date = new Date(file.lastModified()); return date.after(lastYear); } }; final ColorHighlighter back = new ColorHighlighter(valueBased, Color.YELLOW, null); JXFrame frame =showWithScrollingInFrame(table, "TreeTable: performance bottleneck is FileSystemView"); Action toggleBack = new AbstractAction("toggleBackHighlighter") { boolean hasBack; public void actionPerformed(ActionEvent e) { if (hasBack) { table.removeHighlighter(back); } else { table.addHighlighter(back); } hasBack = !hasBack; } }; addAction(frame, toggleBack); Action togglePattern = new AbstractAction("togglePatternHighlighter") { boolean hasBack; public void actionPerformed(ActionEvent e) { if (hasBack) { table.removeHighlighter(hl); } else { table.addHighlighter(hl); } hasBack = !hasBack; } }; addAction(frame, togglePattern); // accessing the FileSystemView is slooooww // increasingly costly over time, shows particularly // when the patternHighlighter is on // (probably because that increases the number // of queries to the systemView final JLabel timeL = new JLabel("stop-watch"); Action timer = new AbstractAction("start") { public void actionPerformed(ActionEvent e) { timeL.setText("started"); long time = System.currentTimeMillis(); for (int i = 0; i < 2000; i++) { table.prepareRenderer(table.getCellRenderer(0, 0), 0, 0); } timeL.setText("stopped: " + (System.currentTimeMillis() - time)); } }; addAction(frame, timer); addStatusComponent(frame, timeL); addStatusMessage(frame, "node is File - string/value based highlighters same"); } /** * Playing with rollover for visual clue if cell editable. * The old problem: cursor shoudn't be altered by the rollover * controller but by the rollover renderer. */ public void interactiveRolloverEffects() { JXTable table = new JXTable(new AncientSwingTeam()); table.setDefaultRenderer(Boolean.class, new DefaultTableRenderer(new RolloverCheckBox())); showWithScrollingInFrame(table, "checkbox rollover effect"); } public static class RolloverCheckBox extends CheckBoxProvider implements RolloverRenderer { boolean wasEditable; @Override protected void configureState(CellContext context) { super.configureState(context); if (context.getComponent() != null) { Point p = (Point) context.getComponent() .getClientProperty(RolloverProducer.ROLLOVER_KEY); if (/*hasFocus || */(p != null && (p.x >= 0) && (p.x == context.getColumn()) && (p.y == context.getRow()))) { rendererComponent.getModel().setRollover(true); } else { rendererComponent.getModel().setRollover(false); } } } @Override protected void format(CellContext context) { // TODO Auto-generated method stub super.format(context); wasEditable = context.isEditable(); } public void doClick() { } public boolean isEnabled() { return wasEditable; } } public void interactiveToolTipList() { final JXTree table = new JXTree(new ComponentTreeTableModel(new JXFrame())); table.expandAll(); // quick model for long values ListModel model = new AbstractListModel() { public Object getElementAt(int index) { return table.getPathForRow(index).getLastPathComponent(); } public int getSize() { return table.getRowCount(); } }; JXList list = new JXList(model) { @Override public String getToolTipText(MouseEvent event) { int row = locationToIndex(event.getPoint()); Rectangle r = getCellBounds(row, row); if (r == null) return super.getToolTipText(event); ListCellRenderer renderer = getCellRenderer(); Component comp = renderer.getListCellRendererComponent(this, getElementAt(row), row, isSelectedIndex(row), false); if (comp.getPreferredSize().width <= getVisibleRect().width) return null; renderer = ((DelegatingRenderer) renderer).getDelegateRenderer(); if (renderer instanceof StringValue) { return ((StringValue) renderer).getString(getElementAt(row)); } return null; } @Override public Point getToolTipLocation(MouseEvent event) { int row = locationToIndex(event.getPoint()); Rectangle r = getCellBounds(row, row); if (r != null) { if (!getComponentOrientation().isLeftToRight()) { r.translate(r.width, 0); } return r.getLocation(); } return super.getToolTipLocation(event); } }; JXFrame frame = wrapWithScrollingInFrame(list, "list tooltip"); addComponentOrientationToggle(frame); show(frame, 300, 300); } public void interactiveToolTipTable() { JXTreeTable treeTable = new JXTreeTable(new ComponentTreeTableModel(new JXFrame())); treeTable.expandAll(); JXTable table = new JXTable(treeTable.getModel()) { @Override public String getToolTipText(MouseEvent event) { int column = columnAtPoint(event.getPoint()); int row = rowAtPoint(event.getPoint()); TableCellRenderer renderer = getCellRenderer(row, column); Component comp = prepareRenderer(renderer, row, column); if (comp.getPreferredSize().width <= getColumn(column).getWidth()) return null; if (renderer instanceof StringValue) { return ((StringValue) renderer).getString(getValueAt(row, column)); } return null; } @Override public Point getToolTipLocation(MouseEvent event) { int column = columnAtPoint(event.getPoint()); int row = rowAtPoint(event.getPoint()); Rectangle cellRect = getCellRect(row, column, false); if (!getComponentOrientation().isLeftToRight()) { cellRect.translate(cellRect.width, 0); } // PENDING JW: otherwise we get a small (borders only) tooltip for null // core issue? Yeh, the logic in tooltipManager is crooked. // but this here is ehem ... rather arbitrary. return getValueAt(row, column) == null ? null : cellRect.getLocation(); // return null; } }; table.setColumnControlVisible(true); JXFrame frame = wrapWithScrollingInFrame(table, "tooltip"); addComponentOrientationToggle(frame); show(frame); } public void interactiveToolTipTree() { ComponentTreeTableModel model = new ComponentTreeTableModel(new JXFrame()); JXTree tree = new JXTree(model) { @Override public String getToolTipText(MouseEvent event) { int row = getRowForLocation(event.getX(), event.getY()); if (row < 0) return null; TreeCellRenderer renderer = getCellRenderer(); TreePath path = getPathForRow(row); Object lastPath = path.getLastPathComponent(); Component comp = renderer.getTreeCellRendererComponent(this, lastPath, isRowSelected(row), isExpanded(row), getModel().isLeaf(lastPath), row, false); int width = getVisibleRect().width; if (comp.getPreferredSize().width <= width ) return null; if (renderer instanceof JXTree.DelegatingRenderer) { renderer = ((JXTree.DelegatingRenderer) renderer).getDelegateRenderer(); if (renderer instanceof StringValue) { return ((StringValue) renderer).getString(lastPath); } } return null; } private int getVisibleWidth() { int width = getVisibleRect().width; int indent = (((BasicTreeUI)getUI()).getLeftChildIndent() + ((BasicTreeUI)getUI()).getRightChildIndent()); return width; } @Override public Point getToolTipLocation(MouseEvent event) { return null; } }; tree.expandAll(); tree.setCellRenderer(new DefaultTreeRenderer()); // I'm registered to do tool tips so we can draw tips for the renderers ToolTipManager toolTipManager = ToolTipManager.sharedInstance(); toolTipManager.registerComponent(tree); JXFrame frame = showWithScrollingInFrame(tree, "tooltip"); addComponentOrientationToggle(frame); show(frame, 400, 400); } /** * PENDING JW: really fancify or remove ;-) */ public void interactiveTreeFancyButton() { JXTree tree = new JXTree(); tree.setRowHeight(30); MattePainter painter = new MattePainter(Color.YELLOW); Highlighter hl = new PainterHighlighter(HighlightPredicate.ROLLOVER_ROW, painter); tree.addHighlighter(hl); ComponentProvider provider = new NormalButtonProvider(StringValues.TO_STRING, JLabel.LEADING); tree.setCellRenderer(new DefaultTreeRenderer(provider)); tree.setRolloverEnabled(true); showWithScrollingInFrame(tree, "Fancy.."); } public void interactiveFancyButton() { JXButton button = new JXButton("Dummy .... but lonnnnnnngg"); button.setBorder(BorderFactory.createCompoundBorder(new DropShadowBorder(), button.getBorder())); JXPanel panel = new JXPanel(); panel.add(button); showInFrame(panel, "Fancy.."); } public static class NormalButtonProvider extends CheckBoxProvider implements RolloverRenderer { private Border border; /** * @param toString * @param leading */ public NormalButtonProvider(StringValue toString, int leading) { super(toString, leading); setBorderPainted(true); } @Override protected void configureState(CellContext context) { super.configureState(context); rendererComponent.setBorder(border); Point p = (Point) context.getComponent().getClientProperty( RolloverProducer.ROLLOVER_KEY); if (/* hasFocus || */(p != null && (p.x >= 0) && (p.x == context.getColumn()) && (p.y == context.getRow()))) { rendererComponent.getModel().setRollover(true); } else { rendererComponent.getModel().setRollover(false); } } @Override protected AbstractButton createRendererComponent() { JXButton button = new JXButton(); border = BorderFactory.createCompoundBorder( new DropShadowBorder(), button.getBorder()); return button; } public void doClick() { // TODO Auto-generated method stub } public boolean isEnabled() { // TODO Auto-generated method stub return true; } } //--------------- unit tests /** * Issue #794-swingx: tooltip must be reset. * * Here: TreeTableCellRenderer (the tree used for rendering the hierarchical * column) * */ public void testToolTipResetTreeTableTreeRenderer() { JXTreeTable treeTable = new JXTreeTable(new ComponentTreeTableModel(new JXPanel())); JComponent label = (JComponent) treeTable.prepareRenderer(treeTable.getCellRenderer(0, 0), 0, 0); String tip = "some tip"; label.setToolTipText(tip); assertEquals("sanity: tooltip must be set", tip, label.getToolTipText()); // prepare again label = (JComponent) treeTable.prepareRenderer(treeTable.getCellRenderer(0, 0), 0, 0); assertEquals("tooltip must be reset in each prepare", null, label.getToolTipText()); } /** * Issue #774-swingx: support per node-type icons. * * postponed to 0.9.x - will break all interface implementors. * */ public void testNodeTypeIcons() { TreeCellContext context = new TreeCellContext(); context.installContext(null, "dummy", -1, -1, false, false, false, true); final Icon custom = XTestUtils.loadDefaultIcon(); IconValue iv = new IconValue() { public Icon getIcon(Object value) { // TODO Auto-generated method stub return custom; } }; WrappingProvider provider = new WrappingProvider(iv); WrappingIconPanel comp = provider.getRendererComponent(context); assertEquals(custom, comp.getIcon()); fail("feature request: per node type iconValue"); } /** * base interaction with list: focused, not-selected uses UI border. * Moved from ListRendererTest: failes on the new server (what's the default LF there?) * TODO: fix and reinstate the test * @throws UnsupportedLookAndFeelException */ public void testListFocusBorder() throws UnsupportedLookAndFeelException { LookAndFeel lf = UIManager.getLookAndFeel(); try { UIManager.setLookAndFeel(new MotifLookAndFeel()); JList list = new JList(new Object[] {1, 2, 3}); ListCellRenderer coreListRenderer = new DefaultListCellRenderer(); ListCellRenderer xListRenderer = new DefaultListRenderer(); // access ui colors Border focusBorder = UIManager.getBorder("List.focusCellHighlightBorder"); // sanity assertNotNull(focusBorder); // JW: this looks suspicious ... // RAH: line below makes hudson fail the test tho it runs fine locally ... assertNotSame(focusBorder, UIManager.getBorder("Table.focusCellHighlightBorder")); // need to prepare directly - focus is true only if list is focusowner JComponent coreComponent = (JComponent) coreListRenderer.getListCellRendererComponent(list, null, 0, false, true); // sanity: known standard behaviour assertEquals(focusBorder, coreComponent.getBorder()); // prepare extended JComponent xComponent = (JComponent) xListRenderer.getListCellRendererComponent(list, null, 0, false, true); // assert behaviour same as standard assertEquals(coreComponent.getBorder(), xComponent.getBorder()); } finally { UIManager.setLookAndFeel(lf); } } /** * test if renderer properties are updated on LF change.

* Note: this can be done examplary only. Here: we use the * font of a rendererComponent returned by a HyperlinkProvider for * comparison. There's nothing to test if the font are equal * in System and crossplattform LF.

* * There are spurious problems when toggling UI (since when?) * with LinkRenderer * "no ComponentUI class for: org.jdesktop.swingx.LinkRenderer$1" * that's the inner class JXHyperlink which overrides updateUI. * * PENDING: this was moved from tableUnitTest - had been passing with * LinkRenderer but with HyperlinkProvider * now is failing (on server with defaultToSystem == false, locally win os * with true), probably due to slightly different setup now * in renderer defaultVisuals? It resets the font to table's which * LinkRenderer didn't. Think whether to change the provider go back * to hyperlink font? */ public void testUpdateRendererOnLFChange() { boolean defaultToSystemLF = true; setSystemLF(defaultToSystemLF); TableCellRenderer comparison = new DefaultTableRenderer(new HyperlinkProvider()); TableCellRenderer linkRenderer = new DefaultTableRenderer(new HyperlinkProvider()); JXTable table = new JXTable(2, 3); Component comparisonComponent = comparison.getTableCellRendererComponent(table, null, false, false, 0, 0); Font comparisonFont = comparisonComponent.getFont(); table.getColumnModel().getColumn(0).setCellRenderer(linkRenderer); setSystemLF(!defaultToSystemLF); SwingUtilities.updateComponentTreeUI(comparisonComponent); if (comparisonFont.equals(comparisonComponent.getFont())) { LOG.info("cannot run test - equal font " + comparisonFont); return; } SwingUtilities.updateComponentTreeUI(table); Component rendererComp = table.prepareRenderer(table.getCellRenderer(0, 0), 0, 0); assertEquals("renderer font must be updated", comparisonComponent.getFont(), rendererComp.getFont()); } /** * RendererLabel NPE with null Graphics. While expected, * the exact location is not. * NPE in JComponent.paintComponent finally block * */ public void testLabelNPEPaintComponentOpaque() { JRendererLabel label = new JRendererLabel(); label.setOpaque(true); label.paintComponent(null); } /** * RendererLabel NPE with null Graphics. While expected, * the exact location is not. * NPE in JComponent.paintComponent finally block * */ public void testLabelNPEPaintComponent() { JRendererLabel label = new JRendererLabel(); label.setOpaque(false); label.paintComponent(null); } } swingx-1.0-src/src/test/org/jdesktop/swingx/renderer/HyperlinkProviderTest.java0000644000175000017500000001675711210401722026720 0ustar tonytony/* * $Id: HyperlinkProviderTest.java,v 1.2 2008/10/11 20:42:32 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.renderer; import java.awt.Point; import java.net.URL; import java.util.logging.Logger; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.table.TableCellRenderer; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXHyperlink; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.hyperlink.EditorPaneLinkVisitor; import org.jdesktop.swingx.hyperlink.LinkModel; import org.jdesktop.swingx.hyperlink.LinkModelAction; import org.jdesktop.swingx.rollover.RolloverProducer; import org.jdesktop.test.AncientSwingTeam; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * Test around hyperlink rendering. * * PENDING JW: how does this relate to JXHyperlinkTest? Merge? * Move to renderer package? * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class HyperlinkProviderTest extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(HyperlinkProviderTest.class .getName()); private LinkModel link; // flag used in setup to explicitly choose LF private boolean defaultToSystemLF; /** * renderers must cope with type mismatch. * */ @Test public void testMixedValueTypes() { LinkModelAction action = new LinkModelAction(new EditorPaneLinkVisitor()); TableCellRenderer linkRenderer = new DefaultTableRenderer( new HyperlinkProvider(action, LinkModel.class)); linkRenderer.getTableCellRendererComponent(null, "stringonly", false, false, -1, -1); } /** * sanity: can cope with subclasses. * a side-effect: renderers should cope with null table. */ @Test public void testSubclassedValueTypes() { LinkModelAction action = new LinkModelAction(new EditorPaneLinkVisitor()); TableCellRenderer renderer = new DefaultTableRenderer( new HyperlinkProvider(action, LinkModel.class)); LinkModel link = new LinkModel() { }; renderer.getTableCellRendererComponent(null, link, false, false, -1, -1); } /** * Issue #183-swingx. test if the selection background is updated on * changing LF. * */ @Test public void testSelectionBackground() { JXTable table = new JXTable(2, 2); TableCellRenderer linkRenderer = new DefaultTableRenderer(new HyperlinkProvider()); table.getColumnModel().getColumn(0).setCellRenderer(linkRenderer); JXHyperlink hyperlink = (JXHyperlink) linkRenderer .getTableCellRendererComponent(table, link, true, false, 1, 0); // JW: asking any background without knowing transparency state is // useless! assertTrue("renderer comp must be opaque", hyperlink.isOpaque()); assertEquals("background must be table selection background", table .getSelectionBackground(), hyperlink.getBackground()); hyperlink = (JXHyperlink) linkRenderer.getTableCellRendererComponent( table, link, false, false, 1, 0); assertEquals("background must be table background", table .getBackground(), hyperlink.getBackground()); } /** * Issue #183-swingx. test if the selection background is updated on * changing LF. * */ @Test public void testRendererComponentPropertiesAfterLFChange() { JXTable table = new JXTable(2, 2); TableCellRenderer linkRenderer = new DefaultTableRenderer(new HyperlinkProvider()); table.getColumnModel().getColumn(0).setCellRenderer(linkRenderer); // sanity: same as set assertSame(linkRenderer, table.getCellRenderer(1, 0)); JXHyperlink hyperlink = (JXHyperlink) table.prepareRenderer( linkRenderer, 1, 0); // KEEP to remember // - JW: asking for the background really doesn't make sense - // will not show if comp isn't opaque! // assertEquals("background must be table selection background", // selectionBackground, hyperlink.getBackground()); // need to check the properties which are set differently in // LinkRenderer assertTrue("renderer comp must be opaque", hyperlink.isOpaque()); assertTrue("renderer must paint border", hyperlink.isBorderPainted()); String lf = UIManager.getLookAndFeel().getName(); // switch LF setSystemLF(!defaultToSystemLF); if (lf.equals(UIManager.getLookAndFeel().getName())) { LOG.info("cannot run rendererComponentPropertiesAfterLFChange - equal LF" + lf); return; } SwingUtilities.updateComponentTreeUI(table); // sanity: same as set assertSame(linkRenderer, table.getCellRenderer(1, 0)); hyperlink = (JXHyperlink) table.prepareRenderer(linkRenderer, 1, 0); // assert that the changed properties survived the LF switch assertTrue("renderer comp must be opaque", hyperlink.isOpaque()); assertTrue("renderer must paint border", hyperlink.isBorderPainted()); } @Test public void testRolloverRecognition() { JXTable table = new JXTable(2, 2); TableCellRenderer linkRenderer = new DefaultTableRenderer(new HyperlinkProvider()); table.getColumnModel().getColumn(0).setCellRenderer(linkRenderer); JXHyperlink hyperlink = (JXHyperlink) linkRenderer .getTableCellRendererComponent(table, link, false, false, 1, 0); assertFalse("renderer must not be rollover", hyperlink.getModel() .isRollover()); table.putClientProperty(RolloverProducer.ROLLOVER_KEY, new Point(0, 1)); hyperlink = (JXHyperlink) linkRenderer.getTableCellRendererComponent( table, link, false, false, 1, 0); assertTrue("renderer must be rollover", hyperlink.getModel() .isRollover()); } /** * Issue #183-swingx. visual check if the selection background is updated on * changing LF. */ public void interactiveTableSelectionBackgroundOnLF() { final JXTable table = new JXTable(new AncientSwingTeam()); TableCellRenderer linkRenderer = new DefaultTableRenderer(new HyperlinkProvider()); table.getColumnModel().getColumn(0).setCellRenderer(linkRenderer); table.setRowSelectionInterval(1, 1); final JXFrame frame = wrapWithScrollingInFrame(table, "test background must change with LAF"); frame.setVisible(true); } public static void main(String[] args) throws Exception { // setSystemLF(true); HyperlinkProviderTest test = new HyperlinkProviderTest(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Table.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } @Override protected void setUp() throws Exception { super.setUp(); URL url = getClass().getResource("resources/test.html"); link = new LinkModel("a resource", null, url); // make sure we have the same default for each test defaultToSystemLF = false; setSystemLF(defaultToSystemLF); } } swingx-1.0-src/src/test/org/jdesktop/swingx/renderer/IconValuesTest.java0000644000175000017500000000345211210401722025274 0ustar tonytony/* * $Id: IconValuesTest.java,v 1.4 2008/12/23 18:12:37 kschaefe Exp $ * * Copyright 2008 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.renderer; import java.io.File; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; import junit.framework.TestCase; /** * * @author Karl George Schaefer */ @RunWith(JUnit4.class) public class IconValuesTest extends TestCase { @Test public void testFileIconWithNonFile() { Object o = new Object(); assertEquals(IconValues.NONE.getIcon(o), IconValues.FILE_ICON.getIcon(o)); } //not asserting the output of file icon just that it isn't none @Test public void testFileIconWithFile() throws Exception { File f = File.createTempFile("ivt", "tmp"); f.deleteOnExit(); assertNotSame(IconValues.NONE.getIcon(f), IconValues.FILE_ICON.getIcon(f)); } } swingx-1.0-src/src/test/org/jdesktop/swingx/renderer/TableRendererTest.java0000644000175000017500000004210311210401722025736 0ustar tonytony/* * $Id: TableRendererTest.java,v 1.11 2009/02/25 17:52:35 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.renderer; import java.awt.Color; import java.awt.Component; import java.io.Serializable; import java.text.DateFormat; import java.util.Date; import java.util.logging.Logger; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.test.XTestUtils; import org.jdesktop.test.SerializableSupport; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests behaviour of SwingX renderers. Currently: mostly characterization to * guarantee that they behave similar to the standard. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class TableRendererTest extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(TableRendererTest.class .getName()); private JTable table; private int coreColumn; private DefaultTableCellRenderer coreTableRenderer; private int xColumn; private DefaultTableRenderer xTableRenderer; @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } @Override protected void setUp() throws Exception { // setup table table = new JTable(10, 2); coreColumn = 0; coreTableRenderer = new DefaultTableCellRenderer(); table.getColumnModel().getColumn(coreColumn).setCellRenderer(coreTableRenderer); xColumn = 1; xTableRenderer = new DefaultTableRenderer(); table.getColumnModel().getColumn(xColumn).setCellRenderer(xTableRenderer); } /** * Issue ??-swingx: getEditable throws if cell coordinates invalid */ @Test public void testCellContextEditable() { TableCellContext cellContext = new TableCellContext(); cellContext.installContext(null, "whatever", 0, 0, false, true, false, false); assertFalse("context must cope with null component", cellContext.isEditable()); JXTable table = new JXTable(); cellContext.installContext(table, "whatever", 0, 0, false, true, false, false); // KEEP commented lines is real-world example that'll blow // DefaultVisuals visuals = new DefaultVisuals(); // visuals.configureVisuals(new JLabel(), cellContext); assertFalse("context must cope with invalid coordinates", cellContext.isEditable()); } /** * Test constructors: here convenience with alignment and converter * */ @Test public void testConstructor() { FormatStringValue sv = new FormatStringValue(DateFormat.getTimeInstance()); int align = JLabel.RIGHT; DefaultTableRenderer renderer = new DefaultTableRenderer(sv, align); assertEquals(sv, renderer.componentController.getStringValue()); assertEquals(align, renderer.componentController.getHorizontalAlignment()); } /** * test if icon handling is the same for core default and * swingx. * */ @Test public void testIcon() { TableModel model = createTableModelWithDefaultTypes(); int iconColumn = 4; // sanity assertTrue(Icon.class.isAssignableFrom(model.getColumnClass(iconColumn))); Icon icon = (Icon) model.getValueAt(0, iconColumn); // default uses a different class for icon rendering DefaultTableCellRenderer coreIconRenderer = (DefaultTableCellRenderer) table.getDefaultRenderer(Icon.class); // core default can't cope with null component - can't really compare behaviour coreIconRenderer.getTableCellRendererComponent(table, icon, false, false, -1, -1); assertEquals(icon, coreIconRenderer.getIcon()); assertEquals("", coreIconRenderer.getText()); JXTable xTable = new JXTable(); TableCellRenderer xIconRenderer = xTable.getDefaultRenderer(Icon.class); JLabel label = (JLabel) xIconRenderer.getTableCellRendererComponent(null, icon, false, false, -1, -1); assertEquals(icon, label.getIcon()); assertEquals("", label.getText()); // wrong assumption after fix of #591-swingx - default icon renderer // no longer tries to be clever // label = (JLabel) xIconRenderer.getTableCellRendererComponent(null, "dummy", false, false, -1, -1); // assertNull(label.getIcon()); // assertEquals("dummy", label.getText()); } /** * @return */ private TableModel createTableModelWithDefaultTypes() { String[] names = {"Object", "Number", "Double", "Date", "ImageIcon", "Boolean"}; final Class[] types = {Object.class, Number.class, Double.class, Date.class, ImageIcon.class, Boolean.class}; DefaultTableModel model = new DefaultTableModel(names, 0) { @Override public Class getColumnClass(int columnIndex) { return types[columnIndex]; } }; Date today = new Date(); Icon icon = XTestUtils.loadDefaultIcon(); for (int i = 0; i < 10; i++) { Object[] values = new Object[] {"row " + i, i, Math.random() * 100, new Date(today.getTime() + i * 1000000), icon, i % 2 == 0}; model.addRow(values); } return model; } /** * test serializable of default renderer. * */ @Test public void testSerializeTableRenderer() { TableCellRenderer xListRenderer = new DefaultTableRenderer(); try { SerializableSupport.serialize(xListRenderer); } catch (Exception e) { fail("not serializable " + e); } } /** * base interaction with table: focused, selected uses UI border. */ @Test public void testTableFocusSelectedBorder() { // sanity to see test test validity // UIManager.put("Table.focusSelectedCellHighlightBorder", new LineBorder(Color.red)); // access ui colors Border selectedFocusBorder = getFocusBorder(true); // sanity if (selectedFocusBorder == null) { LOG.info("cannot run focusSelectedBorder - UI has no selected focus border"); return; } // need to prepare directly - focus is true only if table is focusowner JComponent coreComponent = (JComponent) coreTableRenderer.getTableCellRendererComponent(table, null, true, true, 0, coreColumn); // sanity: known standard behaviour assertEquals(selectedFocusBorder, coreComponent.getBorder()); // prepare extended JComponent xComponent = (JComponent) xTableRenderer.getTableCellRendererComponent(table, null, true, true, 0, xColumn); // assert behaviour same as standard assertEquals(coreComponent.getBorder(), xComponent.getBorder()); } private Border getFocusBorder(boolean lookup) { Border selectedFocusBorder = UIManager.getBorder("Table.focusSelectedCellHighlightBorder"); if (lookup && (selectedFocusBorder == null)) { selectedFocusBorder = UIManager.getBorder("Table.focusCellHighlightBorder"); } return selectedFocusBorder; } /** * base interaction with table: focused, not-selected uses UI border. * * */ @Test public void testTableFocusBorder() { // access ui colors Border focusBorder = UIManager.getBorder("Table.focusCellHighlightBorder"); // Border selectedFocusBorder = UIManager.getBorder("Table.focusSelectedCellHighlightBorder"); // sanity assertNotNull(focusBorder); // need to prepare directly - focus is true only if table is focusowner JComponent coreComponent = (JComponent) coreTableRenderer.getTableCellRendererComponent(table, null, false, true, 0, coreColumn); // sanity: known standard behaviour assertEquals(focusBorder, coreComponent.getBorder()); // prepare extended JComponent xComponent = (JComponent) xTableRenderer.getTableCellRendererComponent(table, null, false, true, 0, xColumn); // assert behaviour same as standard assertEquals(coreComponent.getBorder(), xComponent.getBorder()); } /** * base interaction with table: focused, not-selected and editable * uses UI colors. * */ @Test public void testTableRendererExtFocusedNotSelectedEditable() { // sanity assertTrue(table.isCellEditable(0, coreColumn)); // access ui colors Color uiForeground = UIManager.getColor("Table.focusCellForeground"); Color uiBackground = UIManager.getColor("Table.focusCellBackground"); // sanity assertNotNull(uiForeground); assertNotNull(uiBackground); Color background = Color.MAGENTA; Color foreground = Color.YELLOW; // prepare standard coreTableRenderer.setBackground(background); coreTableRenderer.setForeground(foreground); // need to prepare directly - focus is true only if table is focusowner Component coreComponent = coreTableRenderer.getTableCellRendererComponent(table, null, false, true, 0, coreColumn); // sanity: known standard behaviour assertEquals(uiBackground, coreComponent.getBackground()); assertEquals(uiForeground, coreComponent.getForeground()); // prepare extended xTableRenderer.setBackground(background); xTableRenderer.setForeground(foreground); Component xComponent = xTableRenderer.getTableCellRendererComponent(table, null, false, true, 0, xColumn); // assert behaviour same as standard assertEquals(coreComponent.getBackground(), xComponent.getBackground()); assertEquals(coreComponent.getForeground(), xComponent.getForeground()); } /** * base interaction with table: custom color of renderer precedes * table color. * */ @Test public void testTableRendererExtCustomColor() { Color background = Color.MAGENTA; Color foreground = Color.YELLOW; // prepare standard coreTableRenderer.setBackground(background); coreTableRenderer.setForeground(foreground); Component coreComponent = table.prepareRenderer(coreTableRenderer, 0, coreColumn); // sanity: known standard behaviour assertEquals(background, coreComponent.getBackground()); assertEquals(foreground, coreComponent.getForeground()); // prepare extended xTableRenderer.setBackground(background); xTableRenderer.setForeground(foreground); Component xComponent = table.prepareRenderer(xTableRenderer, 0, xColumn); // assert behaviour same as standard assertEquals(coreComponent.getBackground(), xComponent.getBackground()); assertEquals(coreComponent.getForeground(), xComponent.getForeground()); } /** * base interaction with table: renderer uses table's selection color. * */ @Test public void testTableRendererExtSelectedColors() { // select first row table.setRowSelectionInterval(0, 0); // prepare standard Component coreComponent = table.prepareRenderer(coreTableRenderer, 0, coreColumn); // sanity: known standard behaviour assertEquals(table.getSelectionBackground(), coreComponent.getBackground()); assertEquals(table.getSelectionForeground(), coreComponent.getForeground()); // prepare extended Component xComponent = table.prepareRenderer(xTableRenderer, 0, xColumn); // assert behaviour same as standard assertEquals(coreComponent.getBackground(), xComponent.getBackground()); assertEquals(coreComponent.getForeground(), xComponent.getForeground()); } /** * base interaction with table: renderer uses table's custom selection color. * */ @Test public void testTableRendererExtTableSelectedColors() { Color background = Color.MAGENTA; Color foreground = Color.YELLOW; table.setSelectionBackground(background); table.setSelectionForeground(foreground); // select first row table.setRowSelectionInterval(0, 0); // prepare standard Component coreComponent = table.prepareRenderer(coreTableRenderer, 0, coreColumn); // sanity: known standard behaviour assertEquals(table.getSelectionBackground(), coreComponent.getBackground()); assertEquals(table.getSelectionForeground(), coreComponent.getForeground()); // prepare extended Component xComponent = table.prepareRenderer(xTableRenderer, 0, xColumn); // assert behaviour same as standard assertEquals(coreComponent.getBackground(), xComponent.getBackground()); assertEquals(coreComponent.getForeground(), xComponent.getForeground()); } /** * base interaction with table: renderer uses table's unselected colors. * */ @Test public void testTableRendererExtColors() { // prepare standard Component coreComponent = table.prepareRenderer(coreTableRenderer, 0, coreColumn); // sanity: known standard behaviour assertEquals(table.getBackground(), coreComponent.getBackground()); assertEquals(table.getForeground(), coreComponent.getForeground()); // prepare extended Component xComponent = table.prepareRenderer(xTableRenderer, 0, xColumn); // assert behaviour same as standard assertEquals(coreComponent.getBackground(), xComponent.getBackground()); assertEquals(coreComponent.getForeground(), xComponent.getForeground()); } /** * base interaction with table: renderer uses table's unselected custom colors * * */ @Test public void testTableRendererExtTableColors() { Color background = Color.MAGENTA; Color foreground = Color.YELLOW; table.setBackground(background); table.setForeground(foreground); // prepare standard Component coreComponent = table.prepareRenderer(coreTableRenderer, 0, coreColumn); // sanity: known standard behaviour assertEquals(table.getBackground(), coreComponent.getBackground()); assertEquals(table.getForeground(), coreComponent.getForeground()); // prepare extended Component xComponent = table.prepareRenderer(xTableRenderer, 0, xColumn); // assert behaviour same as standard assertEquals(coreComponent.getBackground(), xComponent.getBackground()); assertEquals(coreComponent.getForeground(), xComponent.getForeground()); } /** * characterize opaqueness of rendering components. * */ @Test public void testTableOpaqueRenderer() { // sanity assertFalse(new JLabel().isOpaque()); assertTrue(coreTableRenderer.isOpaque()); // assertTrue(xTableRenderer.getRendererComponent().isOpaque()); } /** * characterize opaqueness of rendering components. * * that's useless: the opaque magic only applies if parent != null */ @Test public void testTableOpaqueRendererComponent() { // sanity assertFalse(new JLabel().isOpaque()); Component coreComponent = table.prepareRenderer(coreTableRenderer, 0, coreColumn); // prepare extended assertTrue(coreComponent.isOpaque()); Component xComponent = table.prepareRenderer(xTableRenderer, 0, xColumn); assertTrue(xComponent.isOpaque()); } /** * base existence/type tests while adding DefaultTableCellRendererExt. * */ @Test public void testTableRendererExt() { DefaultTableRenderer renderer = new DefaultTableRenderer(); assertTrue(renderer instanceof TableCellRenderer); assertTrue(renderer instanceof Serializable); } } swingx-1.0-src/src/test/org/jdesktop/swingx/renderer/TreeRendererIssues.java0000644000175000017500000002150211210401722026142 0ustar tonytony/* * $Id: TreeRendererIssues.java,v 1.6 2008/06/24 11:11:51 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.renderer; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.event.ActionEvent; import java.io.IOException; import java.util.logging.Logger; import javax.swing.Action; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreePath; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXPanel; import org.jdesktop.swingx.JXTree; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.painter.ImagePainter; import org.jdesktop.swingx.test.ComponentTreeTableModel; import org.jdesktop.swingx.test.XTestUtils; /** * Known/open issues with tree renderer. * * @author Jeanette Winzenburg */ public class TreeRendererIssues extends InteractiveTestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger.getLogger(TreeRendererIssues.class .getName()); private JTree tree; private DefaultTreeCellRenderer coreTreeRenderer; private DefaultTreeRenderer xTreeRenderer; // flag used in setup to explicitly choose LF private boolean defaultToSystemLF; @Override protected void setUp() throws Exception { // setSystemLF(true); // LOG.info("LF: " + UIManager.getLookAndFeel()); // LOG.info("Theme: " + ((MetalLookAndFeel) UIManager.getLookAndFeel()).getCurrentTheme()); // UIManager.put("Tree.drawsFocusBorderAroundIcon", Boolean.TRUE); // make sure we have the same default for each test defaultToSystemLF = false; setSystemLF(defaultToSystemLF); tree = new JTree(); coreTreeRenderer = new DefaultTreeCellRenderer(); xTreeRenderer = new DefaultTreeRenderer(); } public static void main(String[] args) { TreeRendererIssues test = new TreeRendererIssues(); try { test.runInteractiveTests(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void interactiveTransparentRenderer() throws IOException { final JXTree tree = new JXTree(new ComponentTreeTableModel(new JXFrame())); tree.setEditable(true); StringValue sv = new StringValue() { public String getString(Object value) { if (value instanceof Component) { return ((Component) value).getName(); } return " - no component - "; }}; DefaultTreeRenderer renderer = new DefaultTreeRenderer(sv); tree.setCellRenderer(renderer); tree.setForeground(Color.WHITE); JXPanel panel = new JXPanel(new BorderLayout()); ImagePainter imagePainter = new ImagePainter(XTestUtils.loadDefaultImage()); imagePainter.setFillHorizontal(true); imagePainter.setFillVertical(true); panel.setBackgroundPainter(imagePainter); panel.add(new JScrollPane(tree)); JXFrame frame = wrapInFrame(panel, "renderer"); WrappingProvider provider = (WrappingProvider) renderer.getComponentProvider(); provider.getWrappee().getRendererComponent(null).setOpaque(false); tree.setOpaque(false); ((JComponent) tree.getParent()).setOpaque(false); ((JComponent) tree.getParent().getParent()).setOpaque(false); Action edit = new AbstractActionExt("edit") { public void actionPerformed(ActionEvent e) { if (tree.isSelectionEmpty()) return; TreePath path = tree.getSelectionPath(); Component comp = (Component) path.getLastPathComponent(); String oldName = comp.getName(); if (oldName == null) { oldName = "none"; } String changed = oldName.length() > 60 ? oldName.substring(0, 20) : oldName + "+++++++++++++++++++++++++++++++++++++++++++++"; tree.getModel().valueForPathChanged(path, changed); } }; addAction(frame, edit); show(frame); } /** * Sanity: icons updated on LF change. */ public void testTreeIconsUpdateUI() { JXTree tree = new JXTree(); DefaultTreeRenderer renderer = new DefaultTreeRenderer(); tree.setCellRenderer(renderer); WrappingIconPanel before = (WrappingIconPanel) renderer.getTreeCellRendererComponent(tree, "", false, false, true, -1, false); Icon leaf = before.getIcon(); assertNotNull("sanity", leaf); assertEquals("sanity", UIManager.getIcon("Tree.leafIcon"), leaf); String lf = UIManager.getLookAndFeel().getName(); setSystemLF(!defaultToSystemLF); if (lf.equals(UIManager.getLookAndFeel().getName())) { LOG.info("cannot run test - equal LF" + lf); return; } SwingUtilities.updateComponentTreeUI(tree); WrappingIconPanel after = (WrappingIconPanel) renderer.getTreeCellRendererComponent(tree, "", false, false, true, -1, false); Icon leafAfter = after.getIcon(); assertNotNull("sanity", leafAfter); assertFalse("sanity", leaf.equals(leafAfter)); assertEquals("icon must be updated", UIManager.getIcon("Tree.leafIcon"), leafAfter); } /** * base interaction with list: renderer uses list's unselected colors * * currently, this test fails because the assumptions are wrong! Core * renderer behaves slightly unexpected. * * */ public void testTreeRendererExtColors() { // prepare standard Component coreComponent = coreTreeRenderer.getTreeCellRendererComponent(tree, null, false, false, false, 0, false); // sanity: known standard behaviour assertNull(coreComponent.getBackground()); // assertNull(coreComponent.getForeground()); assertNull(tree.getForeground()); Color uiForeground = UIManager.getColor("Tree.textForeground"); assertEquals(uiForeground, coreComponent.getForeground()); // prepare extended Component xComponent = xTreeRenderer.getTreeCellRendererComponent(tree, null, false, false, false, 0, false); // assert behaviour same as standard // assertEquals(coreComponent.getBackground(), xComponent.getBackground()); assertEquals(coreComponent.getForeground(), xComponent.getForeground()); } /** * base interaction with list: renderer uses list's unselected custom * colors. * * currently, this test fails because the assumptions are wrong! Core * renderer behaves slightly unexpected. * */ public void testTreeRendererExtTreeColors() { Color background = Color.MAGENTA; Color foreground = Color.YELLOW; tree.setBackground(background); tree.setForeground(foreground); coreTreeRenderer.setBackgroundNonSelectionColor(background); coreTreeRenderer.setTextNonSelectionColor(foreground); // prepare standard Component coreComponent = coreTreeRenderer .getTreeCellRendererComponent(tree, null, false, false, false, 0, false); // sanity: known standard behaviour // background is manually painted assertEquals(background, coreComponent.getBackground()); assertEquals(tree.getForeground(), coreComponent.getForeground()); // prepare extended Component xComponent = xTreeRenderer.getTreeCellRendererComponent(tree, null, false, false, false, 0, false); // assert behaviour same as standard assertEquals(background, xComponent.getBackground()); assertEquals(foreground, xComponent.getForeground()); } } swingx-1.0-src/src/test/org/jdesktop/swingx/FindTest.java0000644000175000017500000001163311210401724022300 0ustar tonytony/* * $Id: FindTest.java,v 1.34 2008/12/01 14:54:55 kleopatra Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx; import java.net.URL; import java.util.regex.Pattern; import org.jdesktop.swingx.JXEditorPane.DocumentSearchable; import org.jdesktop.swingx.search.SearchFactory; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Contains unit test for search related classes which have references to * swingx package internals (namely JXEditorPane.DocumentSearchable). * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class FindTest extends InteractiveTestCase { @Override protected void setUp() throws Exception { super.setUp(); // sanity: new instance for each test SearchFactory.setInstance(new SearchFactory()); } @Test public void testWrapFindBar() { JXFindBar findBar = new JXFindBar(); assertTrue("findbar must auto-wrap", findBar.getPatternModel().isWrapping()); } /** * test if internal state is reset when search triggered through * methods taking a string. * * */ @Test public void testEditorResetStateOnEmptySearchString() { JXEditorPane editor = new JXEditorPane(); String text = "fou four"; editor.setText(text); // initialize to found state int foundIndex = editor.getSearchable().search("ou"); // sanity assertEquals(1, foundIndex); // search with null searchString int notFoundIndex = editor.getSearchable().search("", foundIndex); // sanity: nothing found assertEquals(-1, notFoundIndex); assertEquals(notFoundIndex, ((DocumentSearchable) editor.getSearchable()).lastFoundIndex); } /** * test if internal state is reset when search triggered through * methods taking a string. * * */ @Test public void testEditorResetStateOnNullSearchString() { JXEditorPane editor = new JXEditorPane(); String text = "fou four"; editor.setText(text); // initialize to found state int foundIndex = editor.getSearchable().search("ou"); // sanity assertEquals(1, foundIndex); // search with null searchString int notFoundIndex = editor.getSearchable().search((String) null, foundIndex); // sanity: nothing found assertEquals(-1, notFoundIndex); assertEquals(notFoundIndex, ((DocumentSearchable) editor.getSearchable()).lastFoundIndex); } /** * test if internal state is reset when search triggered through * methods taking a string. * * */ @Test public void testEditorResetStateOnNullPattern() { JXEditorPane editor = new JXEditorPane(); String text = "fou four"; editor.setText(text); // initialize to found state int foundIndex = editor.getSearchable().search("ou"); // sanity assertEquals(1, foundIndex); // search with null searchString int notFoundIndex = editor.getSearchable().search((Pattern) null, foundIndex); // sanity: nothing found assertEquals(-1, notFoundIndex); assertEquals(notFoundIndex, ((DocumentSearchable) editor.getSearchable()).lastFoundIndex); } @Test public void testEditor() { URL url = FindTest.class.getResource("resources/test.txt"); try { JXEditorPane editor = new JXEditorPane(url); // There are 9 instances of "four" in the test document int useIndex = -1; int lastIndex = -1; for (int i = 0; i < 9; i++) { lastIndex = editor.getSearchable().search("four", useIndex); assertTrue(lastIndex != -1); assertTrue(lastIndex != useIndex); assertEquals("Error text selection is incorrect", "four", editor.getSelectedText()); useIndex = lastIndex; } } catch (Exception ex) { throw new RuntimeException("Error finding resource for JXEditorPane", ex); } } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXTaskPaneContainerIssues.java0000644000175000017500000000237711210401722025572 0ustar tonytony/* * $Id: JXTaskPaneContainerIssues.java,v 1.2 2008/08/22 18:24:44 kschaefe Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx; import junit.framework.TestCase; /** * * @author Jeanette Winzenburg */ public class JXTaskPaneContainerIssues extends TestCase { /** * Empty test method to keep the test runner happy if we have no * open issues. */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/XLocalizeTest.java0000644000175000017500000004273411210401722023316 0ustar tonytony/* * $Id: XLocalizeTest.java,v 1.11 2009/01/27 22:53:23 rah003 Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx; import java.awt.Component; import java.awt.GraphicsEnvironment; import java.awt.event.ActionEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Locale; import java.util.logging.Logger; import javax.swing.Action; import javax.swing.JComponent; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.plaf.LookAndFeelAddons; import org.jdesktop.swingx.plaf.UIManagerExt; import org.jdesktop.swingx.search.PatternModel; import org.jdesktop.test.PropertyChangeReport; import org.jdesktop.test.TestUtils; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; /** * Test to expose known issues around Locale setting. * * Ideally, there would be at least one failing test method per open * Issue in the issue tracker. Plus additional failing test methods for * not fully specified or not yet decided upon features/behaviour. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class XLocalizeTest extends InteractiveTestCase { @SuppressWarnings("all") private static final Logger LOG = Logger.getLogger(XLocalizeTest.class .getName()); private static final Locale A_LOCALE = Locale.FRENCH; private static final Locale OTHER_LOCALE = Locale.GERMAN; private Locale originalLocale; // test scope is static anyway... static { // force the addon to load LookAndFeelAddons.getAddon(); } public static void main(String[] args) { // setSystemLF(true); XLocalizeTest test = new XLocalizeTest(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*TwoTable.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } @Override protected void setUp() throws Exception { originalLocale = Locale.getDefault(); super.setUp(); } @Override protected void tearDown() throws Exception { Locale.setDefault(originalLocale); super.tearDown(); } /** * test correct PropertyChangeNotification: must fire after * all internal state is set ... dooohhh. * * Here: test JXDialog. */ /** * test correct PropertyChangeNotification: must fire after * all internal state is set ... * * Here: test FindPanel */ @Test public void testLocaleDialogPropertyNotificationInListener() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run localeDialogPropertyNotificationInListener - headless environment"); return; } final String prefix = PatternModel.SEARCH_PREFIX; final JXFindPanel findPanel = new JXFindPanel(); final JXDialog dialog = new JXDialog(findPanel); final String titleKey = AbstractPatternPanel.SEARCH_TITLE; // JW: arrrgghh ... dirty! Consequence of dirty initialization // of AbstractPatternPanel subclasses ... findPanel.addNotify(); String name = dialog.getTitle(); String uiValue = UIManagerExt.getString(prefix + titleKey, findPanel .getLocale()); // sanity assertNotNull(uiValue); assertEquals(name, uiValue); final Locale alternative = getAlternativeLocale(dialog); PropertyChangeListener report = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { // sanity // wrong assumption: find widgets name is changed as well // assertTrue("locale property changed, instead: " + evt.getPropertyName(), "locale".equals(evt.getPropertyName())); if (!"locale".equals(evt.getPropertyName())) return; String altUIValue = UIManagerExt.getString(prefix + titleKey, alternative); String altName = dialog.getTitle(); assertEquals("name must be updated before fire propertyChange", altUIValue, altName); }}; dialog.addPropertyChangeListener(report); PropertyChangeReport r = new PropertyChangeReport(); dialog.addPropertyChangeListener(r); dialog.setLocale(alternative); // sanity: guarantee that we got a locale change notification assertEquals(1, r.getEventCount("locale")); } /** * test correct PropertyChangeNotification: must fire after * all internal state is set ... dooohhh. * * Here: test FindBar. */ @Test public void testLocaleFindBarPropertyNotificationInListener() { final String prefix = PatternModel.SEARCH_PREFIX; final JXFindBar findPanel = new JXFindBar(); final String actionCommand = JXFindBar.FIND_NEXT_ACTION_COMMAND; // JW: arrrgghh ... dirty! Consequence of dirty initialization // of AbstractPatternPanel subclasses ... findPanel.addNotify(); final Action action = findPanel.getActionMap().get(actionCommand); String name = (String) action.getValue(Action.NAME); String uiValue = UIManagerExt.getString(prefix + actionCommand, findPanel .getLocale()); // sanity assertNotNull(uiValue); assertEquals(name, uiValue); final Locale alternative = getAlternativeLocale(findPanel); PropertyChangeListener report = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { // sanity // assertTrue("locale property changed", "locale".equals(evt.getPropertyName())); if (!"locale".equals(evt.getPropertyName())) return; String altUIValue = UIManagerExt.getString(prefix + actionCommand, alternative); String altName = (String) action.getValue(Action.NAME); assertEquals("name must be updated before fire propertyChange", altUIValue, altName); }}; PropertyChangeReport r = new PropertyChangeReport(); findPanel.addPropertyChangeListener(r); findPanel.setLocale(alternative); assertEquals(1, r.getEventCount("locale")); } /** * test correct PropertyChangeNotification: must fire after * all internal state is set ... * * Here: test FindPanel */ @Test public void testLocaleFindPanelPropertyNotificationInListener() { final String prefix = PatternModel.SEARCH_PREFIX; final JXFindPanel findPanel = new JXFindPanel(); final String actionCommand = AbstractPatternPanel.MATCH_ACTION_COMMAND; // JW: arrrgghh ... dirty! Consequence of dirty initialization // of AbstractPatternPanel subclasses ... findPanel.addNotify(); final Action action = findPanel.getActionMap().get(actionCommand); String name = (String) action.getValue(Action.NAME); String uiValue = UIManagerExt.getString(prefix + actionCommand, findPanel .getLocale()); // sanity assertNotNull(uiValue); assertEquals(name, uiValue); final Locale alternative = getAlternativeLocale(findPanel); PropertyChangeListener report = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { // sanity // wrong assumption: find widgets name is changed as well // assertTrue("locale property changed, instead: " + evt.getPropertyName(), "locale".equals(evt.getPropertyName())); if (!"locale".equals(evt.getPropertyName())) return; String altUIValue = UIManagerExt.getString(prefix + actionCommand, alternative); String altName = (String) action.getValue(Action.NAME); assertEquals("name must be updated before fire propertyChange", altUIValue, altName); }}; findPanel.addPropertyChangeListener(report); PropertyChangeReport r = new PropertyChangeReport(); findPanel.addPropertyChangeListener(r); findPanel.setLocale(alternative); assertEquals(1, r.getEventCount("locale")); } /** * test correct PropertyChangeNotification: must fire after * all internal state is set ... dooohhh. */ @Test public void testLocaleTablePropertyNotification() { String prefix = "JXTable."; JXTable table = new JXTable(10, 2); String actionCommand = JXTable.HORIZONTALSCROLL_ACTION_COMMAND; Action action = table.getActionMap().get(actionCommand); String name = (String) action.getValue(Action.NAME); String uiValue = UIManagerExt.getString(prefix + actionCommand, table .getLocale()); // sanity assertNotNull(uiValue); assertEquals(name, uiValue); Locale old = table.getLocale(); Locale alternative = getAlternativeLocale(table); PropertyChangeReport report = new PropertyChangeReport(); table.addPropertyChangeListener(report); table.setLocale(alternative); TestUtils.assertPropertyChangeEvent(report, "locale", old, alternative); } /** * test correct PropertyChangeNotification: must fire after * all internal state is set ... * * Here: test JXTable. */ @Test public void testLocaleTablePropertyNotificationInListener() { final String prefix = "JXTable."; final JXTable table = new JXTable(10, 2); final String actionCommand = JXTable.HORIZONTALSCROLL_ACTION_COMMAND; final Action action = table.getActionMap().get(actionCommand); String name = (String) action.getValue(Action.NAME); String uiValue = UIManagerExt.getString(prefix + actionCommand, table .getLocale()); // sanity assertNotNull(uiValue); assertEquals(name, uiValue); final Locale alternative = getAlternativeLocale(table); PropertyChangeListener report = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { // sanity assertTrue("locale property changed", "locale".equals(evt.getPropertyName())); String altUIValue = UIManagerExt.getString(prefix + actionCommand, alternative); String altName = (String) action.getValue(Action.NAME); assertEquals("name must be updated before fire propertyChange", altUIValue, altName); }}; table.addPropertyChangeListener(report); table.setLocale(alternative); } private Locale getAlternativeLocale(final Component table) { Locale alternative = OTHER_LOCALE; if (alternative.getLanguage().equals(table.getLocale().getLanguage())) { alternative = A_LOCALE; } return alternative; } /** * Issue #635-swingx: find widgets must support dynamic localization * Here: test findPanel's actions (incomplete ..) */ @Test public void testLocaleFindPanel() { JXFindPanel panel = new JXFindPanel(); // JW: arrrgghh ... dirty! Consequence of dirty initialization // of AbstractPatternPanel subclasses ... panel.addNotify(); String prefix = PatternModel.SEARCH_PREFIX; assertLocaleActionUpdate(panel, prefix, AbstractPatternPanel.MATCH_ACTION_COMMAND); assertLocaleActionUpdate(panel, prefix, JXFindPanel.FIND_NEXT_ACTION_COMMAND); assertLocaleActionUpdate(panel, prefix, JXFindPanel.FIND_PREVIOUS_ACTION_COMMAND); } /** * Issue #459-swingx: JXTable setLocale doesn't update localized column * control properties.

* * Pass/fail expectation: *

    *
  • fails always with jdk5 independent of LookAndFeelAddon resource * bundle registration. *
  • fails with jdk6 and LookAndFeelAddon copy resource bundle values. *
  • passes with jdk6 and LookAndFeelAddon addResourceBundle. *
*/ @Test public void testLocaleColumnControl() { String prefix = "JXTable."; JXTable table = new JXTable(10, 2); assertLocaleActionUpdate(table, prefix, JXTable.HORIZONTALSCROLL_ACTION_COMMAND); assertLocaleActionUpdate(table, prefix, JXTable.PACKALL_ACTION_COMMAND); assertLocaleActionUpdate(table, prefix, JXTable.PACKSELECTED_ACTION_COMMAND); } private void assertLocaleActionUpdate(JComponent table, String prefix, String actionCommand) { Action action = table.getActionMap().get(actionCommand); String name = (String) action.getValue(Action.NAME); String uiValue = UIManagerExt.getString(prefix + actionCommand, table .getLocale()); // sanity assertNotNull(uiValue); assertEquals(name, uiValue); Locale alternative = OTHER_LOCALE; if (alternative.getLanguage().equals(table.getLocale().getLanguage())) { alternative = A_LOCALE; } table.setLocale(alternative); String altUIValue = UIManagerExt.getString(prefix + actionCommand, table.getLocale()); // sanity assertNotNull(altUIValue); // sanity to track unexpected failure during refactoring assertFalse("new uiValue must be different: " + uiValue + "/" + altUIValue, uiValue.equals(altUIValue)); String altName = (String) action.getValue(Action.NAME); // here are the real asserts assertFalse("new action name must be different: " + name + "/" + altName, name.equals(altName)); assertEquals(altName, altUIValue); } /** * Issue #466-swingx: locale-dependent values not accessible. This looks * like a side-effect of the first go on #159-swingx (not all values of * resourceBundle available). *

* * Could be core problem (in jdk5, fixed in jdk6) around classloader and * ResourceBundle: * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4834404 * * */ @Test public void testGetLocaleUIDefaults() { String key = "JXTable.column.packAll"; Object alternativeValue = UIManagerExt.getString(key, OTHER_LOCALE); // sanity - the value must be available assertNotNull(alternativeValue); Object defaultValue = UIManagerExt.getString(key, A_LOCALE); // sanity - the value must be available assertNotNull(defaultValue); assertFalse("values must be different: " + defaultValue + "/" + alternativeValue, defaultValue.equals(alternativeValue)); } /** * Issue #459-swingx: columnControl properties not updated on locale setting. * */ public void interactiveLocaleColumnControl() { final JXTable table = new JXTable(10, 4); table.setColumnControlVisible(true); table.getColumnExt(0).setTitle(table.getLocale().getLanguage()); Action toggleLocale = new AbstractActionExt("toggleLocale") { public void actionPerformed(ActionEvent e) { Locale old = table.getLocale(); table.setLocale(old == A_LOCALE ? OTHER_LOCALE : A_LOCALE); table.getColumnExt(0).setTitle(table.getLocale().getLanguage()); } }; JXFrame frame = wrapWithScrollingInFrame(table, "toggle locale on table - column control not updated"); addAction(frame, toggleLocale); frame.setVisible(true); } /** * Issue #459-swingx: columnControl properties not updated on locale setting. * * */ public void interactiveLocaleColumnControlTwoTables() { final JXTable table = new JXTable(10, 4); table.setColumnControlVisible(true); table.getColumnExt(0).setTitle(table.getLocale().getLanguage()); JXTable other = new JXTable(10, 4); other.setColumnControlVisible(true); other.setLocale(A_LOCALE); other.getColumnExt(0).setTitle(other.getLocale().getLanguage()); JXFrame frame = wrapWithScrollingInFrame(table, other, "different locals: de <--> vs fr"); addSearchModeToggle(frame); addMessage(frame, "Find panel/bar should be localized per-table"); frame.pack(); frame.setVisible(true); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXTableVisualCheck.java0000644000175000017500000020470711210401722024177 0ustar tonytony/* * $Id: JXTableVisualCheck.java,v 1.87 2009/01/22 17:31:43 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.KeyboardFocusManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.MouseEvent; import java.text.Format; import java.text.NumberFormat; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.DefaultListSelectionModel; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JToolBar; import javax.swing.JViewport; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableColumnModelEvent; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; import org.jdesktop.swingx.JXTable.NumberEditor; import org.jdesktop.swingx.JXTableHeader.SortGestureRecognizer; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.decorator.AbstractHighlighter; import org.jdesktop.swingx.decorator.ColorHighlighter; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.Filter; import org.jdesktop.swingx.decorator.FilterPipeline; import org.jdesktop.swingx.decorator.HighlightPredicate; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.HighlighterFactory; import org.jdesktop.swingx.decorator.PatternFilter; import org.jdesktop.swingx.decorator.ShuttleSorter; import org.jdesktop.swingx.decorator.SortController; import org.jdesktop.swingx.decorator.Sorter; import org.jdesktop.swingx.hyperlink.LinkModel; import org.jdesktop.swingx.hyperlink.LinkModelAction; import org.jdesktop.swingx.renderer.CheckBoxProvider; import org.jdesktop.swingx.renderer.DefaultTableRenderer; import org.jdesktop.swingx.renderer.HyperlinkProvider; import org.jdesktop.swingx.search.SearchFactory; import org.jdesktop.swingx.table.ColumnFactory; import org.jdesktop.swingx.table.ColumnHeaderRenderer; import org.jdesktop.swingx.table.DatePickerCellEditor; import org.jdesktop.swingx.table.NumberEditorExt; import org.jdesktop.swingx.table.TableColumnExt; import org.jdesktop.test.AncientSwingTeam; /** * Split from old JXTableUnitTest - contains "interactive" * methods only.

* * PENDING: too many frames to fit all on screen - either split into different * tests or change positioning algo to start on top again if hidden.

* @author Jeanette Winzenburg */ public class JXTableVisualCheck extends JXTableUnitTest { private static final Logger LOG = Logger.getLogger(JXTableVisualCheck.class .getName()); public static void main(String args[]) { JXTableVisualCheck test = new JXTableVisualCheck(); try { // test.runInteractiveTests(); test.runInteractiveTests("interactive.*Grid.*"); // test.runInteractiveTests("interactive.*Header.*"); // test.runInteractiveTests("interactive.*ColumnProp.*"); // test.runInteractiveTests("interactive.*Multiple.*"); // test.runInteractiveTests("interactive.*RToL.*"); // test.runInteractiveTests("interactive.*Scrollable.*"); // test.runInteractiveTests("interactive.*isable.*"); // test.runInteractiveTests("interactive.*Policy.*"); // test.runInteractiveTests("interactive.*Rollover.*"); // test.runInteractiveTests("interactive.*UpdateUI.*"); // test.runInteractiveTests("interactiveColumnHighlighting"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } @Override protected void setUp() throws Exception { super.setUp(); // super has LF specific tests... setSystemLF(true); } /** * Possible problem: table without gridlines has header mis-aligned. * Looks okay for me. */ public void interactiveNoGridlines() { JXTable table = new JXTable(20, 100); for (int i = 0; i < table.getColumnCount(); i++) { table.setValueAt("col: " + i, 0, i); } table.setHorizontalScrollEnabled(true); table.setShowGrid(true, false); showWithScrollingInFrame(table, "align header without gridlines?"); } /** * Issue #908-swingx: move updateUI responsibility into column. * */ public void interactiveUpdateUIRenderers() { JXTable table = new JXTable(new AncientSwingTeam()); table.getColumn(4).setCellRenderer(new DefaultTableRenderer(new CheckBoxProvider())); showWithScrollingInFrame(table, "toggle ui - must update renderers"); } /** * Issue #908-swingx: move updateUI responsibility into column. * */ public void interactiveUpdateUIEditors() { DefaultTableModel model = new DefaultTableModel(5, 5) { @Override public Class getColumnClass(int columnIndex) { if (getValueAt(0, columnIndex) == null) return super.getColumnClass(columnIndex); return getValueAt(0, columnIndex).getClass(); } }; for (int i = 0; i < model.getRowCount(); i++) { model.setValueAt(new Date(), i, 0); } JXTable table = new JXTable(model); TableCellEditor editor = new DatePickerCellEditor(); table.getColumn(0).setCellEditor(editor); showWithScrollingInFrame(table, "toggle ui - must update editors"); } /** * Issue #550-swingx: xtable must not reset columns' pref/size on * structureChanged if autocreate is false. * * */ public void interactiveColumnWidthOnStructureChanged() { final JXTable table = new JXTable(new AncientSwingTeam()); table.setAutoCreateColumnsFromModel(false); table.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF); table.setColumnControlVisible(true); // min/max is respected // mini.setMaxWidth(5); // mini.setMinWidth(5); Action structureChanged = new AbstractAction("fire structure changed") { public void actionPerformed(ActionEvent e) { table.tableChanged(null); } }; JXFrame frame = showWithScrollingInFrame(table, "structure change must not re-size columns"); addAction(frame, structureChanged); show(frame); } /** * Issue #675-swingx: esc doesn't reach rootpane. * * Verify that the escape is intercepted only if editing. * BUT: (core behaviour) starts editing in table processKeyBinding. So every * second is not passed on. */ public void interactiveDialogCancelOnEscape() { Action cancel = new AbstractActionExt("cancel") { public void actionPerformed(ActionEvent e) { LOG.info("performed: cancel action"); } }; final JButton field = new JButton(cancel); JXTable xTable = new JXTable(10, 3); JTable table = new JTable(xTable.getModel()); JXFrame frame = wrapWithScrollingInFrame(xTable, table, "escape passed to rootpane (if editing)"); frame.setCancelButton(field); frame.add(field, BorderLayout.SOUTH); frame.setVisible(true); } /** * Issue #508/547-swingx: clean up of pref scrollable. * Visual check: column init on model change. * */ public void interactivePrefScrollable() { final DefaultTableModel tableModel = new DefaultTableModel(30, 7); final AncientSwingTeam ancientSwingTeam = new AncientSwingTeam(); final JXTable table = new JXTable(tableModel); table.setColumnControlVisible(true); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); final JXFrame frame = showWithScrollingInFrame(table, "initial sizing"); addMessage(frame, "initial size: " + table.getPreferredScrollableViewportSize()); Action action = new AbstractActionExt("toggle model") { public void actionPerformed(ActionEvent e) { table.setModel(table.getModel() == tableModel ? ancientSwingTeam : tableModel); frame.pack(); } }; addAction(frame, action); frame.pack(); } /** * Issue #508/547-swingx: clean up of pref scrollable. * Visual check: dynamic logical scroll sizes * Toggle visual row/column count. */ public void interactivePrefScrollableDynamic() { final AncientSwingTeam ancientSwingTeam = new AncientSwingTeam(); final JXTable table = new JXTable(ancientSwingTeam); table.setColumnControlVisible(true); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); final JXFrame frame = wrapWithScrollingInFrame(table, "Dynamic pref scrollable"); Action action = new AbstractActionExt("vis row") { public void actionPerformed(ActionEvent e) { int visRowCount = table.getVisibleRowCount() + 5; if (visRowCount > 30) { visRowCount = 10; } table.setVisibleRowCount(visRowCount); frame.pack(); } }; addAction(frame, action); Action columnAction = new AbstractActionExt("vis column") { public void actionPerformed(ActionEvent e) { int visColumnCount = table.getVisibleColumnCount(); if (visColumnCount > 8) { visColumnCount = -1; } else if (visColumnCount < 0 ) { visColumnCount = 2; } else { visColumnCount += 2; } table.setVisibleColumnCount(visColumnCount); frame.pack(); } }; addAction(frame, columnAction); frame.setVisible(true); frame.pack(); } /** * Issue #445-swingx: sort icon not updated on programatic sorting. * The issue is the update (== repaint), so a non-visual test method * will always pass (the icon-border is set in getRendererComp). */ public void interactiveHeaderUpdateOnSorting() { final JXTable table = new JXTable(createAscendingModel(0, 10)); Action action = new AbstractActionExt("toggle sorter order") { public void actionPerformed(ActionEvent e) { table.toggleSortOrder(0); } }; JXFrame frame = wrapWithScrollingInFrame(table, "sort icon"); addAction(frame, action); frame.setVisible(true); } /** * Issue #393-swingx: localized NumberEditor. * * Playing ... looks working :-) * * */ public void interactiveFloatingPointEditor(){ DefaultTableModel model = new DefaultTableModel( new String[] {"Double-core", "Double-ext", "Integer-core", "Integer-ext", "Object"}, 10) { @Override public Class getColumnClass(int columnIndex) { if ((columnIndex == 0) || (columnIndex == 1)) { return Double.class; } if ((columnIndex == 2) || (columnIndex == 3)){ return Integer.class; } return Object.class; } }; final JXTable table = new JXTable(model); table.setSurrendersFocusOnKeystroke(true); table.setValueAt(10.2, 0, 0); table.setValueAt(10.2, 0, 1); table.setValueAt(10, 0, 2); table.setValueAt(10, 0, 3); NumberEditor numberEditor = new NumberEditor(); table.getColumn(0).setCellEditor(numberEditor); table.getColumn(2).setCellEditor(numberEditor); showWithScrollingInFrame(table, "Extended NumberEditors (col 1/3)"); } /** * Issue #??-swingx: default number editor shows 3 digits only. * * Compare with plain JFromattedTextField and default NumberFormat - same. * To see, type a number with fractional digits > 3 in the first text field * and press commit or transfer focus away. */ public void interactiveFloatingPointEditorDigits(){ DefaultTableModel model = new DefaultTableModel( new String[] {"Double-default", "Double-customMaxDigits"}, 10) { @Override public Class getColumnClass(int columnIndex) { if ((columnIndex == 0) || (columnIndex == 1)) { return Double.class; } if ((columnIndex == 2) || (columnIndex == 3)){ return Integer.class; } return Object.class; } }; final JXTable table = new JXTable(model); table.setSurrendersFocusOnKeystroke(true); table.setValueAt(10.2, 0, 0); table.setValueAt(10.2, 0, 1); NumberFormat moreFractionalDigits = NumberFormat.getInstance(); moreFractionalDigits.setMaximumFractionDigits(20); NumberEditorExt numberEditor = new NumberEditorExt(moreFractionalDigits); table.getColumn(1).setCellEditor(numberEditor); JXFrame frame = showWithScrollingInFrame(table, "Extended NumberEditors (col 1/3)"); Format format = NumberFormat.getInstance(); final JFormattedTextField field = new JFormattedTextField(format); field.setColumns(10); final JFormattedTextField target = new JFormattedTextField(format); target.setColumns(10); field.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { target.setValue(field.getValue()); LOG.info("value: " + field.getValue()); } }); FocusAdapter focusAdapter = new FocusAdapter() { @Override public void focusLost(FocusEvent e) { LOG.info("field value: " + field.getValue()); LOG.info("table value: " + table.getValueAt(0, 1)); } }; field.addFocusListener(focusAdapter); table.addFocusListener(focusAdapter); addStatusComponent(frame, field); addStatusComponent(frame, target); } /** * Issue #417-swingx: disable default find. * * Possible alternative to introducing disable api as suggested in the * issue report: disable the action? Move the action up the hierarchy to * the parent actionmap? Maybe JX specific parent? * */ public void interactiveDisableFind() { final JXTable table = new JXTable(sortableTableModel); Action findAction = new AbstractActionExt() { public void actionPerformed(ActionEvent e) { SearchFactory.getInstance().showFindDialog(table, table.getSearchable()); } @Override public boolean isEnabled() { return false; } }; table.getActionMap().put("find", findAction); showWithScrollingInFrame(table, "disable finding"); } /** * visually check if we can bind the CCB's action to a keystroke. * * Working, but there's a visual glitch if opened by keystroke: * the popup is not trailing aligned to the CCB. And the * CCB must be visible, otherwise there's an IllegalStateException * because the popup tries to position itself relative to the CCB. * */ public void interactiveKeybindingColumnControl() { JXTable table = new JXTable(sortableTableModel); // JW: currently the CCB must be visible // table.setColumnControlVisible(true); Action openCCPopup = ((AbstractButton) table.getColumnControl()).getAction(); String actionKey = "popupColumnControl"; table.getActionMap().put(actionKey, openCCPopup); KeyStroke keyStroke = KeyStroke.getKeyStroke("F2"); table.getInputMap(JXTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(keyStroke, actionKey); showWithScrollingInFrame(table, "Press F2 to open column control"); } /** * calculate reasonable table rowHeight withouth "white pixel" in editor. * Compare table and xtable */ public void interactiveCompareRowHeight() { JXTable xtable = new JXTable(sortableTableModel); xtable.setShowGrid(false, false); JTable table = new JTable(sortableTableModel); table.setShowHorizontalLines(false); table.setShowVerticalLines(false); table.setRowMargin(0); table.getColumnModel().setColumnMargin(0); JXFrame frame = wrapWithScrollingInFrame(xtable, table, "compare default rowheight of xtable vs. table"); frame.setVisible(true); } /** * visually check if terminateEditOnFocusLost, autoStartEdit * work as expected. * */ public void interactiveToggleEditProperties() { final JXTable table = new JXTable(10, 2); JXFrame frame = wrapWithScrollingInFrame(table, new JButton("something to focus"), "JXTable: toggle terminate/autoStart on left (right is dummy) "); Action toggleTerminate = new AbstractAction("toggleTerminate") { public void actionPerformed(ActionEvent e) { table.setTerminateEditOnFocusLost(!table.isTerminateEditOnFocusLost()); } }; addAction(frame, toggleTerminate); Action toggleAutoStart = new AbstractAction("toggleAutoStart") { public void actionPerformed(ActionEvent e) { table.setAutoStartEditOnKeyStroke(!table.isAutoStartEditOnKeyStroke()); } }; addAction(frame, toggleAutoStart); frame.setVisible(true); } /** * Example: how to implement a custom toggle sort cycle. * unsorted - ascending - descending - unsorted. */ public void interactiveCustomToggleSortOrder() { FilterPipeline myFilterPipeline = new CustomToggleSortOrderFP(); JXTable table = new JXTable(sortableTableModel); table.setFilters(myFilterPipeline); JXFrame frame = wrapWithScrollingInFrame(table, "Custom sort toggle"); frame.setVisible(true); } /** * Example: how to implement a custom toggle sort cycle. * */ public class CustomToggleSortOrderFP extends FilterPipeline { public CustomToggleSortOrderFP() { super(); } public CustomToggleSortOrderFP(Filter[] inList) { super(inList); } @Override protected SortController createDefaultSortController() { return new CustomSortController(); } protected class CustomSortController extends SorterBasedSortController { @Override public void toggleSortOrder(int column, Comparator comparator) { Sorter currentSorter = getSorter(); if ((currentSorter != null) && (currentSorter.getColumnIndex() == column) && !currentSorter.isAscending()) { setSorter(null); } else { super.toggleSortOrder(column, comparator); } } } }; /** * Respect not-sortable column. */ public void interactiveColumnNotSortable() { final JXTable table = new JXTable(sortableTableModel) ; table.setColumnControlVisible(true); table.getColumnExt(0).setSortable(false); JXFrame frame = wrapWithScrollingInFrame(table, "Always sorted"); frame.setVisible(true); } /** * Expose sorted column. * Example how to guarantee one column sorted at all times. */ public void interactiveAlwaysSorted() { final JXTable table = new JXTable(sortableTableModel) { @Override public void columnRemoved(TableColumnModelEvent e) { super.columnRemoved(e); if (!hasVisibleSortedColumn()) { toggleSortOrder(0); } } private boolean hasVisibleSortedColumn() { TableColumn column = getSortedColumn(); if (column instanceof TableColumnExt) { return ((TableColumnExt) column).isVisible(); } // JW: this path is not tested, don't really expect // non-ext column types, though JXTable must // cope with them return column != null; } }; table.setColumnControlVisible(true); JXFrame frame = wrapWithScrollingInFrame(table, "Always sorted"); frame.setVisible(true); } /** * Issue #271-swingx: make sort triggering mouseEvents * customizable. * * added SortGestureRecognizer. * */ public void interactiveSortGestureRecognizer() { final JXTable table = new JXTable(10, 2); JXFrame frame = wrapWithScrollingInFrame(table, "Sort Gesture customization"); Action action = new AbstractAction("toggle default/custom recognizer") { boolean hasCustom; public void actionPerformed(ActionEvent e) { SortGestureRecognizer recognizer = null; if (!hasCustom) { hasCustom = !hasCustom; recognizer = new SortGestureRecognizer() { /** * allow double clicks to trigger a sort. */ @Override public boolean isSortOrderGesture(MouseEvent e) { return e.getClickCount() <= 2; } /** * Disable reset gesture. */ @Override public boolean isResetSortOrderGesture(MouseEvent e) { return false; } /** * ignore modifiers. */ @Override public boolean isToggleSortOrderGesture(MouseEvent e) { return isSortOrderGesture(e); } }; } ((JXTableHeader) table.getTableHeader()).setSortGestureRecognizer(recognizer); } }; addAction(frame, action); frame.setVisible(true); } /** * Issue #281-swingx: header should be auto-repainted on changes to * header title, value. * * */ public void interactiveUpdateHeader() { final JXTable table = new JXTable(10, 2); JXFrame frame = wrapWithScrollingInFrame(table, "update header"); Action action = new AbstractAction("update headervalue") { int count; public void actionPerformed(ActionEvent e) { table.getColumn(0).setHeaderValue("A" + count++); } }; addAction(frame, action); action = new AbstractAction("update column title") { int count; public void actionPerformed(ActionEvent e) { table.getColumnExt(0).setTitle("A" + count++); } }; addAction(frame, action); frame.setVisible(true); } /** * Issue #281-swingx, Issue #334-swing: * header should be auto-repainted on changes to * header title, value. Must update size if appropriate. * * still open: core #4292511 - autowrap not really working * */ public void interactiveUpdateHeaderAndSizeRequirements() { final String[] alternate = { "simple", // "This is a test of a large label to see if it wraps ", // "simple", "

Line 1
Line 2
" }; final JXTable table = new JXTable(10, 2); JXFrame frame = wrapWithScrollingInFrame(table, "update header"); Action action = new AbstractAction("update headervalue") { boolean first; public void actionPerformed(ActionEvent e) { table.getColumn(1).setHeaderValue(first ? alternate[0] : alternate[1]); first = !first; } }; addAction(frame, action); frame.setVisible(true); } /** * Issue #??-swingx: column auto-sizing support. * */ public void interactiveTestExpandsToViewportWidth() { final JXTable table = new JXTable(); ColumnFactory factory = new ColumnFactory() { @Override public void configureTableColumn(TableModel model, TableColumnExt columnExt) { super.configureTableColumn(model, columnExt); if (model.getColumnClass(columnExt.getModelIndex()) == Integer.class) { // to see the effect: excess width is distributed relative // to the difference between maxSize and prefSize columnExt.setMaxWidth(200); } else { columnExt.setMaxWidth(1024); } } }; table.setColumnFactory(factory); table.setColumnControlVisible(true); table.setModel(sortableTableModel); table.setHorizontalScrollEnabled(true); table.packAll(); JXFrame frame = wrapWithScrollingInFrame(table, "expand to width"); Action toggleModel = new AbstractAction("toggle model") { public void actionPerformed(ActionEvent e) { table.setModel(table.getModel() == sortableTableModel ? new DefaultTableModel(20, 4) : sortableTableModel); } }; addAction(frame, toggleModel); frame.setSize(table.getPreferredSize().width - 50, 300); frame.setVisible(true); LOG.info("table: " + table.getWidth()); LOG.info("Viewport: " + table.getParent().getWidth()); } /** * Issue #256-swingx: viewport config. * */ public void interactiveTestFillsViewportHeight() { final JXTable table = new JXTable(10, 2); table.setFillsViewportHeight(true); JXFrame frame = wrapWithScrollingInFrame(table, "toggle viewport height"); frame.setSize(500, table.getPreferredSize().height * 2); Action action = new AbstractAction("toggle fill") { public void actionPerformed(ActionEvent e) { table.setFillsViewportHeight(!table.getFillsViewportHeight()); } }; addAction(frame, action); frame.setVisible(true); } /** * Issue ??: Anchor lost after receiving a structure changed. * Lead/anchor no longer automatically initialized - no visual clue * if table is focused. * */ public void interactiveTestToggleTableModelU6() { final DefaultTableModel tableModel = createAscendingModel(0, 20); final JTable table = new JTable(tableModel); // JW: need to explicitly set _both_ anchor and lead to >= 0 // need to set anchor first table.getSelectionModel().setAnchorSelectionIndex(0); table.getSelectionModel().setLeadSelectionIndex(0); table.getColumnModel().getSelectionModel().setAnchorSelectionIndex(0); table.getColumnModel().getSelectionModel().setLeadSelectionIndex(0); Action toggleAction = new AbstractAction("Toggle TableModel") { public void actionPerformed(ActionEvent e) { TableModel model = table.getModel(); table.setModel(model.equals(tableModel) ? sortableTableModel : tableModel); } }; JXFrame frame = wrapWithScrollingInFrame(table, "JTable - anchor lost after structure changed"); addAction(frame, toggleAction); frame.setVisible(true); frame.pack(); SwingUtilities.invokeLater(new Runnable() { public void run() { // sanity - focus is on table LOG.info("isFocused? " + table.hasFocus()); LOG.info("who has focus? " + KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner()); } }); } /** * Issue #186-swingxProblem with lead/selection and buttons as editors: * - move focus (using arrow keys) to first editable boolean * - press space to toggle boolean * - move focus to next row (same column) * - press space to toggle boolean * - move back to first row (same column) * - press space: boolean is toggled and (that's the problem) * lead selection is moved to next row. * No problem in JTable. * */ public void interactiveTestCompareTableBoolean() { JXTable xtable = new JXTable(createModelWithBooleans()); JTable table = new JTable(createModelWithBooleans()); JXFrame frame = wrapWithScrollingInFrame(xtable, table, "Compare boolean renderer JXTable <--> JTable"); frame.setVisible(true); } private TableModel createModelWithBooleans() { String[] columnNames = { "text only", "Bool editable", "Bool not-editable" }; DefaultTableModel model = new DefaultTableModel(columnNames, 0) { @Override public Class getColumnClass(int column) { return getValueAt(0, column).getClass(); } @Override public boolean isCellEditable(int row, int column) { return !getColumnName(column).contains("not"); } }; for (int i = 0; i < 4; i++) { model.addRow(new Object[] {"text only " + i, Boolean.TRUE, Boolean.TRUE }); } return model; } /** * Issue #89-swingx: ColumnControl not updated with ComponentOrientation. * */ public void interactiveRToLTableWithColumnControl() { final JXTable table = new JXTable(createAscendingModel(0, 20)); JScrollPane pane = new JScrollPane(table); // table.setColumnControlVisible(true); // pane.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); final JXFrame frame = wrapInFrame(pane, "RToLScrollPane"); addComponentOrientationToggle(frame); Action toggleColumnControl = new AbstractAction("toggle column control") { public void actionPerformed(ActionEvent e) { table.setColumnControlVisible(!table.isColumnControlVisible()); } }; addAction(frame, toggleColumnControl); frame.setVisible(true); } public void interactiveTestRowHeightAndSelection() { final JXTable table = new JXTable(sortableTableModel); table.setRowHeightEnabled(true); table.setRowHeight(0, table.getRowHeight() * 2); final int column = 0; table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) return; ListSelectionModel model = (ListSelectionModel) e.getSource(); int selected = model.getMinSelectionIndex(); if (selected < 0) return; System.out.println("from selection: " + table.getValueAt(selected, column)); } }); JXFrame frame = wrapWithScrollingInFrame(table, "Accessing values (indy rowheights)"); Action updateCellAction = new AbstractAction("update cell value") { public void actionPerformed(ActionEvent e) { int anchorRow = table.getSelectionModel().getLeadSelectionIndex(); int anchorCol = table.getColumnModel().getSelectionModel().getLeadSelectionIndex(); if ((anchorRow < 0) || (anchorCol < 0)) return; table.setValueAt("x" + table.getValueAt(anchorRow, anchorCol), anchorRow, anchorCol); } }; addAction(frame, updateCellAction); frame.setVisible(true); } public void interactiveTestRowHeight() { final JXTable table = new JXTable(sortableTableModel); table.setRowHeightEnabled(true); table.setRowHeight(0, table.getRowHeight() * 2); JXFrame frame = wrapWithScrollingInFrame(table, "Individual rowheight"); Action temp = new AbstractAction("empty selection") { public void actionPerformed(ActionEvent e) { table.changeSelection(-1, -1, false, false); } }; addAction(frame, temp); frame.setVisible(true); } /** * Issue #232-swingx: SelectionMapper not updated on changing selectionModel. * visually verify that the mapper keeps the selection after re-setting * table's selectionModel. * * * */ public void interactiveSelectionMapperOnSelectionModelChange() { final JXTable table = new JXTable(sortableTableModel); table.setSelectionModel(new DefaultListSelectionModel()); JXFrame frame = wrapWithScrollingInFrame(table, "SelectionMapper: keep selection on change view model"); // Action temp = new AbstractAction("toggle selectionModel") { // // public void actionPerformed(ActionEvent e) { // table.setSelectionModel(new DefaultListSelectionModel()); // // } // // }; // addAction(frame, temp); frame.setVisible(true); } /** * example mixed sorting (Jens Elkner). * */ public void interactiveTestSorterPatch() { Object[][] fourWheels = new Object[][]{ new Object[] {"Car", new Car(180f)}, new Object[] {"Porsche", new Porsche(170)}, new Object[] {"Porsche", new Porsche(170)}, new Object[] {"Porsche", new Porsche(170, false)}, new Object[] {"Tractor", new Tractor(20)}, new Object[] {"Tractor", new Tractor(10)}, }; DefaultTableModel model = new DefaultTableModel(fourWheels, new String[] {"Text", "Car"}) ; JXTable table = new JXTable(model); JFrame frame = wrapWithScrollingInFrame(table, "Sorter patch"); frame.setVisible(true); } public class Car implements Comparable { float speed = 100; public Car(float speed) { this.speed = speed; } public int compareTo(Car o) { return speed < o.speed ? -1 : speed > o.speed ? 1 : 0; } @Override public String toString() { return "Car - " + speed; } } public class Porsche extends Car { boolean hasBridgeStone = true; public Porsche(float speed) { super(speed); } public Porsche(float speed, boolean bridgeStone) { this(speed); hasBridgeStone = bridgeStone; } @Override public int compareTo(Car o) { if (o instanceof Porsche) { return ((Porsche) o).hasBridgeStone ? 0 : 1; } return super.compareTo(o); } @Override public String toString() { return "Porsche - " + speed + (hasBridgeStone ? "+" : ""); } } public class Tractor implements Comparable { float speed = 20; public Tractor(float speed) { this.speed = speed; } public int compareTo(Tractor o) { return speed < o.speed ? -1 : speed > o.speed ? 1 : 0; } @Override public String toString() { return "Tractor - " + speed; } } /** * Issue #179: Sorter does not use collator if cell content is * a String. * */ public void interactiveTestLocaleSorter() { Object[][] rowData = new Object[][] { new Object[] { Boolean.TRUE, "aa" }, new Object[] { Boolean.FALSE, "AB" }, new Object[] { Boolean.FALSE, "AC" }, new Object[] { Boolean.TRUE, "BA" }, new Object[] { Boolean.FALSE, "BB" }, new Object[] { Boolean.TRUE, "BC" } }; String[] columnNames = new String[] { "Critical", "Task" }; DefaultTableModel model = new DefaultTableModel(rowData, columnNames); // { // public Class getColumnClass(int column) { // return column == 1 ? String.class : super.getColumnClass(column); // } // }; final JXTable table = new JXTable(model); table.toggleSortOrder(1); JFrame frame = wrapWithScrollingInFrame(table, "locale sorting"); frame.setVisible(true); } /** * Issue #??: Problems with filters and ColumnControl * * - sporadic ArrayIndexOOB after sequence: * filter(column), sort(column), hide(column), setFilter(null) * * - filtering invisible columns? Unclear state transitions. * */ public void interactiveTestColumnControlAndFilters() { final JXTable table = new JXTable(sortableTableModel); // hmm bug regression with combos as editors - same in JTable // JComboBox box = new JComboBox(new Object[] {"one", "two", "three" }); // box.setEditable(true); // table.getColumnExt(0).setCellEditor(new DefaultCellEditor(box)); Action toggleFilter = new AbstractAction("Toggle Filter col. 0") { boolean hasFilters; public void actionPerformed(ActionEvent e) { if (hasFilters) { table.setFilters(null); } else { Filter filter = new PatternFilter("e", 0, 0); table.setFilters(new FilterPipeline(new Filter[] {filter})); } hasFilters = !hasFilters; } }; toggleFilter.putValue(Action.SHORT_DESCRIPTION, "filtering first column - problem if invisible "); table.setColumnControlVisible(true); JXFrame frame = wrapWithScrollingInFrame(table, "JXTable ColumnControl and Filters"); addAction(frame, toggleFilter); frame.setVisible(true); } /** * Issue #55-swingx: NPE on setModel if sorter in pipeline and new * model getColumnCount() < sorter.getColumnIndex(). * */ public void interactiveSetModelFilter() { final DefaultTableModel model = createAscendingModel(0, 20, 3, true); final AncientSwingTeam ancientSwingTeam = new AncientSwingTeam(); final JXTable table = new JXTable(ancientSwingTeam); Sorter sorter = new ShuttleSorter(3, false); FilterPipeline pipeline = new FilterPipeline(new Filter[] {sorter}); table.setFilters(pipeline); table.setRowHeight(0, 25); Action action = new AbstractAction("toggleModel") { public void actionPerformed(ActionEvent e) { if (table.getModel() == ancientSwingTeam) { table.setModel(model); } else { table.setModel(ancientSwingTeam); } } }; JXFrame frame = wrapWithScrollingInFrame(table, "model update?"); addAction(frame, action); frame.setVisible(true); } /** * @KEEP this is about testing Mustang sorting. */ public void interactiveTestColumnControlAndFiltersRowSorter() { // final JXTable table = new JXTable(sortableTableModel); // // hmm bug regression with combos as editors - same in JTable //// JComboBox box = new JComboBox(new Object[] {"one", "two", "three" }); //// box.setEditable(true); //// table.getColumnExt(0).setCellEditor(new DefaultCellEditor(box)); // Action toggleFilter = new AbstractAction("Toggle RowFilter -contains e- ") { // boolean hasFilters; // public void actionPerformed(ActionEvent e) { // if (hasFilters) { // table.setFilters(null); // } else { // RowSorterFilter filter = new RowSorterFilter(); // filter.setRowFilter(RowFilter.regexFilter(".*e.*", 0)); // table.setFilters(new FilterPipeline(new Filter[] {filter})); // // } // hasFilters = !hasFilters; // } // // }; // toggleFilter.putValue(Action.SHORT_DESCRIPTION, "filtering first column - problem if invisible "); // table.setColumnControlVisible(true); // JFrame frame = wrapWithScrollingInFrame(table, "JXTable ColumnControl and Filters"); // addAction(frame, toggleFilter); // frame.setVisible(true); } /** * Issue #155-swingx: vertical scrollbar policy lost. * */ public void interactiveTestColumnControlConserveVerticalScrollBarPolicyAlways() { final JXTable table = new JXTable(); Action toggleAction = new AbstractAction("Toggle Control") { public void actionPerformed(ActionEvent e) { table.setColumnControlVisible(!table.isColumnControlVisible()); } }; table.setModel(new DefaultTableModel(10, 5)); // initial state of column control visibility doesn't seem to matter // table.setColumnControlVisible(true); final JScrollPane scrollPane1 = new JScrollPane(table); scrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); final JXFrame frame = wrapInFrame(scrollPane1, "JXTable Vertical ScrollBar Policy - always"); addAction(frame, toggleAction); Action packAction = new AbstractAction("Pack frame") { public void actionPerformed(ActionEvent e) { frame.remove(scrollPane1); frame.add(scrollPane1); } }; addAction(frame, packAction); frame.setVisible(true); } /** * Issue #155-swingx: vertical scrollbar policy lost. * */ public void interactiveTestColumnControlConserveVerticalScrollBarPolicyNever() { final JXTable table = new JXTable(); Action toggleAction = new AbstractAction("Toggle Control") { public void actionPerformed(ActionEvent e) { table.setColumnControlVisible(!table.isColumnControlVisible()); } }; table.setModel(new DefaultTableModel(10, 5)); // initial state of column control visibility doesn't seem to matter // table.setColumnControlVisible(true); final JScrollPane scrollPane1 = new JScrollPane(table); scrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); final JXFrame frame = wrapInFrame(scrollPane1, "JXTable Vertical ScrollBar Policy - never"); addAction(frame, toggleAction); Action packAction = new AbstractAction("Pack frame") { public void actionPerformed(ActionEvent e) { frame.remove(scrollPane1); frame.add(scrollPane1); } }; addAction(frame, packAction); frame.setVisible(true); } /** * Issue #11: Column control not showing with few rows. * */ public void interactiveTestColumnControlFewRows() { final JXTable table = new JXTable(); Action toggleAction = new AbstractAction("Toggle Control") { public void actionPerformed(ActionEvent e) { table.setColumnControlVisible(!table.isColumnControlVisible()); } }; table.setModel(new DefaultTableModel(10, 5)); table.setColumnControlVisible(true); JXFrame frame = wrapWithScrollingInFrame(table, "JXTable ColumnControl with few rows"); addAction(frame, toggleAction); frame.setVisible(true); } /** * check behaviour outside scrollPane * */ public void interactiveTestColumnControlWithoutScrollPane() { final JXTable table = new JXTable(); Action toggleAction = new AbstractAction("Toggle Control") { public void actionPerformed(ActionEvent e) { table.setColumnControlVisible(!table.isColumnControlVisible()); } }; toggleAction.putValue(Action.SHORT_DESCRIPTION, "does nothing visible - no scrollpane"); table.setModel(new DefaultTableModel(10, 5)); table.setColumnControlVisible(true); JXFrame frame = wrapInFrame(table, "JXTable: Toggle ColumnControl outside ScrollPane"); addAction(frame, toggleAction); frame.setVisible(true); } /** * check behaviour of moving into/out of scrollpane. * */ public void interactiveTestToggleScrollPaneWithColumnControlOn() { final JXTable table = new JXTable(); table.setModel(new DefaultTableModel(10, 5)); table.setColumnControlVisible(true); final JXFrame frame = wrapInFrame(table, "JXTable: Toggle ScrollPane with Columncontrol on"); Action toggleAction = new AbstractAction("Toggle ScrollPane") { public void actionPerformed(ActionEvent e) { Container parent = table.getParent(); boolean inScrollPane = parent instanceof JViewport; if (inScrollPane) { JScrollPane scrollPane = (JScrollPane) table.getParent().getParent(); frame.getContentPane().remove(scrollPane); frame.getContentPane().add(table); } else { parent.remove(table); parent.add(new JScrollPane(table)); } frame.pack(); } }; addAction(frame, toggleAction); frame.setVisible(true); } /** * TableColumnExt: user friendly resizable * */ public void interactiveTestColumnResizable() { final JXTable table = new JXTable(sortableTableModel); table.setColumnControlVisible(true); final TableColumnExt priorityColumn = table.getColumnExt("First Name"); JXFrame frame = wrapWithScrollingInFrame(table, "JXTable: Column with Min=Max not resizable"); Action action = new AbstractAction("Toggle MinMax of FirstName") { public void actionPerformed(ActionEvent e) { // user-friendly resizable flag if (priorityColumn.getMinWidth() == priorityColumn.getMaxWidth()) { priorityColumn.setMinWidth(50); priorityColumn.setMaxWidth(150); } else { priorityColumn.setMinWidth(100); priorityColumn.setMaxWidth(100); } } }; addAction(frame, action); frame.setVisible(true); } //--------------------------------- /** * quick check if multiple comparators per column work. * Basically yes, with a slight tweak: need to comment guarding * code in filterpipeline throwing exceptions. * * So commented the body for now, need to enquire why the guard * was added in the first place. * * @KEEP */ public void interactiveMultipleComparatorsPerColumn() { // JXTable table = new JXTable(createSplittableValues()); // Sorter sorter1 = new ShuttleSorter(0, false); // sorter1.setComparator(new ClassComparator(0)); // Sorter sorter2 = new ShuttleSorter(0, true ); // sorter2.setComparator(new ClassComparator(1)); // // FilterPipeline pipeline = new FilterPipeline(new Filter[] { sorter1, sorter2 }); // table.setFilters(pipeline); // JXFrame frame = wrapWithScrollingInFrame(table, "MultipleSorter per Column"); // frame.setVisible(true); } /** * @KEEP - this is used in the commented method above. */ // private TableModel createSplittableValues() { // String[] values = {"avalue:zvalue", "avalue:yvalue", "avalue:xvalue", // "bvalue:zvalue", "bvalue:yvalue", "bvalue:xvalue", // "cvalue:zvalue", "cvalue:yvalue", "cvalue:xvalue", // }; // DefaultTableModel model = new DefaultTableModel(values.length, 1); // for (int i = 0; i < values.length; i++) { // model.setValueAt(values[i], i, 0); // } // return model; //} public class ClassComparator implements Comparator { List packageOrder; int sortIndex; public ClassComparator(int index) { this.sortIndex = index; } public int compare(Object o1, Object o2) { String[] value1 = String.valueOf(o1).split(":"); String[] value2 = String.valueOf(o2).split(":"); String part1 = value1.length > sortIndex ? value1[sortIndex] : ""; String part2 = value2.length > sortIndex ? value2[sortIndex] : ""; return part1.compareTo(part2); } } /** * Issue #31 (swingx): clicking header must not sort if table !enabled. * */ public void interactiveTestDisabledTableSorting() { final JXTable table = new JXTable(sortableTableModel); table.setEnabled(false); table.setColumnControlVisible(true); Action toggleAction = new AbstractAction("Toggle Enabled") { public void actionPerformed(ActionEvent e) { table.setEnabled(!table.isEnabled()); } }; JXFrame frame = wrapWithScrollingInFrame(table, "Disabled tabled: no sorting"); addAction(frame, toggleAction); frame.setVisible(true); } /** * Issue #191: sorting and custom renderer * not reproducible ... * */ public void interactiveTestCustomRendererSorting() { JXTable table = new JXTable(sortableTableModel); TableColumn column = table.getColumn("No."); TableCellRenderer renderer = new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { value = "# " + value ; Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col ); return comp; } }; column.setCellRenderer(renderer); JFrame frame = wrapWithScrollingInFrame(table, "RendererSortingTest"); frame.setVisible(true); } /** */ public void interactiveTestToggleSortable() { final JXTable table = new JXTable(sortableTableModel); table.setColumnControlVisible(true); Action toggleSortableAction = new AbstractAction("Toggle Sortable") { public void actionPerformed(ActionEvent e) { table.setSortable(!table.isSortable()); } }; JXFrame frame = wrapWithScrollingInFrame(table, "ToggleSortingEnabled Test"); addAction(frame, toggleSortableAction); frame.setVisible(true); } public void interactiveTestTableSizing1() { JXTable table = new JXTable(); table.setAutoCreateColumnsFromModel(false); table.setModel(tableModel); installLinkRenderer(table); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); TableColumnExt columns[] = new TableColumnExt[tableModel.getColumnCount()]; for (int i = 0; i < columns.length; i++) { columns[i] = new TableColumnExt(i); table.addColumn(columns[i]); } columns[0].setPrototypeValue(new Integer(0)); columns[1].setPrototypeValue("Simple String Value"); columns[2].setPrototypeValue(new Integer(1000)); columns[3].setPrototypeValue(Boolean.TRUE); columns[4].setPrototypeValue(new Date(100)); columns[5].setPrototypeValue(new Float(1.5)); columns[6].setPrototypeValue(new LinkModel("Sun Micro", "_blank", tableModel.linkURL)); columns[7].setPrototypeValue(new Integer(3023)); columns[8].setPrototypeValue("John Doh"); columns[9].setPrototypeValue("23434 Testcase St"); columns[10].setPrototypeValue(new Integer(33333)); columns[11].setPrototypeValue(Boolean.FALSE); table.setVisibleRowCount(12); JFrame frame = wrapWithScrollingInFrame(table, "TableSizing1 Test"); frame.setVisible(true); } private void installLinkRenderer(JXTable table) { LinkModelAction action = new LinkModelAction() { @Override public void actionPerformed(ActionEvent e) { LOG.info("activated link: " + getTarget()); } }; TableCellRenderer linkRenderer = new DefaultTableRenderer( new HyperlinkProvider(action, LinkModel.class)); table.setDefaultRenderer(LinkModel.class, linkRenderer); } public void interactiveTestEmptyTableSizing() { JXTable table = new JXTable(0, 5); table.setColumnControlVisible(true); JFrame frame = wrapWithScrollingInFrame(table, "Empty Table (0 rows)"); frame.setVisible(true); } public void interactiveTestTableSizing2() { JXTable table = new JXTable(); table.setAutoCreateColumnsFromModel(false); table.setModel(tableModel); installLinkRenderer(table); TableColumnExt columns[] = new TableColumnExt[6]; int viewIndex = 0; for (int i = columns.length - 1; i >= 0; i--) { columns[viewIndex] = new TableColumnExt(i); table.addColumn(columns[viewIndex++]); } columns[5].setHeaderValue("String Value"); columns[5].setPrototypeValue("9999"); columns[4].setHeaderValue("String Value"); columns[4].setPrototypeValue("Simple String Value"); columns[3].setHeaderValue("Int Value"); columns[3].setPrototypeValue(new Integer(1000)); columns[2].setHeaderValue("Bool"); columns[2].setPrototypeValue(Boolean.FALSE); //columns[2].setSortable(false); columns[1].setHeaderValue("Date"); columns[1].setPrototypeValue(new Date(0)); //columns[1].setSortable(false); columns[0].setHeaderValue("Float"); columns[0].setPrototypeValue(new Float(5.5)); table.setRowHeight(24); table.setRowMargin(2); JFrame frame = wrapWithScrollingInFrame(table, "TableSizing2 Test"); frame.setVisible(true); } public void interactiveTestTableSorter1() { JXTable table = new JXTable(sortableTableModel); table.setBackground(new Color(0xFF, 0xFF, 0xCC)); // notepad table.setGridColor(Color.cyan.darker()); table.setRowHeight(22); table.setRowMargin(1); table.setShowHorizontalLines(true); table.setFilters(new FilterPipeline(new Filter[] { new ShuttleSorter(0, true), // column 0, ascending new ShuttleSorter(1, true), // column 1, ascending })); JFrame frame = wrapWithScrollingInFrame(table, "TableSorter1 col 0= asc, col 1 = asc"); frame.setVisible(true); } public void interactiveTestTableSorter2() { JXTable table = new JXTable(sortableTableModel); table.setBackground(new Color(0xF5, 0xFF, 0xF5)); // ledger table.setGridColor(Color.cyan.darker()); table.setRowHeight(22); table.setRowMargin(1); table.setShowHorizontalLines(true); table.setFilters(new FilterPipeline(new Filter[] { new ShuttleSorter(0, true), // column 0, ascending new ShuttleSorter(1, false), // column 1, descending })); JFrame frame = wrapWithScrollingInFrame(table, "TableSorter2 col 0 = asc, col 1 = desc"); frame.setVisible(true); } @SuppressWarnings("deprecation") public void interactiveTestFocusedCellBackground() { TableModel model = new AncientSwingTeam() { @Override public boolean isCellEditable(int row, int column) { return column != 0; } }; JXTable xtable = new JXTable(model); xtable.setBackground(HighlighterFactory.NOTEPAD); JTable table = new JTable(model); table.setBackground(new Color(0xF5, 0xFF, 0xF5)); // ledger JFrame frame = wrapWithScrollingInFrame(xtable, table, "Unselected focused background: JXTable/JTable"); frame.setVisible(true); } public void interactiveTestTableSorter3() { JXTable table = new JXTable(sortableTableModel); table.setFilters(new FilterPipeline(new Filter[] { new ShuttleSorter(1, true), // column 1, ascending new ShuttleSorter(0, false), // column 0, descending })); JFrame frame = wrapWithScrollingInFrame(table, "TableSorter3 col 1 = asc, col 0 = desc"); frame.setVisible(true); } public void interactiveTestTableSorter4() { JXTable table = new JXTable(sortableTableModel); table.setFilters(new FilterPipeline(new Filter[] { new ShuttleSorter(0, false), // column 0, descending new ShuttleSorter(1, true), // column 1, ascending })); JFrame frame = wrapWithScrollingInFrame(table, "TableSorter4 col 0 = des, col 1 = asc"); frame.setVisible(true); } public void interactiveTestTablePatternFilter1() { JXTable table = new JXTable(tableModel); installLinkRenderer(table); table.setIntercellSpacing(new Dimension(1, 1)); table.setShowGrid(true); table.setFilters(new FilterPipeline(new Filter[] { new PatternFilter("^A", 0, 1) })); JFrame frame = wrapWithScrollingInFrame(table, "TablePatternFilter1 Test"); frame.setVisible(true); } public void interactiveTestTablePatternFilter2() { JXTable table = new JXTable(tableModel); installLinkRenderer(table); table.setIntercellSpacing(new Dimension(2, 2)); table.setShowGrid(true); table.setFilters(new FilterPipeline(new Filter[] { new PatternFilter("^S", 0, 1), new ShuttleSorter(0, false), // column 0, descending })); JFrame frame = wrapWithScrollingInFrame(table, "TablePatternFilter2 Test"); frame.setVisible(true); } public void interactiveTestTablePatternFilter3() { JXTable table = new JXTable(tableModel); installLinkRenderer(table); table.setShowGrid(true); table.setFilters(new FilterPipeline(new Filter[] { new PatternFilter("^S", 0, 1), new ShuttleSorter(1, false), // column 1, descending new ShuttleSorter(0, false), // column 0, descending })); JFrame frame = wrapWithScrollingInFrame(table, "TablePatternFilter3 Test"); frame.setVisible(true); } public void interactiveTestTablePatternFilter4() { JXTable table = new JXTable(tableModel); installLinkRenderer(table); table.setIntercellSpacing(new Dimension(3, 3)); table.setShowGrid(true); table.setFilters(new FilterPipeline(new Filter[] { new PatternFilter("^A", 0, 1), new ShuttleSorter(0, false), // column 0, descending })); JFrame frame = wrapWithScrollingInFrame(table, "TablePatternFilter4 Test"); frame.setVisible(true); } public void interactiveTestTableViewProperties() { JXTable table = new JXTable(tableModel); installLinkRenderer(table); table.setIntercellSpacing(new Dimension(15, 15)); table.setRowHeight(48); JFrame frame = wrapWithScrollingInFrame(table, "TableViewProperties Test"); frame.setVisible(true); } public void interactiveTestTableColumnProperties() { JXTable table = new JXTable(); table.setModel(tableModel); installLinkRenderer(table); table.getTableHeader().setBackground(Color.green); table.getTableHeader().setForeground(Color.magenta); table.getTableHeader().setFont(new Font("Serif", Font.PLAIN, 10)); ColumnHeaderRenderer headerRenderer = ColumnHeaderRenderer.createColumnHeaderRenderer(); headerRenderer.setHorizontalAlignment(JLabel.LEFT); headerRenderer.setBackground(Color.blue); headerRenderer.setForeground(Color.yellow); headerRenderer.setIcon(new Icon() { public int getIconWidth() { return 12; } public int getIconHeight() { return 12; } public void paintIcon(Component c, Graphics g, int x, int y) { g.setColor(Color.red); g.fillOval(0, 0, 10, 10); } }); headerRenderer.setIconTextGap(20); headerRenderer.setFont(new Font("Serif", Font.BOLD, 18)); for (int i = 0; i < table.getColumnCount(); i++) { TableColumnExt column = table.getColumnExt(i); if (i % 3 > 0) { column.setHeaderRenderer(headerRenderer); } if (i % 2 > 0) { TableCellRenderer cellRenderer = table.getNewDefaultRenderer(table.getColumnClass(i)); if (cellRenderer instanceof JLabel || cellRenderer instanceof AbstractButton) { JComponent labelCellRenderer = (JComponent)cellRenderer; labelCellRenderer.setBackground(Color.gray); labelCellRenderer.setForeground(Color.red); if (cellRenderer instanceof JLabel) { ((JLabel) labelCellRenderer).setHorizontalAlignment(JLabel.CENTER); } else { ((AbstractButton) labelCellRenderer).setHorizontalAlignment(JLabel.CENTER); } column.setCellRenderer(cellRenderer); } } } JXFrame frame = wrapWithScrollingInFrame(table, "TableColumnProperties Test"); addStatusMessage(frame, "column properties currently not working"); frame.setVisible(true); } public void interactiveTestEditableHighlight() { JXTable table = new JXTable(tableModel); table.addHighlighter(new ColorHighlighter(HighlightPredicate.EDITABLE, Color.RED, Color.WHITE)); JFrame frame = wrapWithScrollingInFrame(table, "Editability Highlighter Test"); frame.setVisible(true); } public void interactiveColumnHighlighting() { final JXTable table = new JXTable(new AncientSwingTeam()); table.getColumnExt("Favorite Color").setHighlighters(new AbstractHighlighter() { @Override protected Component doHighlight(Component renderer, ComponentAdapter adapter) { Color color = (Color) adapter.getValue(); if (renderer instanceof JComponent) { ((JComponent) renderer).setBorder(BorderFactory.createLineBorder(color)); } return renderer; } }); JFrame frame = wrapWithScrollingInFrame(table, "Column Highlighter Test"); JToolBar bar = new JToolBar(); bar.add(new AbstractAction("Toggle") { boolean state = false; public void actionPerformed(ActionEvent e) { if (state) { table.getColumnExt("No.").setHighlighters(new Highlighter[0]); state = false; } else { table.getColumnExt("No.").addHighlighter( new AbstractHighlighter(new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { return adapter.getValue().toString().contains("8"); } }) { @Override protected Component doHighlight(Component renderer, ComponentAdapter adapter) { Font f = renderer.getFont().deriveFont(Font.ITALIC); renderer.setFont(f); return renderer; } } ); state = true; } } }); frame.add(bar, BorderLayout.NORTH); frame.setVisible(true); } /** * dummy */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/HorizontalLayoutTest.java0000644000175000017500000000227211210401722024744 0ustar tonytony/** * */ package org.jdesktop.swingx; import java.awt.Color; import java.awt.Dimension; import javax.swing.JPanel; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; import junit.framework.TestCase; /** * * @author Karl George Schaefer */ @RunWith(JUnit4.class) public class HorizontalLayoutTest extends TestCase { /** * SwingX Issue #666: incorrect calculation of preferred size. */ @Test public void testLayout() { JPanel panel = new JPanel(new HorizontalLayout()); JPanel p = new JPanel(); p.setOpaque(true); p.setBackground(Color.RED); p.setPreferredSize(new Dimension(50, 25)); panel.add(p); p = new JPanel(); p.setOpaque(true); p.setBackground(Color.WHITE); p.setPreferredSize(new Dimension(125, 15)); panel.add(p); p = new JPanel(); p.setOpaque(true); p.setBackground(Color.BLUE); p.setPreferredSize(new Dimension(30, 30)); panel.add(p); assertEquals(new Dimension(205, 30), panel.getPreferredSize()); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXTipOfTheDayTest.java0000644000175000017500000001240211210401722023773 0ustar tonytony/** * @PROJECT.FULLNAME@ @VERSION@ License. * * Copyright @YEAR@ L2FProd.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jdesktop.swingx; import java.util.Properties; import javax.swing.JTree; import junit.framework.TestCase; import org.jdesktop.swingx.icon.EmptyIcon; import org.jdesktop.swingx.tips.DefaultTip; import org.jdesktop.swingx.tips.DefaultTipOfTheDayModel; import org.jdesktop.swingx.tips.TipLoader; import org.jdesktop.swingx.tips.TipOfTheDayModel; import org.jdesktop.test.PropertyChangeReport; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; @RunWith(JUnit4.class) public class JXTipOfTheDayTest extends TestCase { @Test public void testBean() { PropertyChangeReport report = new PropertyChangeReport(); JXTipOfTheDay totd = new JXTipOfTheDay(); assertEquals(0, totd.getCurrentTip()); // with an empty model next/previous are no-op totd.nextTip(); totd.previousTip(); assertFalse(report.hasEvents(JXTipOfTheDay.CURRENT_TIP_CHANGED_KEY)); totd.addPropertyChangeListener(report); DefaultTipOfTheDayModel model = new DefaultTipOfTheDayModel(); model.add(new DefaultTip("name1", "description1")); model.add(new DefaultTip("name2", "description2")); model.add(new DefaultTip("name3", new EmptyIcon())); model.add(new DefaultTip("name3", new JTree())); totd.setModel(model); assertTrue(report.hasEvents("model")); assertFalse(report.hasEvents(JXTipOfTheDay.CURRENT_TIP_CHANGED_KEY)); assertEquals(0, totd.getCurrentTip()); totd.nextTip(); assertTrue(report.hasEvents(JXTipOfTheDay.CURRENT_TIP_CHANGED_KEY)); assertEquals(1, totd.getCurrentTip()); totd.nextTip(); assertEquals(2, totd.getCurrentTip()); totd.nextTip(); assertEquals(3, totd.getCurrentTip()); // tips cycle when bounds are reached totd.nextTip(); assertEquals(0, totd.getCurrentTip()); totd.previousTip(); assertEquals(3, totd.getCurrentTip()); // do not accept to go outside of tip count bounds try { totd.setCurrentTip(-1); fail("Negative tip!"); } catch (IllegalArgumentException e) { } try { totd.setCurrentTip(totd.getModel().getTipCount()); fail("Over the limit!"); } catch (IllegalArgumentException e) { } // do not accept null model try { totd.setModel(null); fail("Should not reach this code"); } catch (IllegalArgumentException e) { } DefaultTip tip = new DefaultTip(); assertNull(tip.getTip()); assertNull(tip.getTipName()); tip.setTipName("name"); assertEquals("name", tip.getTipName()); tip.setTip("tip"); assertEquals("tip", tip.getTip()); assertEquals(tip.getTipName(), tip.toString()); } @Test public void testTipLoader() { TipOfTheDayModel model; Properties props = new Properties(); // empty properties create empty model model = TipLoader.load(props); assertEquals(0, model.getTipCount()); // one tip with name and description props.put("tip.1.name", "name1"); props.put("tip.1.description", "description1"); model = TipLoader.load(props); assertEquals(1, model.getTipCount()); assertEquals("name1", model.getTipAt(0).getTipName()); assertEquals("description1", model.getTipAt(0).getTip()); // one tip with description only (name is optional) props.put("tip.2.description", "description2"); model = TipLoader.load(props); assertEquals(2, model.getTipCount()); assertEquals("name1", model.getTipAt(0).getTipName()); assertEquals("description1", model.getTipAt(0).getTip()); assertNull(model.getTipAt(1).getTipName()); assertEquals("description2", model.getTipAt(1).getTip()); // one tip with name only, but description is mandatory! props.put("tip.3.name", "name3"); try { model = TipLoader.load(props); assertTrue("Must not get here", false); } catch (IllegalArgumentException e) { // expected } // one missing number in the tip sequence props.put("tip.3.description", "desc3"); props.put("tip.5.description", "desc5"); model = TipLoader.load(props); assertEquals(3, model.getTipCount()); } @Test public void testAddon() throws Exception { // move around all addons TestUtilities.cycleAddons(new JXTipOfTheDay()); } @Test public void testChoice() throws Exception { JXTipOfTheDay.ShowOnStartupChoice noshow = new JXTipOfTheDay.ShowOnStartupChoice() { public boolean isShowingOnStartup() { return false; } public void setShowingOnStartup(boolean showOnStartup) { } }; JXTipOfTheDay totd = new JXTipOfTheDay(); assertFalse(totd.showDialog(null, noshow)); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXTreeVisualCheck.java0000644000175000017500000005374211210401722024050 0ustar tonytony/* * $Id: JXTreeVisualCheck.java,v 1.32 2008/12/23 18:12:37 kschaefe Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JTree; import javax.swing.ToolTipManager; import javax.swing.plaf.basic.BasicTreeUI; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellEditor; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.decorator.AbstractHighlighter; import org.jdesktop.swingx.decorator.ColorHighlighter; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.CompoundHighlighter; import org.jdesktop.swingx.decorator.HighlightPredicate; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.HighlighterFactory; import org.jdesktop.swingx.decorator.PatternPredicate; import org.jdesktop.swingx.decorator.SearchPredicate; import org.jdesktop.swingx.decorator.HighlightPredicate.DepthHighlightPredicate; import org.jdesktop.swingx.renderer.DefaultListRenderer; import org.jdesktop.swingx.renderer.DefaultTreeRenderer; import org.jdesktop.swingx.renderer.IconValues; import org.jdesktop.swingx.renderer.StringValue; import org.jdesktop.swingx.renderer.StringValues; import org.jdesktop.swingx.renderer.WrappingProvider; import org.jdesktop.swingx.test.ActionMapTreeTableModel; import org.jdesktop.swingx.treetable.TreeTableNode; public class JXTreeVisualCheck extends JXTreeUnitTest { @SuppressWarnings("all") private static final Logger LOG = Logger.getLogger(JXTreeVisualCheck.class .getName()); public static void main(String[] args) { // setSystemLF(true); JXTreeVisualCheck test = new JXTreeVisualCheck(); try { // test.runInteractiveTests(); // test.runInteractiveTests("interactive.*RToL.*"); // test.runInteractiveTests("interactive.*Revalidate.*"); // test.runInteractiveTests("interactiveRootExpansionTest"); test.runInteractiveTests("interactive.*UpdateUI.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #862-swingx: JXTree - add api for selection colors. */ public void interactiveSelectionColors() { final JXTree tree = new JXTree(); // use SwingX renderer which is aware of per-tree selection colors tree.setCellRenderer(new DefaultTreeRenderer()); final Color uiBackground = tree.getSelectionBackground(); final Color uiForeground = tree.getSelectionForeground(); Action toggleSelectionColors = new AbstractAction("toggle selection colors") { public void actionPerformed(ActionEvent e) { if (tree.getSelectionBackground() == uiBackground) { tree.setSelectionBackground(Color.BLUE); tree.setSelectionForeground(Color.RED); } else { tree.setSelectionBackground(uiBackground); tree.setSelectionForeground(uiForeground); } } }; JXFrame frame = wrapWithScrollingInFrame(tree, "selection color property in JXTree"); addAction(frame, toggleSelectionColors); show(frame); } /** * Issue #862-swingx: JXTree - add api for selection colors. * Compare with JList repaint behaviour. */ public void interactiveSelectionColorsList() { final JXList tree = new JXList(new Object[]{"one", "two", "three"}); // use SwingX renderer which is aware of per-tree selection colors tree.setCellRenderer(new DefaultListRenderer()); final Color uiBackground = tree.getSelectionBackground(); final Color uiForeground = tree.getSelectionForeground(); Action toggleSelectionColors = new AbstractAction("toggle selection colors") { public void actionPerformed(ActionEvent e) { if (tree.getSelectionBackground() == uiBackground) { tree.setSelectionBackground(Color.BLUE); tree.setSelectionForeground(Color.RED); } else { tree.setSelectionBackground(uiBackground); tree.setSelectionForeground(uiForeground); } } }; JXFrame frame = wrapWithScrollingInFrame(tree, "selection color property - compare list repaint"); addAction(frame, toggleSelectionColors); show(frame); } /** * Requirements * - no icons, use IconValue.NONE * - don't unwrap user object */ public void interactiveNoIconsNoUnwrap() { TreeModel model = new ActionMapTreeTableModel(new JXTable()); JXTree tree = new JXTree(model); StringValue sv = new StringValue() { public String getString(Object value) { if ((value instanceof TreeTableNode) && ((TreeTableNode) value).getColumnCount() > 0) { value = ((TreeTableNode) value).getValueAt(0); } return StringValues.TO_STRING.getString(value); } }; DefaultTreeRenderer renderer = new DefaultTreeRenderer(IconValues.NONE, sv); ((WrappingProvider) renderer.getComponentProvider()).setUnwrapUserObject(false); tree.setCellRenderer(renderer); JXFrame frame = wrapWithScrollingInFrame(tree, "WrappingProvider: no icons, no unwrapped userObject"); frame.pack(); frame.setSize(400, 200); frame.setVisible(true); } /** * * Requirements: * - striping effect on leaf, extend to full width of tree * - striping relative to parent (not absolute position of row) * * Trick (from forum): set the rendering component's pref width * in the renderer. * * Applied to SwingX: * - use a highlighter for the pref width setting * - use a predicate to decide which striping to turn on * * Problem: difficult to get rid off size cache of BasicTreeUI. * * The sizing of the nodes is cached before the actual expansion. * That is the row index is invalid at the time of messaging the * renderer, so decoration which effects the size (like setting pref * f.i.) is ignored. Except for largeModel and fixed row height. * * Note: as is, it cannot cope with RToL component orientation. */ public void interactiveExpandToWidthHighlighter() { final JXTree tree = new JXTree(); tree.setCellRenderer(new DefaultTreeRenderer()); tree.expandRow(3); tree.setRowHeight(20); tree.setLargeModel(true); tree.setRootVisible(false); tree.setShowsRootHandles(true); int indent = ((BasicTreeUI) tree.getUI()).getLeftChildIndent() + ((BasicTreeUI) tree.getUI()).getRightChildIndent(); int depthOffset = getDepthOffset(tree); HighlightPredicate evenChild = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { if (!(adapter.getComponent() instanceof JTree)) return false; TreePath path = ((JTree) adapter.getComponent()).getPathForRow(adapter.row); return path == null ? false : (adapter.row - ((JTree) adapter.getComponent()).getRowForPath(path.getParentPath())) % 2 == 0; } }; HighlightPredicate oddChild = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { if (!(adapter.getComponent() instanceof JTree)) return false; TreePath path = ((JTree) adapter.getComponent()).getPathForRow(adapter.row); return path == null ? false : (adapter.row - ((JTree) adapter.getComponent()).getRowForPath(path.getParentPath())) % 2 == 1; } }; final ExtendToWidthHighlighter extendToWidthHighlighter = new ExtendToWidthHighlighter(null, indent, depthOffset); tree.setHighlighters( new CompoundHighlighter( HighlightPredicate.IS_LEAF, extendToWidthHighlighter, new ColorHighlighter(evenChild, HighlighterFactory.BEIGE, null), new ColorHighlighter(oddChild, HighlighterFactory.LINE_PRINTER, null)), new ColorHighlighter(HighlightPredicate.IS_FOLDER, null, Color.RED) ); final JXFrame frame = wrapWithScrollingInFrame(tree, "tree-wide cell renderer"); Action rootVisible = new AbstractActionExt("toggle root visible") { public void actionPerformed(ActionEvent e) { tree.setRootVisible(!tree.isRootVisible()); extendToWidthHighlighter.setDepthOffset(getDepthOffset(tree)); } }; addAction(frame, rootVisible); Action handleVisible = new AbstractActionExt("toggle handles") { public void actionPerformed(ActionEvent e) { tree.setShowsRootHandles(!tree.getShowsRootHandles()); extendToWidthHighlighter.setDepthOffset(getDepthOffset(tree)); } }; addAction(frame, handleVisible); addComponentOrientationToggle(frame); show(frame, 400, 400); } /** * C&p from BasicTreeUI: adjust the depth to root/handle visibility. * @param tree * @return */ protected int getDepthOffset(JTree tree) { if(tree.isRootVisible()) { if(tree.getShowsRootHandles()) { return 1; } } else if(!tree.getShowsRootHandles()) { return -1; } return 0; } /** * Highlighter which sets the preferredWidth of the renderer relative to the * target component's width. Very special requirement for tree rendering: * extend the coloring all the way from the node to the boundary of the tree. * An alternative would be to us a renderer which is layout in such * a way so by default. */ public static class ExtendToWidthHighlighter extends AbstractHighlighter { private int indent; private int depthOffset; public ExtendToWidthHighlighter(HighlightPredicate predicate, int indent, int depthOffset) { super(predicate); this.indent = indent; this.depthOffset = depthOffset; } public void setDepthOffset(int offset) { if (offset == this.depthOffset) return; this.depthOffset = offset; fireStateChanged(); } @Override protected Component doHighlight(Component component, ComponentAdapter adapter) { Dimension dim = component.getPreferredSize(); int width = adapter.getComponent().getWidth() - (adapter.getDepth() + depthOffset) * indent ; dim.width = Math.max(dim.width, width); component.setPreferredSize(dim); return component; } } public void interactiveExpandWithHighlighters() { JXTree tree = new JXTree(); Highlighter searchHighlighter = new ColorHighlighter(new SearchPredicate("\\Qe\\E"), null, Color.RED); tree.addHighlighter(searchHighlighter); showWithScrollingInFrame(tree, "NPE on tree expand with highlighter"); } /** * visually check if invokesStopCellEditing jumps in on focusLost. * */ public void interactiveToggleEditProperties() { final JXTree table = new JXTree(); table.setEditable(true); DefaultTreeCellEditor editor = new DefaultTreeCellEditor(null, null) { @Override public boolean stopCellEditing() { String value = String.valueOf(getCellEditorValue()); if (value.startsWith("s")) { return false; } return super.stopCellEditing(); } }; table.setCellEditor(editor); JXFrame frame = wrapWithScrollingInFrame(table, new JButton("something to focus"), "JXTree: toggle invokesStopEditing "); Action toggleTerminate = new AbstractAction("toggleInvokesStop") { public void actionPerformed(ActionEvent e) { table.setInvokesStopCellEditing(!table.getInvokesStopCellEditing()); } }; addAction(frame, toggleTerminate); frame.setVisible(true); } /** * visualize editing of the hierarchical column, both * in a tree and a xTree switching CO. * using DefaultXTreeCellEditor. */ public void interactiveXTreeEditingRToL() { JTree tree = new JTree(); tree.setEditable(true); JXTree xTree = new JXTree(); xTree.setCellRenderer(new DefaultTreeRenderer()); xTree.setEditable(true); final JXFrame frame = wrapWithScrollingInFrame(xTree, tree, "XEditing: compare JXTree vs. JTree"); addComponentOrientationToggle(frame); addMessage(frame, "JXTree configured with SwingX renderer/treeEditor"); show(frame); } /** * Issue ??: Background highlighters not working on JXTree. * */ public void interactiveUnselectedFocusedBackground() { JXTree xtree = new JXTree(treeTableModel); xtree.setCellRenderer(new DefaultTreeRenderer()); xtree.setBackground(new Color(0xF5, 0xFF, 0xF5)); JTree tree = new JTree(treeTableModel); tree.setBackground(new Color(0xF5, 0xFF, 0xF5)); JXFrame frame = wrapWithScrollingInFrame(xtree, tree, "Unselected focused background: JXTree/JTree" ); addMessage(frame, "xtree uses swingx renderer"); } /** * Issue #503-swingx: JXList rolloverEnabled disables custom cursor. * * Sanity test for JXTree (looks okay). * */ public void interactiveTestRolloverHighlightCustomCursor() { JXTree tree = new JXTree(treeTableModel); tree.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); tree.setRolloverEnabled(true); tree.setHighlighters(createRolloverHighlighter(true)); showWithScrollingInFrame(tree, "foreground rollover, custom cursor " ); } public void interactiveTestDepthHighlighter() { JXTree tree = new JXTree(treeTableModel); tree.setHighlighters(createDepthHighlighters()); showWithScrollingInFrame(tree, "Depth highlighter" ); } public void interactiveTestEditabilityHighlighter() { JXTree tree = new JXTree(treeTableModel); tree.setEditable(true); tree.setHighlighters(new ColorHighlighter(HighlightPredicate.EDITABLE, Color.WHITE, Color.RED)); showWithScrollingInFrame(tree, "Editability highlighter" ); } /** * Issue ??: Background highlighters not working on JXTree. * * Works with SwingX renderer */ public void interactiveTestRolloverHighlightBackground() { JXTree tree = new JXTree(treeTableModel); tree.setRolloverEnabled(true); tree.setCellRenderer(new DefaultTreeRenderer()); tree.setHighlighters(createRolloverHighlighter(false)); JXFrame frame = wrapWithScrollingInFrame(tree, "Rollover - background " ); addMessage(frame, "here we use a SwingX renderer - backgound okay"); show(frame); } private Highlighter createRolloverHighlighter(boolean useForeground) { Color color = new Color(0xF0, 0xF0, 0xE0); //LegacyHighlighter.ledgerBackground.getBackground(); Highlighter highlighter = new ColorHighlighter( HighlightPredicate.ROLLOVER_ROW, useForeground ? null : color, useForeground ? color.darker() : null); return highlighter; } private Highlighter[] createDepthHighlighters() { Highlighter[] highlighters = new Highlighter[2]; highlighters[0] = new ColorHighlighter(new DepthHighlightPredicate(1), Color.WHITE, Color.RED); highlighters[1] = new ColorHighlighter(new DepthHighlightPredicate(2), Color.WHITE, Color.BLUE); return highlighters; } /** * Issue ??: Background highlighters not working on JXTree. * * It's a problem of core DefaultTreeCellRenderer. SwingX renderers are okay. * */ public void interactiveTestHighlighters() { JXTree tree = new JXTree(treeTableModel); String pattern = "o"; tree.setHighlighters(new ColorHighlighter(new PatternPredicate(pattern, 0), Color.YELLOW, Color.RED), HighlighterFactory.createSimpleStriping(HighlighterFactory.LINE_PRINTER)); JXFrame frame = wrapWithScrollingInFrame(tree, "Foreground/background Highlighter: " + pattern); addMessage(frame, "here we use a core default renderer - background highlighter not working!"); show(frame); } public void interactiveTestToolTips() { JXTree tree = new JXTree(treeTableModel); // JW: don't use this idiom - Stackoverflow... // multiple delegation - need to solve or discourage tree.setCellRenderer(createRenderer()); // JW: JTree does not automatically register itself // should JXTree? ToolTipManager toolTipManager = ToolTipManager.sharedInstance(); toolTipManager.registerComponent(tree); showWithScrollingInFrame(tree, "tooltips"); } private TreeCellRenderer createRenderer() { final TreeCellRenderer delegate = new DefaultTreeCellRenderer(); TreeCellRenderer renderer = new TreeCellRenderer() { public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component result = delegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); ((JComponent) result).setToolTipText(String.valueOf(tree.getPathForRow(row))); return result; } }; return renderer; } /** * test if lineStyle client property is respected by JXTree. * Note that some LFs don't respect anyway (WinLF f.i.) */ public void interactiveTestLineStyle() { JXTree tree = new JXTree(treeTableModel); tree.setDragEnabled(true); tree.putClientProperty("JTree.lineStyle", "None"); showWithScrollingInFrame(tree, "LineStyle Test - none"); } /** * setting tree properties: JXTree is updated properly. */ public void interactiveTestTreeProperties() { final JXTree treeTable = new JXTree(treeTableModel); Action toggleHandles = new AbstractAction("Toggle Handles") { public void actionPerformed(ActionEvent e) { treeTable.setShowsRootHandles(!treeTable.getShowsRootHandles()); } }; Action toggleRoot = new AbstractAction("Toggle Root") { public void actionPerformed(ActionEvent e) { treeTable.setRootVisible(!treeTable.isRootVisible()); } }; treeTable.setRowHeight(22); JXFrame frame = wrapWithScrollingInFrame(treeTable, "Toggle Tree properties "); addAction(frame, toggleRoot); addAction(frame, toggleHandles); show(frame); } /** * Ensure that the root node is expanded if invisible and child added. */ public void interactiveRootExpansionTest() { final DefaultMutableTreeNode root = new DefaultMutableTreeNode("root"); final DefaultTreeModel model = new DefaultTreeModel(root); final JXTree tree = new JXTree(model); tree.setRootVisible(false); assertFalse(tree.isExpanded(new TreePath(root))); Action addChild = new AbstractAction("Add Root Child") { private int counter = 0; public void actionPerformed(ActionEvent e) { root.add(new DefaultMutableTreeNode("Child " + (counter + 1))); model.nodesWereInserted(root, new int[]{counter}); counter++; assertTrue(tree.isExpanded(new TreePath(root))); } }; JXFrame frame = wrapWithScrollingInFrame(tree, "Root Node Expansion Test"); addAction(frame, addChild); show(frame); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXTreeIssues.java0000644000175000017500000003572111210401722023117 0ustar tonytony/* * $Id: JXTreeIssues.java,v 1.17 2009/03/20 15:11:23 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx; import java.awt.Component; import java.awt.Font; import java.awt.event.ActionEvent; import java.io.File; import java.util.Locale; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.AbstractListModel; import javax.swing.Action; import javax.swing.DefaultComboBoxModel; import javax.swing.Icon; import javax.swing.JTree; import javax.swing.ListModel; import javax.swing.plaf.UIResource; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreeCellEditor; import javax.swing.tree.TreeCellRenderer; import org.jdesktop.swingx.decorator.AbstractHighlighter; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.HighlightPredicate; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.renderer.CellContext; import org.jdesktop.swingx.renderer.CheckBoxProvider; import org.jdesktop.swingx.renderer.ComponentProvider; import org.jdesktop.swingx.renderer.DefaultListRenderer; import org.jdesktop.swingx.renderer.DefaultTreeRenderer; import org.jdesktop.swingx.renderer.IconValue; import org.jdesktop.swingx.renderer.StringValue; import org.jdesktop.swingx.renderer.StringValues; import org.jdesktop.swingx.renderer.WrappingIconPanel; import org.jdesktop.swingx.renderer.WrappingProvider; import org.jdesktop.swingx.test.XTestUtils; import org.jdesktop.swingx.tree.DefaultXTreeCellEditor; import org.jdesktop.swingx.tree.DefaultXTreeCellRenderer; import org.junit.Test; /** * Test to expose known issues of JXTree. *

* * Ideally, there would be at least one failing test method per open issue in * the issue tracker. Plus additional failing test methods for not fully * specified or not yet decided upon features/behaviour. *

* * If an issue is fixed and the corresponding methods are passing, they * should be moved over to the XXTest. * * @author Jeanette Winzenburg */ public class JXTreeIssues extends JXTreeUnitTest { @SuppressWarnings("unused") private static final Logger LOG = Logger.getLogger(JXTreeIssues.class .getName()); public static void main(String[] args) { setSystemLF(true); JXTreeIssues test = new JXTreeIssues(); try { // test.runInteractiveTests(); test.runInteractiveTests("interactive.*UpdateUI.*"); // test.runInteractiveTests("interactive.*Icons.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #1061-swingx: renderer/editor inconsistent on startup. * Note: this test will fail once we use an enhanced cellEditor (which can cope with * SwingX default renderers). */ @Test public void testRendererUsedInEditorAfterSet() { TestTree tree = new TestTree(); assertTrue("sanity: editor is of type DefaultXTreeCellEditor", tree.getCellEditor() instanceof DefaultXTreeCellEditor); TreeCellRenderer renderer = new DefaultTreeCellRenderer(); tree.setCellRenderer(renderer); assertSame("sanity: new renderer is wrapped", renderer, tree.getWrappedCellRenderer()); assertSame("editor must be updated with new renderer", renderer, ((DefaultXTreeCellEditor) tree.getCellEditor()).getRenderer()); } /** * Issue #601-swingx: allow LAF to hook in LAF provided renderers. * * Unexpected: plain ol' tree doesn't install UIResource? */ public void testLAFRendererTree() { JTree tree = new JTree(); assertNotNull("default renderer installed", tree.getCellRenderer()); assertTrue("expected UIResource, but was: " + tree.getCellRenderer().getClass(), tree.getCellRenderer() instanceof UIResource); } /** * Issue #601-swingx: allow LAF to hook in LAF provided renderers. * * Unexpected: plain ol' tree doesn't install UIResource? */ public void testLAFRendererXTree() { JXTree tree = new JXTree(); assertNotNull("default renderer installed", tree.getCellRenderer()); assertTrue("expected UIResource, but was: " + tree.getCellRenderer().getClass(), tree.getCellRenderer() instanceof UIResource); } private DefaultTreeRenderer sharedRenderer; ComponentProvider provider; @Override protected void setUp() throws Exception { super.setUp(); provider = new CheckBoxProvider(StringValues.TO_STRING); sharedRenderer = new DefaultTreeRenderer(new WrappingProvider(provider)); } /** * Issue ??-swingx: JXTree must update renderer. * It does ... the renderer comp is never removed from the tree's * rendererPane? Not true - removed at end of paint. * Why is this renderer replaced on LAF-toggle? */ public void interactiveUpdateUIRendererProvider() { JXTree tree = new JXTree(); tree.setCellRenderer(sharedRenderer); showWithScrollingInFrame(tree, "updateUI must update renderer??"); } /** * share in list - okay. */ public void interactiveUpdateUISharedProvider() { JXList list = new JXList(new DefaultComboBoxModel(new String[] {"one", "two", "three"})); list.setCellRenderer(new DefaultListRenderer(provider)); showWithScrollingInFrame(list, "list with shared provider"); } /** * Issue ??-swingx: JXTree must update renderer * share in other tree - okay */ public void interactiveUpdateUIRendererOther() { JXTree tree = new JXTree(); tree.setCellRenderer(sharedRenderer); showWithScrollingInFrame(tree, "updateUI must update renderer"); } /** * Issue #1060-swingx: JXTree must update renderer * * tree renderer not updated if set on the tree (as opposed to using the * default set by the ui-delegate) */ public void interactiveUpdateUICoreTreeDefaultRenderer() { JTree tree = new JTree(); tree.getModel().valueForPathChanged(tree.getPathForRow(0), "core with ui provided renderer"); tree.setEditable(true); JTree treeSetRenderer = new JTree(); treeSetRenderer.getModel().valueForPathChanged(treeSetRenderer.getPathForRow(0), "core with renderer set"); treeSetRenderer.setCellRenderer(new DefaultTreeCellRenderer()); treeSetRenderer.setEditable(true); JXFrame frame = wrapWithScrollingInFrame(tree, treeSetRenderer, "JTree/core renderer: updateUI must update renderer"); addComponentOrientationToggle(frame); show(frame); } /** * Issue #1060-swingx: JXTree must update renderer * * tree renderer not updated if set on the tree (as opposed to using the * default set by the ui-delegate) */ public void interactiveUpdateUIXTreeDefaultRenderer() { JXTree tree = new JXTree(); tree.getModel().valueForPathChanged(tree.getPathForRow(0), "x with ui provided renderer"); tree.setEditable(true); JXTree treeSetRenderer = new JXTree(); treeSetRenderer.getModel().valueForPathChanged(treeSetRenderer.getPathForRow(0), "x with renderer set"); treeSetRenderer.setCellRenderer(new DefaultXTreeCellRenderer()); treeSetRenderer.setEditable(true); JXFrame frame = wrapWithScrollingInFrame(tree, treeSetRenderer, "JXTree/core renderer: updateUI must update renderer"); addComponentOrientationToggle(frame); show(frame); } /** * Issue #1060-swingx: JXTree must update renderer * * tree renderer not updated if set on the tree (as opposed to using the * default set by the ui-delegate) */ public void interactiveUpdateUIXTreeXRenderer() { JXTree treeSetRenderer = new JXTree(); treeSetRenderer.getModel().valueForPathChanged(treeSetRenderer.getPathForRow(0), "x with renderer set"); treeSetRenderer.setCellRenderer(new DefaultTreeRenderer()); treeSetRenderer.setEditable(true); JXFrame frame = wrapWithScrollingInFrame(treeSetRenderer, "JXTree/x renderer: updateUI must update renderer/editor"); addComponentOrientationToggle(frame); show(frame); } /** * Size effecting decoration vs. initial config (in provider). * * Decoration: use highlighter * - works correctly only with largeModel (due to caching issues) * * Config in Provider (usually not recommended): * - override getRendererComponent, width always correct, height only * if enabled via setRowHeight(0) * */ public void interactiveBold() { JXTree tree = new JXTree(); tree.setCellRenderer(new DefaultTreeRenderer()); // tree.setRowHeight(0); tree.setLargeModel(true); final Font bold = tree.getFont().deriveFont(Font.BOLD, 20f); Highlighter hl = new AbstractHighlighter(HighlightPredicate.IS_LEAF) { @Override protected Component doHighlight(Component component, ComponentAdapter adapter) { component.setFont(bold); return component; } }; tree.addHighlighter(hl); JXTree treeP = new JXTree(); treeP.setRowHeight(0); WrappingProvider provider = new WrappingProvider() { @Override public WrappingIconPanel getRendererComponent(CellContext context) { super.getRendererComponent(context); if (context.isLeaf()) { rendererComponent.setFont(bold); } return rendererComponent; } }; treeP.setCellRenderer(new DefaultTreeRenderer(provider)); showWithScrollingInFrame(tree, treeP, "bold font: decorate vs. config"); } /** * Size effecting decoration vs. initial config (in provider). * * For comparison: JXList * * Decoration: use highlighter * - works correctly * * Config in Provider (usually not recommended): * - override getRendererComponent, works correctly * */ public void interactiveBoldList() { final Locale[] locales = Locale.getAvailableLocales(); ListModel model = new AbstractListModel() { public Object getElementAt(int index) { return locales[index]; } public int getSize() { return locales.length; } }; JXList tree = new JXList(model); tree.setCellRenderer(new DefaultListRenderer()); final Font bold = tree.getFont().deriveFont(Font.BOLD, 20f); Highlighter hl = new AbstractHighlighter(HighlightPredicate.EVEN) { @Override protected Component doHighlight(Component component, ComponentAdapter adapter) { component.setFont(bold); return component; } }; tree.addHighlighter(hl); JXList treeP = new JXList(model); WrappingProvider provider = new WrappingProvider() { @Override public WrappingIconPanel getRendererComponent(CellContext context) { super.getRendererComponent(context); if (context.getRow() % 2 == 0) { rendererComponent.setFont(bold); } return rendererComponent; } }; treeP.setCellRenderer(new DefaultListRenderer(provider)); showWithScrollingInFrame(tree, treeP, "bold font: decorate vs. config"); } /** * Issue #242: CCE when setting icons. Not reproducible? * Another issue: icon setting does not repaint (with core default renderer) * Does not work at all with SwingX renderer (not surprisingly, the * delegating renderer in JXTree looks for a core default to wrap). * Think: tree/table should trigger repaint? */ public void interactiveTreeIcons() { final JXTree tree = new JXTree(treeTableModel); final Icon downIcon = XTestUtils.loadDefaultIcon("wellbottom.gif"); final Icon upIcon = XTestUtils.loadDefaultIcon("welltop.gif"); Action toggleClosedIcon = new AbstractAction("Toggle closed icon") { boolean down; public void actionPerformed(ActionEvent e) { if (down) { tree.setClosedIcon(downIcon); } else { tree.setClosedIcon(upIcon); } down = !down; // need to force - but shouldn't that be done in the // tree/table itself? and shouldn't the tree fire a // property change? tree.repaint(); } }; tree.setRowHeight(22); JXFrame frame = wrapWithScrollingInFrame(tree, "Toggle Tree icons "); addAction(frame, toggleClosedIcon); frame.setVisible(true); } /** * use WrappingProvider: custom icons */ public void interactiveProviderIcons() { final JXTree tree = new JXTree(treeTableModel); final Icon downIcon = XTestUtils.loadDefaultIcon("wellbottom.gif"); final Icon upIcon = XTestUtils.loadDefaultIcon("welltop.gif"); final StringValue sv = StringValues.FILE_NAME; IconValue iv = new IconValue() { public Icon getIcon(Object value) { if (sv.getString(value).startsWith("A")) { return downIcon; } else if (sv.getString(value).startsWith("D")) { return upIcon; } return null; } }; tree.setCellRenderer(new DefaultTreeRenderer(iv, sv)); tree.setRowHeight(22); JXFrame frame = wrapWithScrollingInFrame(tree, "IconValue on WrappingProvider"); // addAction(frame, toggleClosedIcon); frame.setVisible(true); } /** * use WrappingProvider: default icons */ public void interactiveProviderStringValue() { final JXTree tree = new JXTree(treeTableModel); final StringValue sv = new StringValue() { public String getString(Object value) { if (value instanceof File) { return ((File) value).getName(); } return StringValues.TO_STRING.getString(value); } }; tree.setCellRenderer(new DefaultTreeRenderer(sv)); tree.setRowHeight(22); JXFrame frame = wrapWithScrollingInFrame(tree, "Custom StringValue on WrappingProvider, default icons"); // addAction(frame, toggleClosedIcon); frame.setVisible(true); } public void testDummy() { // do nothing - it's here let the test pass } } swingx-1.0-src/src/test/org/jdesktop/swingx/test/0000755000175000017500000000000011210401734020671 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/test/TreeTableUtils.java0000644000175000017500000000237711210401722024432 0ustar tonytony/** * */ package org.jdesktop.swingx.test; import java.util.Enumeration; import java.util.Vector; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; import org.jdesktop.swingx.treetable.DefaultTreeTableModel; /** * */ public class TreeTableUtils { private TreeTableUtils() { //does nothing } public static DefaultTreeTableModel convertDefaultTreeModel(DefaultTreeModel model) { Vector v = new Vector(); v.add("A"); DefaultTreeTableModel ttModel = new DefaultTreeTableModel(null, v); ttModel.setRoot(convertDefaultMutableTreeNode((DefaultMutableTreeNode) model.getRoot())); return ttModel; } private static DefaultMutableTreeTableNode convertDefaultMutableTreeNode(DefaultMutableTreeNode node) { DefaultMutableTreeTableNode ttNode = new DefaultMutableTreeTableNode(node.getUserObject()); Enumeration children = node.children(); while (children.hasMoreElements()) { ttNode.add(convertDefaultMutableTreeNode(children.nextElement())); } return ttNode; } } swingx-1.0-src/src/test/org/jdesktop/swingx/test/DateSelectionReport.java0000644000175000017500000000465211210401722025457 0ustar tonytony/* * $Id: DateSelectionReport.java,v 1.7 2008/06/13 14:41:38 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.test; import java.util.Collections; import java.util.LinkedList; import java.util.List; import org.jdesktop.swingx.calendar.DateSelectionModel; import org.jdesktop.swingx.event.DateSelectionEvent; import org.jdesktop.swingx.event.DateSelectionListener; import org.jdesktop.swingx.event.DateSelectionEvent.EventType; /** * A ChangeListener that stores the received ChangeEvents. * */ public class DateSelectionReport implements DateSelectionListener { /** * Holds a list of all received DateSelectionEvents. */ protected List events = Collections.synchronizedList(new LinkedList()); /** * Instantiates a DateSelectionReport. */ public DateSelectionReport() {} /** * Instantiates a DateSelectionReport and registers itself to the given model. * @param model the DateSelectionModel to listen to, must not be null. */ public DateSelectionReport(DateSelectionModel model) { model.addDateSelectionListener(this); } //------------------------ implement DateSelectionListener public void valueChanged(DateSelectionEvent evt) { events.add(0, evt); } // ------------------- accessors public int getEventCount() { return events.size(); } public void clear() { events.clear(); } public boolean hasEvents() { return !events.isEmpty(); } public DateSelectionEvent getLastEvent() { return hasEvents() ? events.get(0) : null; } /** * @return the EventType of the last event or null if no event received. */ public EventType getLastEventType() { return hasEvents() ? getLastEvent().getEventType() : null; } public boolean hasEvent(EventType type) { for (DateSelectionEvent ev : events) { if (ev.getEventType().equals(type)) { return true; } } return false; } public int getEventCount(EventType type) { int count = 0; for (DateSelectionEvent ev : events) { if (ev.getEventType().equals(type)) { count++; } } return count; } } swingx-1.0-src/src/test/org/jdesktop/swingx/test/XTestUtils.java0000644000175000017500000000717211210401722023630 0ustar tonytony/* * $Id: XTestUtils.java,v 1.8 2008/03/31 14:10:16 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.test; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import java.util.Calendar; import java.util.Date; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.Icon; import javax.swing.ImageIcon; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.calendar.CalendarUtils; /** * Static convenience methods for testing. Note that the resources * are available in the test src hierarchy. * * @author Jeanette Winzenburg */ public class XTestUtils { private static final Logger LOG = Logger.getLogger(XTestUtils.class .getName()); private static String IMAGE_DIR = "resources/images/"; private static Class BASE = JXTable.class; private static String IMAGE_NAME = "kleopatra.jpg"; /** * * @return the default icon for the swingx testing context. */ public static Icon loadDefaultIcon() { return loadDefaultIcon(IMAGE_NAME); } /** * * @param name the name relative to the default image package. * @return */ public static Icon loadDefaultIcon(String name) { URL url = BASE.getResource(IMAGE_DIR + name); return new ImageIcon(url); } public static BufferedImage loadDefaultImage() { return loadDefaultImage(IMAGE_NAME); } public static BufferedImage loadDefaultImage(String imageName) { try { return ImageIO.read(BASE.getResource(IMAGE_DIR + imageName)); } catch (IOException e) { LOG.warning("no reason this should happen .... we are "); } return null; } /** * * @param days offset from today * @return the start of the day offset from today by the given value, * of the calendar default instance. */ public static Date getStartOfToday(int days) { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, days); return getStartOfDay(cal); } /** * * @return the start of today of the calendar default instance. */ public static Date getStartOfToday() { return getStartOfDay(Calendar.getInstance()); } /** * Adjusts the given calendar to the start of the * current day and returns its date. *

* Note that the calendar is * changed! This is a convenience wrapper around CalendarUtils.startOfDay, * might be moved there? * * @param cal the calendar to clean * @return the calendar's date with all time elements set to 0 */ public static Date getStartOfDay(Calendar cal) { CalendarUtils.startOfDay(cal); return cal.getTime(); } } swingx-1.0-src/src/test/org/jdesktop/swingx/test/PipelineReport.java0000644000175000017500000000541511210401722024477 0ustar tonytony/* * $Id: PipelineReport.java,v 1.2 2008/06/13 14:41:38 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.test; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.jdesktop.swingx.decorator.PipelineEvent; import org.jdesktop.swingx.decorator.PipelineListener; /** * A ChangeListener that stores the received ChangeEvents. * */ public class PipelineReport implements PipelineListener { /** * Holds a list of all received PropertyChangeEvents. */ protected List events = Collections.synchronizedList(new LinkedList()); protected List orderChanged = Collections.synchronizedList(new LinkedList()); protected List contentsChanged = Collections.synchronizedList(new LinkedList()); protected Map eventMap = Collections.synchronizedMap(new HashMap()); //------------------------ implement PropertyChangeListener public void contentsChanged(PipelineEvent evt) { events.add(0, evt); if (PipelineEvent.SORT_ORDER_CHANGED == evt.getType()) { orderChanged.add(0, evt); } else { contentsChanged.add(0, evt); } if (evt.getSource() != null) { eventMap.put(evt.getSource(), evt); } } public int getEventCount() { return events.size(); } public int getEventCount(int type) { if (PipelineEvent.SORT_ORDER_CHANGED == type) { return orderChanged.size(); } else if (PipelineEvent.CONTENTS_CHANGED == type){ return contentsChanged.size(); } return events.size(); } public void clear() { events.clear(); contentsChanged.clear(); orderChanged.clear(); eventMap.clear(); } public boolean hasEvents() { return !events.isEmpty(); } public PipelineEvent getLastEvent() { return getLastEvent(events); } public PipelineEvent getLastEvent(int type) { List list = events; if (PipelineEvent.CONTENTS_CHANGED == type) { list = contentsChanged; } else if (PipelineEvent.SORT_ORDER_CHANGED == type) { list = orderChanged; } return getLastEvent(list); } private PipelineEvent getLastEvent(List events) { return events.isEmpty() ? null : events.get(0); } public PipelineEvent getEvent(Object source) { return eventMap.get(source); } } swingx-1.0-src/src/test/org/jdesktop/swingx/test/ColumnModelReport.java0000644000175000017500000001132711210401722025147 0ustar tonytony/* * $Id: ColumnModelReport.java,v 1.4 2008/09/30 14:24:23 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.test; import java.beans.PropertyChangeEvent; import java.util.Collections; import java.util.LinkedList; import java.util.List; import javax.swing.event.ChangeEvent; import javax.swing.event.ListSelectionEvent; import javax.swing.event.TableColumnModelEvent; import org.jdesktop.swingx.event.TableColumnModelExtListener; import org.jdesktop.test.PropertyChangeReport; /** * A TableColumnExtListener that stores the received TableColumnEvents and * PropertyChangeEvents originating from the TableColumns contained in the * TableColumnModel. */ public class ColumnModelReport implements TableColumnModelExtListener { /** * Holds a list of all received ValueChangeEvents. */ private List removedEvents = Collections.synchronizedList(new LinkedList()); private List addedEvents = Collections.synchronizedList(new LinkedList()); private List movedEvents = Collections.synchronizedList(new LinkedList()); private List selectionEvents = Collections.synchronizedList(new LinkedList()); private List changeEvents = Collections.synchronizedList(new LinkedList()); // private List columnPropertyEvents = new LinkedList(); private PropertyChangeReport propertyReport = new PropertyChangeReport(); //------------------------ implement TableColumnModelListener public void columnAdded(TableColumnModelEvent e) { addedEvents.add(0, e); } public void columnMarginChanged(ChangeEvent e) { changeEvents.add(0, e); } public void columnMoved(TableColumnModelEvent e) { movedEvents.add(0, e); } public void columnRemoved(TableColumnModelEvent e) { removedEvents.add(0, e); } public void columnSelectionChanged(ListSelectionEvent e) { selectionEvents.add(0, e); } //---------------------- implement TableColumnModelExtListener public void columnPropertyChange(PropertyChangeEvent e) { propertyReport.propertyChange(e); } public boolean hasEvents() { return getEventCount() > 0; } public void clear() { addedEvents.clear(); removedEvents.clear(); movedEvents.clear(); changeEvents.clear(); selectionEvents.clear(); propertyReport.clear(); } public int getEventCount() { return addedEvents.size() + removedEvents.size() + movedEvents.size() + changeEvents.size() + selectionEvents.size() + propertyReport.getEventCount(); } // -------------- access reported TableModelEvents public boolean hasRemovedEvent() { return !removedEvents.isEmpty(); } public TableColumnModelEvent getLastRemoveEvent() { return removedEvents.isEmpty() ? null : removedEvents.get(0); } public boolean hasAddedEvent() { return !addedEvents.isEmpty(); } public TableColumnModelEvent getLastAddEvent() { return addedEvents.isEmpty() ? null : addedEvents.get(0); } public boolean hasChangeEvent() { return !changeEvents.isEmpty(); } public int getChangeEventCount() { return changeEvents.size(); } public ChangeEvent getLastChangeEvent() { return hasChangeEvent() ? changeEvents.get(0) : null; } public boolean hasSelectionEvent() { return !selectionEvents.isEmpty(); } public int getSelectionEventCount() { return selectionEvents.size(); } public ListSelectionEvent getLastSelectionEvent() { return hasSelectionEvent() ? selectionEvents.get(0) : null; } //--------------- access reported propertyChangeEvent public boolean hasColumnPropertyEvent() { return propertyReport.hasEvents(); } public int getColumnPropertyEventCount() { return propertyReport.getEventCount(); } public PropertyChangeEvent getLastColumnPropertyEvent() { return propertyReport.getLastEvent(); } public int getColumnPropertyEventCount(String property) { return propertyReport.getEventCount(property); } public Object getLastColumnPropertyEvent(String property) { return propertyReport.getLastEvent(property); } public PropertyChangeReport getPropertyChangeReport() { return propertyReport; } }swingx-1.0-src/src/test/org/jdesktop/swingx/test/CustomMonthViewUI.java0000644000175000017500000000134511210401722025105 0ustar tonytony/* * Created on 19.12.2007 * */ package org.jdesktop.swingx.test; import java.awt.Color; import javax.swing.JComponent; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.ComponentUI; import org.jdesktop.swingx.plaf.basic.BasicMonthViewUI; /** * * Testing custom ui delegate for JXMonthView. * * @author Jeanette Winzenburg */ public class CustomMonthViewUI extends BasicMonthViewUI { @SuppressWarnings({"UnusedDeclaration"}) public static ComponentUI createUI(JComponent c) { return new CustomMonthViewUI(); } @Override protected void installDefaults() { super.installDefaults(); monthView.setSelectionBackground(new ColorUIResource(Color.MAGENTA)); } }swingx-1.0-src/src/test/org/jdesktop/swingx/test/ComponentTreeTableModel.java0000644000175000017500000001256311210401722026253 0ustar tonytony/* * Created on 20.06.2005 * */ package org.jdesktop.swingx.test; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import javax.swing.tree.TreePath; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.treetable.AbstractTreeTableModel; /** * A static snapshot of a container hierarchy. * * NOTE: does not listen to any property changes of * contained components - cell updates are arbitrary on * repaint only! * * @author Jeanette Winzenburg */ public class ComponentTreeTableModel extends AbstractTreeTableModel { public ComponentTreeTableModel(Container root) { super(root); setRoot(root); } public void setRoot(Container root) { if (root == null) { root = new JXFrame(); } this.root = root; modelSupport.fireNewRoot(); } // ------------------TreeModel @Override public Container getRoot() { // TODO Auto-generated method stub return (Container) super.getRoot(); } public Object getChild(Object parent, int index) { return ((Container) parent).getComponent(index); } public int getChildCount(Object parent) { return parent instanceof Container ? ((Container) parent).getComponentCount() : 0; } public int getIndexOfChild(Object parent, Object child) { Component[] children = ((Container) parent).getComponents(); for (int i = 0; i < children.length; i++) { if (children[i].equals(child)) { return i; } } return -1; } @Override public boolean isLeaf(Object node) { return getChildCount(node) == 0; } /** * This method is called by the "tree" part to render the hierarchical * column.

* * PENDING: currently need to comment to let the treetable show the * correct value. Need to dig why ... * * @param node * the node to convert * @return the {@code node} as a string */ // public String convertValueToText(Object node) { // return String.valueOf(getValueAt(node, getHierarchicalColumn())); // } @Override public void valueForPathChanged(TreePath path, Object newValue) { Object node = path.getLastPathComponent(); setValueAt(newValue, node, getHierarchicalColumn()); } //------------------ TreeTableModel @Override public Class getColumnClass(int column) { switch (column) { case 0: return Object.class; case 1: return Class.class; case 2: return Dimension.class; default: return Object.class; } } public int getColumnCount() { return 3; } @Override public String getColumnName(int column) { switch (column) { case 0: return "Name"; case 1: return "Type"; case 2: return "Size"; default: return "Column " + column; } } public Object getValueAt(Object node, int column) { Component comp = (Component) node; switch (column) { case 0: return comp.getName(); case 1: return comp.getClass(); case 2: return comp.getSize(); default: return null; } } @Override public boolean isCellEditable(Object node, int column) { // fake accessing the node: TreeModel can expect to // be messaged with nodes that belong to the // hierarchical structure // introduced for testing #270-swingx: // NPE for invisible rows (if parent is collapsed. ((Component) node).getName(); return column == 0; } @Override public void setValueAt(Object value, Object node, int column) { if (!isCellEditable(node, column)) return; Component comp = (Component) node; comp.setName(String.valueOf(value)); nodeChanged(comp); } private void nodeChanged(Component comp) { TreePath path = getPathToRoot(comp); modelSupport.firePathChanged(path); } /** * exposed for test convenience. * * @param node * @return a {@code TreePath} representation from {@code root} to * {@code node} */ public TreePath getPathToRoot(Component node) { return new TreePath(getPathToRoot(node, 0)); } private Component[] getPathToRoot(Component node, int depth) { Component[] retNodes; // This method recurses, traversing towards the root in order // size the array. On the way back, it fills in the nodes, // starting from the root and working back to the original node. /* Check for null, in case someone passed in a null node, or they passed in an element that isn't rooted at root. */ if(node == null) { if(depth == 0) return null; else retNodes = new Component[depth]; } else { depth++; if(node == root) retNodes = new Component[depth]; else retNodes = getPathToRoot(node.getParent(), depth); retNodes[retNodes.length - depth] = node; } return retNodes; } } swingx-1.0-src/src/test/org/jdesktop/swingx/test/ActionMapTreeTableModel.java0000644000175000017500000001335211210401722026161 0ustar tonytony/* * $Id: ActionMapTreeTableModel.java,v 1.6 2008/12/03 19:21:11 kschaefe Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.test; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.Vector; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.JComponent; import javax.swing.tree.TreeNode; import org.jdesktop.swingx.treetable.DefaultTreeTableModel; import org.jdesktop.swingx.treetable.TreeTableNode; /** * Convenience TreeTableModel for wrapping an ActionMap hierarchy. * * @author Jeanette Winzenburg, Berlin */ public class ActionMapTreeTableModel extends DefaultTreeTableModel { public ActionMapTreeTableModel(JComponent comp) { super(); setRoot(createRootNodeExt(comp)); Vector names = new Vector(); names.add("Key Name"); names.add("Action Name"); names.add("Action Command"); setColumnIdentifiers(names); } private ActionEntryNode createRootNodeExt(JComponent comp) { ActionMap map = comp.getActionMap(); if (map == null) throw new IllegalArgumentException("Component must have ActionMap"); List actionMaps = new ArrayList(); actionMaps.add(map); while ((map = map.getParent()) != null) { actionMaps.add(0, map); } return createActionEntryNodes(actionMaps); } private ActionEntryNode createActionEntryNodes(List actionMaps) { ActionMap topLevel = (ActionMap) actionMaps.get(0); ActionEntryNode mapRoot = new ActionEntryNode("topLevel", topLevel, null); ActionEntryNode current = mapRoot; for (int i = 1; i < actionMaps.size(); i++) { current = current.addActionMapAsChild("childMap " + i, (ActionMap) actionMaps.get(i)); } return mapRoot; } private static class ActionEntryNode implements TreeTableNode { ActionEntryNode parent; Object key; Action action; ActionMap actionMap; List children; public ActionEntryNode(Object key, Action action, ActionEntryNode parent) { this.parent = parent; this.key = key; this.action = action; children = Collections.emptyList(); } public ActionEntryNode(Object key, ActionMap map, ActionEntryNode parent) { this.parent = parent; this.key = key; this.actionMap = map; children = new ArrayList(); Object[] keys = map.keys(); for (int i = 0; i < keys.length; i++) { children.add(new ActionEntryNode(keys[i], (Action) map .get(keys[i]), this)); } } /** * pre: !isLeaf * * @param key * @param map */ public ActionEntryNode addActionMapAsChild(Object key, ActionMap map) { ActionEntryNode actionEntryNode = new ActionEntryNode(key, map, this); getChildren().add(0, actionEntryNode); return actionEntryNode; } public List getChildren() { return children; } public ActionMap getActionMap() { return actionMap; } public Action getAction() { return action; } public String toString() { return key.toString(); } // --------------- implement TreeNode public boolean isLeaf() { return action != null; } public boolean getAllowsChildren() { return !isLeaf(); } public int getChildCount() { return children.size(); } public int getIndex(TreeNode node) { return children.indexOf(node); } //------------- implement re-defined methods of TreeNode public Enumeration children() { return Collections.enumeration(children); } public TreeTableNode getChildAt(int childIndex) { return children.get(childIndex); } public TreeTableNode getParent() { return parent; } //---------------- implement TreeTableNode public Class getColumnClass(int index) { return Object.class; } public int getColumnCount() { return 2; } public Object getValueAt(int column) { ActionEntryNode actionNode = this; switch (column) { case 0: return actionNode.key; case 1: if (actionNode.isLeaf()) return actionNode.getAction().getValue(Action.NAME); return null; case 2: if (actionNode.isLeaf()) return actionNode.getAction().getValue( Action.ACTION_COMMAND_KEY); // case 3: // return "Modification Date"; default: return null; } } public boolean isEditable(int column) { return false; } public void setValueAt(Object aValue, int column) { // do nothing } public Object getUserObject() { return getAction(); } public void setUserObject(Object userObject) { // TODO Auto-generated method stub } } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXTipOfTheDayVisualCheck.java0000644000175000017500000001040411210401722025255 0ustar tonytony/* * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.event.ActionEvent; import java.util.Locale; import javax.swing.AbstractAction; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JTree; import org.jdesktop.swingx.plaf.basic.BasicTipOfTheDayUI; import org.jdesktop.swingx.tips.DefaultTip; import org.jdesktop.swingx.tips.DefaultTipOfTheDayModel; import org.jdesktop.swingx.tips.TipOfTheDayModel; /** * Simple tests to ensure that the {@code JXDatePicker} can be instantiated and * displayed. * * @author Karl Schaefer */ public class JXTipOfTheDayVisualCheck extends InteractiveTestCase { public JXTipOfTheDayVisualCheck() { super("JXLoginPane Test"); } public static void main(String[] args) throws Exception { // setSystemLF(true); JXTipOfTheDayVisualCheck test = new JXTipOfTheDayVisualCheck(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #538-swingx Failure to set locale at runtime * */ public void interactiveDisplay() { JXTipOfTheDay tip = new JXTipOfTheDay(createTipOfTheDayModel()); tip.showDialog(new JFrame()); // showInFrame(new JXTipOfTheDay(), "tip"); } private TipOfTheDayModel createTipOfTheDayModel() { // Create a tip model with some tips DefaultTipOfTheDayModel tips = new DefaultTipOfTheDayModel(); // plain text tips .add(new DefaultTip( "tip1", "This is the first tip " + "This is the first tip " + "This is the first tip " + "This is the first tip " + "This is the first tip " + "This is the first tip\n" + "This is the first tip " + "This is the first tip")); // html text tips .add(new DefaultTip( "tip2", "This is an html TIP

" + "" + "" + "" + "" + "
1entry 1
2entry 2
3entry 3
")); // a Component tips.add(new DefaultTip("tip3", new JTree())); // an Icon tips .add(new DefaultTip( "tip 4", new ImageIcon(BasicTipOfTheDayUI.class.getResource("resources/TipOfTheDay24.gif")))); return tips; } @Override protected void createAndAddMenus(JMenuBar menuBar, final JComponent component) { super.createAndAddMenus(menuBar, component); JMenu menu = new JMenu("Locales"); menu.add(new AbstractAction("Change Locale") { public void actionPerformed(ActionEvent e) { if (component.getLocale() == Locale.FRANCE) { component.setLocale(Locale.ENGLISH); } else { component.setLocale(Locale.FRANCE); } }}); menuBar.add(menu); } /** * Do nothing, make the test runner happy * (would output a warning without a test fixture). * */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXEditorPaneVisualCheck.java0000644000175000017500000003475711210401722025210 0ustar tonytony/* * $Id: JXEditorPaneVisualCheck.java,v 1.3 2008/12/05 14:34:58 kschaefe Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Dimension; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.JEditorPane; import javax.swing.JToolBar; import javax.swing.ListModel; import javax.swing.event.ListDataListener; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.action.ActionContainerFactory; import org.jdesktop.swingx.action.ActionFactory; import org.jdesktop.swingx.action.ActionManager; /** * A unit test for the JXEditorPane * * @author Mark Davidson */ public class JXEditorPaneVisualCheck extends JXEditorPaneTest { @SuppressWarnings("all") private static final Logger LOG = Logger.getLogger(JXEditorPaneVisualCheck.class .getName()); private static String testText = "This is an example of some text"; public static void main(String[] args) throws Exception { // setSystemLF(true); JXEditorPaneVisualCheck test = new JXEditorPaneVisualCheck(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Table.*"); // test.runInteractiveTests("interactive.*List.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #289-swingx: JXEditorPane actions should be disabled if not * applicable. * checking action enabled behaviour of core editorpane. * Doing nothing to enable/disable depending on editable state? * */ public void interactiveXEditorStyledActions() { URL url = JXEditorPaneVisualCheck.class.getResource("resources/test.html"); JXEditorPane editor = null; try { editor = new JXEditorPane(url); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } editor.setEditable(false); editor.setPreferredSize(new Dimension(600, 400)); // JXEditorPane editor = new JXEditorPane(); Action[] actions = editor.getActions(); ActionManager manager = ActionManager.getInstance(); List actionNames = new ArrayList(); StringBuffer buffer = new StringBuffer("No. of default actions: " + actions.length); ActionMap map = editor.getActionMap(); Object[] keys = map.keys(); int count = keys != null ? keys.length : 0; buffer.append("\n No. of actions in ActionMap: " + count); for (int i = 0; i < actions.length; i++) { // TODO: are names allowed to be anything else as String? // same question in other test methods as well Object id = actions[i].getValue(Action.NAME); // ?? the id in the actionManager is doc'ed as ACTION_COMMAND? // which would imply to be a String (assumption somewhere in core) manager.addAction(id, actions[i]); actionNames.add(id); buffer.append("\n" + actions[i].toString()); } editor.setText(buffer.toString()); ActionContainerFactory factory = new ActionContainerFactory(manager); JToolBar toolbar = factory.createToolBar(actionNames); toolbar.setOrientation(JToolBar.VERTICAL); editor.setEditable(false); editor.setPreferredSize(new Dimension(600, 400)); JXList list = new JXList(); list.setFilterEnabled(true); list.setModel(createListModel(actionNames)); JXFrame frame = wrapWithScrollingInFrame(editor, list, "Looking at swingx editor default and styled actions"); frame.getContentPane().add(toolbar, BorderLayout.WEST); frame.setVisible(true); } private ListModel createListModel(final List actionNames) { ListModel model = new ListModel() { public int getSize() { return actionNames.size(); } public Object getElementAt(int index) { return actionNames.get(index); } public void addListDataListener(ListDataListener l) { // TODO Auto-generated method stub } public void removeListDataListener(ListDataListener l) { // TODO Auto-generated method stub } }; return model; } /** * Issue #289-swingx: JXEditorPane actions should be disabled if not * applicable. * checking action enabled behaviour of core editorpane. * Doing nothing to enable/disable depending on editable state? * */ public void interactiveXEditorDefaultActions() { URL url = JXEditorPaneVisualCheck.class.getResource("resources/test.html"); JXEditorPane editor = null; try { editor = new JXEditorPane(url); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } editor.setEditable(false); editor.setPreferredSize(new Dimension(600, 400)); Action[] actions = editor.getActions(); ActionManager manager = ActionManager.getInstance(); List actionNames = new ArrayList(); StringBuffer buffer = new StringBuffer("No. of default actions: " + actions.length); ActionMap map = editor.getActionMap(); Object[] keys = map.keys(); int count = keys != null ? keys.length : 0; buffer.append("\n No. of actions in ActionMap: " + count); for (int i = 0; i < actions.length; i++) { Object id = actions[i].getValue(Action.NAME); manager.addAction(id, actions[i]); actionNames.add(id); buffer.append("\n" + actions[i].toString()); } editor.setText(buffer.toString()); ActionContainerFactory factory = new ActionContainerFactory(manager); JToolBar toolbar = factory.createToolBar(actionNames); toolbar.setOrientation(JToolBar.VERTICAL); editor.setEditable(false); editor.setPreferredSize(new Dimension(600, 400)); JXFrame frame = wrapWithScrollingInFrame(editor, "Looking at swingx editor default actions"); frame.getContentPane().add(toolbar, BorderLayout.WEST); frame.setVisible(true); } /** * Issue #289-swingx: JXEditorPane actions should be disabled if not * applicable. * checking action enabled behaviour of core editorpane. * Doing nothing to enable/disable depending on editable state? * */ public void interactiveEditorDefaultActions() { JEditorPane editor = new JEditorPane(); editor.setText(testText); Action[] actions = editor.getActions(); ActionManager manager = ActionManager.getInstance(); List actionNames = new ArrayList(); StringBuffer buffer = new StringBuffer("No. of default actions: " + actions.length); ActionMap map = editor.getActionMap(); Object[] keys = map.keys(); int count = keys != null ? keys.length : 0; buffer.append("\n No. of actions in ActionMap: " + count); for (int i = 0; i < actions.length; i++) { Object id = actions[i].getValue(Action.NAME); manager.addAction(id, actions[i]); actionNames.add(id); buffer.append("\n" + actions[i].toString()); } editor.setText(buffer.toString()); ActionContainerFactory factory = new ActionContainerFactory(manager); JToolBar toolbar = factory.createToolBar(actionNames); toolbar.setOrientation(JToolBar.VERTICAL); editor.setEditable(false); editor.setPreferredSize(new Dimension(600, 400)); JXFrame frame = wrapWithScrollingInFrame(editor, "Looking at core default actions"); frame.getContentPane().add(toolbar, BorderLayout.WEST); frame.setVisible(true); } /** * JW: this is oold - no idea if that's the way to handle actions!. * */ public void interactiveXEditorActions() { //AbstractActionExt[] actions = new AbstractActionExt[14]; List actions = new ArrayList(); actions.add(ActionFactory.createTargetableAction("cut-to-clipboard", "Cut", "C")); actions.add(ActionFactory.createTargetableAction("copy-to-clipboard", "Copy", "P")); actions.add(ActionFactory.createTargetableAction("paste-from-clipboard", "Paste", "T")); actions.add(ActionFactory.createTargetableAction("undo", "Undo", "U")); actions.add(ActionFactory.createTargetableAction("redo", "Redo", "R")); actions.add(ActionFactory.createTargetableAction("insert-break", "LF", "F")); actions.add(ActionFactory.createTargetableAction("left-justify", "Left", "L", true, "position-group")); actions.add(ActionFactory.createTargetableAction("center-justify", "Center", "C", true, "position-group")); actions.add(ActionFactory.createTargetableAction("right-justify", "Right", "R", true, "position-group")); actions.add(ActionFactory.createTargetableAction("font-bold", "Bold", "B", true)); actions.add(ActionFactory.createTargetableAction("font-italic", "Italic", "I", true)); actions.add(ActionFactory.createTargetableAction("font-underline", "Underline", "U", true)); actions.add(ActionFactory.createTargetableAction("InsertUnorderedList", "UL", "U", true)); actions.add(ActionFactory.createTargetableAction("InsertOrderedList", "OL", "O", true)); actions.add(ActionFactory.createTargetableAction("InsertHR", "HR", "H")); ActionManager manager = ActionManager.getInstance(); List actionNames = new ArrayList(); for (AbstractActionExt ext : actions) { manager.addAction(ext); actionNames.add(ext.getActionCommand()); } // Populate the toolbar. Must use the ActionContainerFactory to ensure // that toggle actions are supported. ActionContainerFactory factory = new ActionContainerFactory(manager); JToolBar toolbar = factory.createToolBar(actionNames); URL url = JXEditorPaneVisualCheck.class.getResource("resources/test.html"); JXEditorPane editor = null; try { editor = new JXEditorPane(url); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } editor.setEditable(false); editor.setPreferredSize(new Dimension(600, 400)); // toolbar.add(editor.getParagraphSelector()); JXFrame frame = wrapWithScrollingInFrame(editor, "Swingx Editor tester"); frame.getContentPane().add(toolbar, BorderLayout.NORTH); frame.pack(); frame.setVisible(true); } /** * JW: this is oold - no idea if that's the way to handle actions!. * */ public void interactiveEditorActions() { //AbstractActionExt[] actions = new AbstractActionExt[14]; List actions = new ArrayList(); // actions.add(ActionFactory.createTargetableAction("cut-to-clipboard", "Cut", "C")); // actions.add(ActionFactory.createTargetableAction("copy-to-clipboard", "Copy", "P")); // actions.add(ActionFactory.createTargetableAction("paste-from-clipboard", "Paste", "T")); actions.add(ActionFactory.createTargetableAction("cut", "Cut", "C")); actions.add(ActionFactory.createTargetableAction("copy", "Copy", "P")); actions.add(ActionFactory.createTargetableAction("paste", "Paste", "T")); actions.add(ActionFactory.createTargetableAction("undo", "Undo", "U")); actions.add(ActionFactory.createTargetableAction("redo", "Redo", "R")); actions.add(ActionFactory.createTargetableAction("insert-break", "LF", "F")); actions.add(ActionFactory.createTargetableAction("left-justify", "Left", "L", true, "position-group")); actions.add(ActionFactory.createTargetableAction("center-justify", "Center", "C", true, "position-group")); actions.add(ActionFactory.createTargetableAction("right-justify", "Right", "R", true, "position-group")); actions.add(ActionFactory.createTargetableAction("font-bold", "Bold", "B", true)); actions.add(ActionFactory.createTargetableAction("font-italic", "Italic", "I", true)); actions.add(ActionFactory.createTargetableAction("font-underline", "Underline", "U", true)); actions.add(ActionFactory.createTargetableAction("InsertUnorderedList", "UL", "U", true)); actions.add(ActionFactory.createTargetableAction("InsertOrderedList", "OL", "O", true)); actions.add(ActionFactory.createTargetableAction("InsertHR", "HR", "H")); ActionManager manager = ActionManager.getInstance(); List actionNames = new ArrayList(); for (AbstractActionExt ext : actions) { manager.addAction(ext); actionNames.add(ext.getActionCommand()); } // Populate the toolbar. Must use the ActionContainerFactory to ensure // that toggle actions are supported. ActionContainerFactory factory = new ActionContainerFactory(manager); JToolBar toolbar = factory.createToolBar(actionNames); URL url = JXEditorPaneVisualCheck.class.getResource("resources/test.html"); JEditorPane editor = null; try { editor = new JEditorPane(url); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } editor.setEditable(false); editor.setPreferredSize(new Dimension(600, 400)); // toolbar.add(editor.getParagraphSelector()); JXFrame frame = wrapWithScrollingInFrame(editor, "Core Editor tester"); frame.getContentPane().add(toolbar, BorderLayout.NORTH); frame.pack(); frame.setVisible(true); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXTableHeaderTest.java0000644000175000017500000002432211210401724024021 0ustar tonytony/* * Created on 09.06.2006 * */ package org.jdesktop.swingx; import java.awt.Component; import java.awt.Dimension; import java.awt.GraphicsEnvironment; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JTable; import javax.swing.KeyStroke; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import org.jdesktop.swingx.table.TableColumnExt; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; @RunWith(JUnit4.class) public class JXTableHeaderTest extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(JXTableHeaderTest.class .getName()); @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } /** * Issue #485-swingx: table header disappears if all header values are * empty. * * fixed for SwingX. * */ @Test public void testHeaderSizeEmptyStringHeaderValue() { final String[] alternate = { "", "", }; JXTable xTable = new JXTable(10, 2); xTable.getColumn(0).setHeaderValue(alternate[0]); xTable.getColumn(1).setHeaderValue(alternate[1]); assertTrue("header height must be > 0", xTable.getTableHeader().getPreferredSize().height > 0); } /** * Issue #485-swingx: table header disappears if all header values are * empty. * * fixed for Swingx. * */ @Test public void testHeaderSizeNullHeaderValue() { final String[] alternate = { null, null, }; JXTable xTable = new JXTable(10, 2); xTable.getColumn(0).setHeaderValue(alternate[0]); xTable.getColumn(1).setHeaderValue(alternate[1]); assertTrue("header height must be > 0", xTable.getTableHeader().getPreferredSize().height > 0); } /** * Issue #390-swingx: JXTableHeader: throws AIOOB on removing dragged column. * Test that getDraggedColumn is null if removed. * * Problem was reported on mac: * http://forums.java.net/jive/thread.jspa?threadID=18368&tstart=0 * when hiding column while drag(?) is in process. * * */ @Test public void testDraggedColumnRemoved() { JXTable table = new JXTable(10, 2); TableColumnExt columnExt = table.getColumnExt(0); table.getTableHeader().setDraggedColumn(columnExt); // sanity assert assertEquals(columnExt, table.getTableHeader().getDraggedColumn()); table.getColumnModel().removeColumn(columnExt); assertNull("draggedColumn must be null if removed", table.getTableHeader().getDraggedColumn()); } /** * Issue #390-swingx: JXTableHeader: throws AIOOB on removing dragged column. * Test that getDraggedColumn is visible or null. * * Problem was reported on mac: * http://forums.java.net/jive/thread.jspa?threadID=18368&tstart=0 * when hiding column while drag(?) is in process. */ @Test public void testDraggedColumnVisible() { JXTable table = new JXTable(10, 2); TableColumnExt columnExt = table.getColumnExt(0); table.getTableHeader().setDraggedColumn(columnExt); // sanity assert assertEquals(columnExt, table.getTableHeader().getDraggedColumn()); columnExt.setVisible(false); assertNull("dragged column must visible or null", table.getTableHeader().getDraggedColumn()); } /** * Issue 334-swingx: BasicTableHeaderUI.getPrefSize doesn't respect * all renderere's size requirements. * */ @Test public void testPreferredHeight() { JXTable table = new JXTable(10, 2); TableColumnExt columnExt = table.getColumnExt(1); columnExt.setTitle("
Line 1
Line 2
"); JXTableHeader tableHeader = (JXTableHeader) table.getTableHeader(); TableCellRenderer renderer = tableHeader.getCellRenderer(1); Component comp = renderer.getTableCellRendererComponent(table, columnExt.getHeaderValue(), false, false, -1, 1); Dimension prefRendererSize = comp.getPreferredSize(); assertEquals("Header pref height must respect renderer", prefRendererSize.height, tableHeader.getPreferredSize().height); } /** * test doc'ed xheader.getToolTipText(MouseEvent) behaviour. * */ @Test public void testColumnToolTip() { JXTable table = new JXTable(10, 2); TableColumnExt columnExt = table.getColumnExt(0); JXTableHeader tableHeader = (JXTableHeader) table.getTableHeader(); MouseEvent event = new MouseEvent(tableHeader, 0, 0, 0, 40, 5, 0, false); DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); String rendererToolTip = "rendererToolTip"; renderer.setToolTipText(rendererToolTip); columnExt.setHeaderRenderer(renderer); assertEquals(rendererToolTip, tableHeader.getToolTipText(event)); String columnToolTip = "columnToolTip"; columnExt.setToolTipText(columnToolTip); assertEquals(columnToolTip, tableHeader.getToolTipText(event)); } /** * #212-swingx: second last column cannot be set to invisible programatically. * * One reason for the "trick" of reselecting the last is that * the header and with it the columnControl vanishes if there is * no visible column. * * * */ @Test public void testHeaderVisibleWithoutColumns() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run headerVisible - headless environment"); return; } JXTable table = new JXTable(); table.setColumnControlVisible(true); wrapWithScrollingInFrame(table, ""); assertTrue("headerHeight must be > 0", table.getTableHeader().getHeight() > 0); assertEquals("headerWidth must be table width", table.getWidth(), table.getTableHeader().getWidth()); } /** * #212-swingx: second last column cannot be set to invisible programatically. * * One reason for the "trick" of reselecting the last is that * the header and with it the columnControl vanishes if there is * no visible column. * * * */ @Test public void testHeaderVisibleWithColumns() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run headerVisible - headless environment"); return; } JXTable table = new JXTable(10, 2); table.setColumnControlVisible(true); wrapWithScrollingInFrame(table, ""); assertTrue("headerHeight must be > 0", table.getTableHeader().getHeight() > 0); table.setModel(new DefaultTableModel()); assertTrue("headerHeight must be > 0", table.getTableHeader().getHeight() > 0); } //--------------------------------- visual checks /** * Issue #485-swingx: table header disappears if all header values are * empty. Compare core <--> JXTable * fixed for SwingX. * */ public void interactiveHeaderSizeRequirements() { final String[] alternate = { null, null, }; final JTable table = new JTable(10, 2); table.getColumnModel().getColumn(0).setHeaderValue(alternate[0]); table.getColumnModel().getColumn(1).setHeaderValue(alternate[1]); JXTable xTable = new JXTable(10, 2); xTable.getColumn(0).setHeaderValue(alternate[0]); xTable.getColumn(1).setHeaderValue(alternate[1]); JXFrame frame = wrapWithScrollingInFrame(table, xTable, "header height empty (core - xtable)"); frame.setVisible(true); } /** * Issue #390-swingx: JXTableHeader: throws AIOOB on removing dragged column. * */ public void interactiveDraggedColumnRemoved() { final JXTable table = new JXTable(10, 5); Action deleteColumn = new AbstractAction("deleteCurrentColumn") { public void actionPerformed(ActionEvent e) { TableColumn column = table.getTableHeader().getDraggedColumn(); if (column == null) return; table.getColumnModel().removeColumn(column); } }; KeyStroke keyStroke = KeyStroke.getKeyStroke("F1"); table.getInputMap(JTable.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "f1"); table.getActionMap().put("f1", deleteColumn); JXFrame frame = wrapWithScrollingInFrame(table, "Remove dragged column with F1"); frame.setVisible(true); } /** * Visual demo that header is always visible. */ public void interactiveHeaderVisible() { final JXTable table = new JXTable(); table.setColumnControlVisible(true); JXFrame frame = wrapWithScrollingInFrame(table, "header always visible"); Action action = new AbstractAction("toggle model") { public void actionPerformed(ActionEvent e) { int columnCount = table.getColumnCount(true); table.setModel(columnCount > 0 ? new DefaultTableModel() : new DefaultTableModel(10, 2)); } }; addAction(frame, action); frame.setVisible(true); } public static void main(String args[]) { JXTableHeaderTest test = new JXTableHeaderTest(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Siz.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXCollapsiblePaneVisualCheck.java0000644000175000017500000000711711210401722026201 0ustar tonytony/* * $Id: JXCollapsiblePaneVisualCheck.java,v 1.1 2008/04/07 02:35:47 kschaefe Exp $ * * Copyright 2008 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import org.jdesktop.swingx.JXCollapsiblePane.Direction; /** * @author Karl George Schaefer * */ public class JXCollapsiblePaneVisualCheck extends InteractiveTestCase { /** * @param args */ public static void main(String[] args) { JXCollapsiblePaneVisualCheck test = new JXCollapsiblePaneVisualCheck(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * SwingX 578: Ensure that the directions work correctly. */ public void interactiveDirectionTest() { JXCollapsiblePane north = new JXCollapsiblePane(Direction.UP); JLabel label = new JLabel("north1
north2
north3
north4
north5
north6"); label.setHorizontalAlignment(SwingConstants.CENTER); north.add(label); JXCollapsiblePane south = new JXCollapsiblePane(Direction.DOWN); label = new JLabel("south1
south2
south3
south4
south5
south6"); label.setHorizontalAlignment(SwingConstants.CENTER); south.add(label); JXCollapsiblePane west = new JXCollapsiblePane(Direction.LEFT); west.add(new JLabel("west1west2west3west4west5west6")); JXCollapsiblePane east = new JXCollapsiblePane(Direction.RIGHT); east.add(new JLabel("east1east2east3east4east5east6")); JPanel panel = new JPanel(new GridLayout(2, 2)); JButton button = new JButton(north.getActionMap().get(JXCollapsiblePane.TOGGLE_ACTION)); button.setText("UP"); panel.add(button); button = new JButton(south.getActionMap().get(JXCollapsiblePane.TOGGLE_ACTION)); button.setText("DOWN"); panel.add(button); button = new JButton(west.getActionMap().get(JXCollapsiblePane.TOGGLE_ACTION)); button.setText("LEFT"); panel.add(button); button = new JButton(east.getActionMap().get(JXCollapsiblePane.TOGGLE_ACTION)); button.setText("RIGHT"); panel.add(button); JFrame frame = wrapInFrame(panel, "Direction Animation Test"); frame.add(north, BorderLayout.NORTH); frame.add(south, BorderLayout.SOUTH); frame.add(west, BorderLayout.WEST); frame.add(east, BorderLayout.EAST); frame.pack(); frame.setVisible(true); } /** * do nothing test - keep the testrunner happy. */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/action/0000755000175000017500000000000011210401736021171 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/action/TargetManagerTest.java0000644000175000017500000001022711210401722025412 0ustar tonytony/* * $Id: TargetManagerTest.java,v 1.3 2008/10/11 20:41:09 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.action; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; import junit.framework.TestCase; /** * Tests registration and command execution of the target manager. * * @author Mark Davidson */ @RunWith(JUnit4.class) public class TargetManagerTest extends TestCase { @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } protected void tearDown() { TargetManager manager = TargetManager.getInstance(); manager.reset(); } /** * By default, there are no targets. */ @Test public void testGetTargets() { TargetManager manager = TargetManager.getInstance(); assertNull(manager.getTarget()); Targetable[] targets = manager.getTargets(); assertNotNull(targets); assertTrue(targets.length == 0); } /** * Test Target registration methods. */ @Test public void testAddRemoveTargets() { FooTarget foo = new FooTarget(); BarTarget bar = new BarTarget(); TargetManager manager = TargetManager.getInstance(); // append targets manager.addTarget(foo); manager.addTarget(bar); Targetable[] targets = manager.getTargets(); assertNotNull(targets); assertTrue(targets.length == 2); // by default, targets are appended to the list. assertTrue(targets[0] == foo); assertTrue(targets[1] == bar); // Test removal manager.removeTarget(foo); manager.removeTarget(bar); targets = manager.getTargets(); assertNotNull(targets); assertTrue(targets.length == 0); // add targets, prepend bar manager.addTarget(foo); manager.addTarget(bar, true); targets = manager.getTargets(); assertNotNull(targets); assertTrue(targets.length == 2); assertTrue(targets[0] == bar); assertTrue(targets[1] == foo); } /** * Tests doCommand for both explicit targets and the targets in the list. */ @Test public void testDoCommand() { FooTarget foo = new FooTarget(); BarTarget bar = new BarTarget(); TargetManager manager = TargetManager.getInstance(); // set explicit targets manager.setTarget(foo); assertTrue(manager.doCommand("foo", null)); assertFalse(manager.doCommand("bar", null)); manager.setTarget(bar); assertTrue(manager.doCommand("bar", null)); assertFalse(manager.doCommand("foo", null)); // Add both of the targets all commands are valid manager.setTarget(null); manager.addTarget(foo); manager.addTarget(bar); assertTrue(manager.doCommand("bar", null)); assertTrue(manager.doCommand("foo", null)); } // // Some examples of Targets // private class FooTarget implements Targetable { public String FOO_ACTION = "foo"; public boolean doCommand(Object command, Object value) { return hasCommand(command); } public boolean hasCommand(Object command) { if (command.equals(FOO_ACTION)) { return true; } return false; } public Object[] getCommands() { return new Object[] { FOO_ACTION }; } } private class BarTarget implements Targetable { public String BAR_ACTION = "bar"; public boolean doCommand(Object command, Object value) { return hasCommand(command); } public boolean hasCommand(Object command) { if (command.equals(BAR_ACTION)) { return true; } return false; } public Object[] getCommands() { return new Object[] { BAR_ACTION }; } } } swingx-1.0-src/src/test/org/jdesktop/swingx/action/ActionManagerTest.java0000644000175000017500000002606311210401722025406 0ustar tonytony/* * $Id: ActionManagerTest.java,v 1.7 2008/10/11 20:41:10 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.action; import java.awt.event.ActionEvent; import java.awt.event.ItemEvent; import java.beans.Statement; import java.util.Iterator; import javax.swing.Action; import javax.swing.JButton; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; import junit.framework.TestCase; /** * Unit test driver for the ActionManager * * TODO: Should test TargetableActions */ @RunWith(JUnit4.class) public class ActionManagerTest extends TestCase { private ActionManager manager; @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } // TODO: Add more attributes which represent actions and types. protected void setUp() { // JW: changed on reorg to remove reference to Application // manager = Application.getInstance().getActionManager(); manager = ActionManager.getInstance(); // Simple commands manager.addAction(createBoundAction("simple-command", "Simple", "S")); manager.addAction(createBoundAction("simple2-command", "Simple 2", "2")); manager.addAction(createBoundAction("simple3-command", "Simple 3", "3")); // Toggle action manager.addAction(createBoundAction("toggle-command", "Toggle", "T", true)); // More toggle actions for a group manager.addAction(createBoundAction("left-command", "Left", "L", true, "position-group")); manager.addAction(createBoundAction("center-command", "Center", "C", true, "position-group")); manager.addAction(createBoundAction("right-command", "Right", "R", true, "position-group")); // Composite action CompositeAction action = ActionFactory.createCompositeAction("composite-command", "Composite", "C"); action.addAction("simple-command"); action.addAction("simple2-command"); manager.addAction(action); // Server action ServerAction saction = ActionFactory.createServerAction("namefinder-command", "NameFinder", "N"); saction.setURL("http://namefinder.sfbay/NameFinder"); saction.addParam("nfquery", "Mark Davidson"); manager.addAction(saction); // XXX This doesn't work since google doesn't allow this. saction = ActionFactory.createServerAction("server-command", "Google", "G"); saction.setURL("http://www.google.com/search"); saction.addParam("q", "Zaphod+Beeblebrox"); manager.addAction(saction); } public BoundAction createBoundAction(String id, String name, String mnemonic) { return createBoundAction(id, name, mnemonic, false); } public BoundAction createBoundAction(String id, String name, String mnemonic, boolean toggle) { return createBoundAction(id, name, mnemonic, toggle, null); } public BoundAction createBoundAction(String id, String name, String mnemonic, boolean toggle, String group) { return ActionFactory.createBoundAction(id, name, mnemonic, toggle, group); } /** * Test to see if the types of actions that are created map correctly. */ @Test public void testActionTypes() { assertTrue(manager.isBoundAction("simple-command")); assertTrue(manager.isBoundAction("simple2-command")); assertTrue(manager.isBoundAction("simple3-command")); assertTrue(manager.isBoundAction("toggle-command")); assertTrue(manager.isBoundAction("left-command")); assertTrue(manager.isBoundAction("right-command")); assertTrue(manager.isBoundAction("center-command")); assertTrue(manager.isCompositeAction("composite-command")); assertTrue(manager.isServerAction("namefinder-command")); assertTrue(manager.isServerAction("server-command")); // state types assertTrue(!manager.isStateAction("simple-command")); assertTrue(!manager.isStateAction("simple2-command")); assertTrue(!manager.isStateAction("simple3-command")); assertTrue(manager.isStateAction("toggle-command")); assertTrue(manager.isStateAction("left-command")); assertTrue(manager.isStateAction("right-command")); assertTrue(manager.isStateAction("center-command")); assertTrue(!manager.isStateAction("composite-command")); assertTrue(!manager.isStateAction("namefinder-command")); assertTrue(!manager.isStateAction("server-command")); } /** * A test which registers all the actions with a controller, * invokes the actions to see if the registration was correct. */ @Test public void testRegisterMethod() { Controller controller = new Controller(); // Register the action on the controller. Iterator iter = manager.getActionIDs().iterator(); while (iter.hasNext()) { manager.registerCallback(iter.next(), controller, "action"); } // Invoke all the actions. Action action; // dummy ItemSelectable used for forging ItemEvents. java.awt.ItemSelectable dummy = new JButton("Dummy"); iter = manager.getActionIDs().iterator(); while (iter.hasNext()) { controller.reset(); Object id = iter.next(); action = manager.getAction(id); if (manager.isBoundAction(id)) { if (manager.isStateAction(id)) { // Use reflection to fake the ItemEvent. ItemEvent evt = new ItemEvent(dummy, 666, "test", ItemEvent.SELECTED); Statement statement = new Statement(action, "itemStateChanged", new Object[] { evt }); try { statement.execute(); } catch (Exception ex) { ex.printStackTrace(); } assertTrue(controller.isInvoked()); } else { // Simple command action. action.actionPerformed(new ActionEvent(action, 666, "test")); assertTrue("ERROR: " + manager.getBoundAction(id).toString(), controller.isInvoked()); } } } } /** * Test the composite action. Two simple commands have registered methods. * these methods should be executed in the composite action invokation. */ @Test public void testCompositeAction() { Controller controller = new Controller(); manager.registerCallback("simple-command", controller, "doNew"); manager.registerCallback("simple2-command", controller, "doSave"); Action action = manager.getAction("composite-command"); action.actionPerformed(new ActionEvent(action, 666, "test")); assertTrue("ERROR: Controller was not invoked", controller.isInvoked()); assertTrue("ERROR: Controller should have been invoked twice", controller.getNumInvoked() == 2); } /** * Test the server action. The server action should send an http post. * with the params and not throw an exception. * * TODO: It's difficult to test the server action in a firewall/non-controlled * network environment. Enable this test when working specifically with ServerActions. @Test public void testServerAction() { ServerAction action = manager.getServerAction("namefinder-command"); try { // Determine if we are behind a firewall. Set // set the web proxy if we are URL url = new URL(action.getURL()); URLConnection uc = url.openConnection(); uc.connect(); } catch (Exception ex) { // Set proxy since we are behind the firewall. System.setProperty("http.proxyHost", "scaweb1.sfbay"); System.setProperty("http.proxyPort", "8080"); } action.actionPerformed(new ActionEvent(action, 666, "test")); } */ @Test public void testEnabled() { boolean[] values = new boolean[] { true, false, true, true, false, false }; Iterator iter; for (int i = 0; i < values.length; i++) { // Test for actions enabled by disabling actions. iter = manager.getActionIDs().iterator(); while (iter.hasNext()) { manager.setEnabled(iter.next(), values[i]); } iter = manager.getActionIDs().iterator(); while (iter.hasNext()) { assertTrue(manager.isEnabled(iter.next()) == values[i]); } } } @Test public void testSelected() { boolean[] values = new boolean[] { true, false, true, true, false, false }; Iterator iter; for (int i = 0; i < values.length; i++) { // Test for actions enabled by disabling actions. iter = manager.getActionIDs().iterator(); while (iter.hasNext()) { manager.setSelected(iter.next(), values[i]); } iter = manager.getActionIDs().iterator(); while (iter.hasNext()) { Object a = iter.next(); if (manager.isStateAction(a)) { assertTrue("Action: " + a + " selected state not " + values[i], manager.isSelected(a) == values[i]); } else { // Non StateActions will always return false. assertFalse(manager.isSelected(a)); } } } } /** * A simple controller callback for ActionManager registration test. */ public class Controller { private boolean invoked = false; private int numInvoked = 0; public void action() { invoked = true; numInvoked++; } public void doNew() { action(); } public void doSave() { action(); } public void action(boolean state) { action(); } public void reset() { invoked = false; numInvoked = 0; } public int getNumInvoked() { return numInvoked; } public boolean isInvoked() { return invoked; } } } swingx-1.0-src/src/test/org/jdesktop/swingx/action/ActionTest.java0000644000175000017500000003470411210401722024114 0ustar tonytony/* * Created on 27.01.2006 * */ package org.jdesktop.swingx.action; import java.awt.event.ActionEvent; import java.awt.event.ItemListener; import java.util.logging.Logger; import javax.swing.AbstractButton; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JRadioButton; import javax.swing.JRadioButtonMenuItem; import javax.swing.JToggleButton; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; import junit.framework.TestCase; @RunWith(JUnit4.class) public class ActionTest extends TestCase { @SuppressWarnings("all") private static final Logger LOG = Logger.getLogger(ActionTest.class .getName()); protected ActionContainerFactory factory; @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } @Override protected void setUp() throws Exception { factory = new ActionContainerFactory(null); } /** * Issue #255-swingx: probs in synch selectable button <--> action. * * test that configured button is kept in synch with * action selected state and the other way round. This uses a * custom configure via the ActionContainerFactory.configureSelectableButton. * The direction from button to action is broken. */ @Test public void testButtonSelectedSynchAction() { AbstractActionExt extAction = createStateAction(); boolean actionSelected = true; extAction.setSelected(actionSelected); JToggleButton button = new JToggleButton(); factory.configureSelectableButton(button, extAction, null); // invert action selected and assert that the change is taken up // by the button extAction.setSelected(!actionSelected); assertEquals("button selected must be synched to action", !actionSelected, button.isSelected()); // reset button button.setSelected(actionSelected); // sanity: the button did take the direct selection change assertEquals(actionSelected, button.isSelected()); // assert that changed selected is taken up by action assertEquals("action selected must be synched to button", actionSelected, extAction.isSelected()); } /** * Issue #255-swingx: probs in synch selectable button <--> action. * * test that configured button is kept in synch with * action selected state and the other way round. This uses the * ActionContainerFactory.createButton(). * The direction from button to action is broken. */ @Test public void testCreateButtonSelectedSynchAction() { AbstractActionExt extAction = createStateAction(); boolean actionSelected = true; extAction.setSelected(actionSelected); JToggleButton button = (JToggleButton) factory.createButton(extAction); // invert action selected and assert that the change is taken up // by the button extAction.setSelected(!actionSelected); assertEquals("button selected must be synched to action", !actionSelected, button.isSelected()); // reset button button.setSelected(actionSelected); // sanity: the button did take the direct selection change assertEquals(actionSelected, button.isSelected()); // assert that changed selected is taken up by action assertEquals("action selected must be synched to button", actionSelected, extAction.isSelected()); } /** * Issue #255-swingx: probs in synch selectable button <--> action. * * test that the button always has mostly one * Action registered as itemListener and that * this registered listener is the same as the buttons * action. * */ @Test public void testButtonOneActionAsItemListener() { AbstractActionExt extAction = createStateAction(); JToggleButton button = new JToggleButton(); factory.configureSelectableButton(button, extAction, null); assertCountAsItemListener(button, extAction, 1); factory.configureSelectableButton(button, null, null); // assert that the previous action is removed as itemListener assertCountAsItemListener(button, extAction, 0); } /** * Issue #255-swingx: probs in synch selectable button <--> action. * test that configured button is kept in synch with * maximal one action's selected state */ @Test public void testButtonSelectedNullAction() { AbstractActionExt extAction = createStateAction(); JToggleButton button = new JToggleButton(); factory.configureSelectableButton(button, extAction, null); // we are sure that the button selected is true (has dedicated test) // now configure it with a different action, unselected AbstractActionExt extActionB = createStateAction(); factory.configureSelectableButton(button, extActionB, null); // invert the old action selected and assert that the change // does not effect the taken up by the button extAction.setSelected(!extAction.isSelected()); assertEquals("button selected must be uneffected by old action", extActionB.isSelected(), button.isSelected()); } /** * Issue #255-swingx: probs in synch selectable button <--> action. * test that PCLs related to a previous button are * unregistered from the Action after release. * */ @Test public void testButtonReleaseActionReleasePCL() { AbstractActionExt extAction = createStateAction(); JToggleButton button = new JToggleButton(); factory.configureSelectableButton(button, extAction, null); // sanity: expect it to be 2 - one is the menuitem itself, another // the TogglePCL registered by the ActionContainerFacory assertEquals(2, extAction.getPropertyChangeListeners().length); // set the button's action to null factory.configureSelectableButton(button, null, null); // assert that button related PCLs are removed from the action's listener list assertEquals(0, extAction.getPropertyChangeListeners().length); } /** * Issue #255-swingx: probs in synch selectable button <--> action. * test that configured button is no longer kept in * synch after setting the action to null. */ @Test public void testButtonSelectedReleasedSynchAction() { AbstractActionExt extAction = createStateAction(); JToggleButton button = new JToggleButton(); factory.configureSelectableButton(button, extAction, null); // now we unconfigure it with a null action factory.configureSelectableButton(button, null, null); // invert the old action selected and assert that the change // does not effect the taken up by the button boolean oldSelected = button.isSelected(); extAction.setSelected(!extAction.isSelected()); assertEquals("button selected must be uneffected by old action", oldSelected, button.isSelected()); } /** * Issue #255-swingx: probs in synch selectable button <--> action. * test that configured button is kept in synch with * maximal one action's selected state */ @Test public void testButtonSelectedMaxOneSynchAction() { AbstractActionExt extAction = createStateAction(); boolean actionSelected = true; extAction.setSelected(actionSelected); JToggleButton button = new JToggleButton(); factory.configureSelectableButton(button, extAction, null); // we are sure that the button selected is true (has dedicated test) // now configure it with a different action, unselected AbstractActionExt extActionB = createStateAction(); factory.configureSelectableButton(button, extActionB, null); // sanity: the new action is not effected by the old // currently this may accidentally pass because the back direction isn't // synched!! assertFalse(extActionB.isSelected()); assertEquals("button selected must be initialized to new action", extActionB.isSelected(), button.isSelected()); // invert the old action selected and assert that the change // does not effect the taken up by the button extAction.setSelected(!actionSelected); // need to be done twice, the first toggle produces extAction.setSelected(actionSelected); assertEquals("button selected must be uneffected by old action", extActionB.isSelected(), button.isSelected()); } /** * Issue #255-swingx: probs in synch selectable button <--> action. * test that button is configured with initial action selected state. * */ @Test public void testButtonSelectedInitialSynchAction() { AbstractActionExt extAction = createStateAction(); boolean actionSelected = true; extAction.setSelected(actionSelected); JToggleButton button = new JToggleButton(); boolean buttonSelected = button.isSelected(); // sanity: different selected state assertTrue(actionSelected != buttonSelected); factory.configureSelectableButton(button, extAction, null); assertEquals("action selection must be unchanged", actionSelected, extAction.isSelected()); assertEquals("button selected must be initialized", actionSelected, button.isSelected()); } /** * test method contract: configureSelectable must throw runtime exception * for non-state action. * */ @Test public void testExceptionOnNonStateAction() { AbstractActionExt actionExt = createStateAction(); actionExt.setStateAction(false); JToggleButton button = new JToggleButton(); try { factory.configureSelectableButton(button, actionExt, null); fail("configureSelectable didn't throw IllegalArgument for non-state action "); } catch (IllegalArgumentException e) { // nothing todo - this is what we expect } catch (Exception e) { fail("caught unexpected exception " + e); } } /** * Issue #229-swingx: increasing listener list in column actions. * * sub-issue: ActionContainerFactory doesn't check if the action is * already synchronizing to the same button. */ @Test public void testToggleButtonConfigure() { // this should pass after giving the gc "reasonable" chance to // have collected the unreachable... // assertToggleButtonConfigure(new JToggleButton(), new JToggleButton()); } /** * Issue #229-swingx: increasing listener list in column actions. * * sub-issue: ActionContainerFactory doesn't check if the action is * already synchronizing to the same button. */ @Test public void testToggleButtonConfigureToggleWithSame() { assertToggleButtonConfigureWithSame(new JToggleButton()); assertToggleButtonConfigureWithSame(new JRadioButton()); assertToggleButtonConfigureWithSame(new JCheckBox()); assertToggleButtonConfigureWithSame(new JRadioButtonMenuItem()); assertToggleButtonConfigureWithSame(new JCheckBoxMenuItem()); } private void assertToggleButtonConfigureWithSame(AbstractButton button) { AbstractActionExt extAction = createStateAction(); assertEquals(0, extAction.getPropertyChangeListeners().length); factory.configureSelectableButton(button, extAction, null); // sanity: expect it to be 2 - one is the menuitem itself, another // the TogglePCL registered by the ActionContainerFacory assertEquals(2, extAction.getPropertyChangeListeners().length); factory.configureSelectableButton(button, extAction, null); // JW: wrong assumption!! Valid only if first == second, for // different buttons we actually expect the listener count to be increased! // Note to myself: remove this comment after correcting the method call // sequence here in the test ... assertEquals(2, extAction.getPropertyChangeListeners().length); } /** * Issue #229-swingx: increasing listener list in column actions. * * sub-issue: ActionContainerFactory registers the action multiple times to * the same button as ItemListener */ @Test public void testToggleButtonAddItemListenerToSame() { assertAddItemListenerToSame(new JToggleButton()); assertAddItemListenerToSame(new JRadioButton()); assertAddItemListenerToSame(new JCheckBox()); assertAddItemListenerToSame(new JRadioButtonMenuItem()); assertAddItemListenerToSame(new JCheckBoxMenuItem()); } private void assertAddItemListenerToSame(AbstractButton checkBoxItem) { AbstractActionExt extAction = createStateAction(); factory.configureSelectableButton(checkBoxItem, extAction, null); assertCountAsItemListener(checkBoxItem, extAction, 1 ); factory.configureSelectableButton(checkBoxItem, extAction, null); assertCountAsItemListener(checkBoxItem, extAction, 1 ); } protected AbstractActionExt createStateAction() { AbstractActionExt extAction = new AbstractActionExt("dummy") { public void actionPerformed(ActionEvent e) { } }; extAction.setStateAction(); return extAction; } /** * assert that the given itemListener is registered exactly * expectedCount times to the given button. * @param checkBoxItem * @param extAction * @param expectedCount */ protected void assertCountAsItemListener(AbstractButton checkBoxItem, ItemListener extAction, int expectedCount) { int count = 0; ItemListener[] itemListeners = checkBoxItem.getItemListeners(); for (int j = 0; j < itemListeners.length; j++) { if (extAction == itemListeners[j]) { count++; } } assertEquals("ItemListener registration count", expectedCount, count); } /** * Issue #4-swinglabs: infinite loop when setting long destricption. * */ @Test public void testLongDescriptionLoop() { AbstractActionExt action = createStateAction(); action.setLongDescription("some"); } } swingx-1.0-src/src/test/org/jdesktop/swingx/action/ServerActionTest.java0000644000175000017500000000127411210401722025277 0ustar tonytony/* * $Id: ServerActionTest.java,v 1.2 2008/10/11 20:41:09 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.action; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; import junit.framework.TestCase; @RunWith(JUnit4.class) public class ServerActionTest extends TestCase { /** * Issue #206-swingx: NPE in addHeader. * */ @Test public void testNPEAddHeader() { ServerAction action = new ServerAction(); action.addHeader("key", "value"); } } swingx-1.0-src/src/test/org/jdesktop/swingx/action/ActionIssues.java0000644000175000017500000001331011210401722024436 0ustar tonytony/* * Created on 31.01.2006 * */ package org.jdesktop.swingx.action; import java.awt.event.ActionEvent; import java.awt.event.ItemEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.io.Serializable; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenuItem; import javax.swing.JRadioButton; import javax.swing.JToggleButton; import org.jdesktop.test.PropertyChangeReport; import org.jdesktop.test.SerializableSupport; public class ActionIssues extends ActionTest implements Serializable { /** * Issue #349-swingx: table not serializable * * */ public void testSerializationBoundAction() { BoundAction action = new BoundAction("some"); action.registerCallback(this, "testSerializationRolloverFalse"); try { SerializableSupport.serialize(action); } catch (IOException e) { fail("not serializable " + e); } catch (ClassNotFoundException e) { fail("not serializable " + e); } } /** * core issue: * set enabled via putValue leads to inconsistent state. * fixed in jdk6 */ public void testFireEnabled() { Action action = new AbstractAction("dummy") { public void actionPerformed(ActionEvent e) { // nothing to do } }; PropertyChangeListener l = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if ("enabled".equals(evt.getPropertyName())) { assertEquals(evt.getNewValue(), ((Action) evt.getSource()).isEnabled()); } } }; action.addPropertyChangeListener(l); action.putValue("enabled", false); } /** * core issue: * set selected via putValue leads to inconsistent state. * */ public void testFireSelected() { AbstractActionExt action = new AbstractActionExt("dummy") { public void actionPerformed(ActionEvent e) { // nothing to do } public void itemStateChanged(ItemEvent e) { // nothing to do } }; PropertyChangeListener l = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if ("selected".equals(evt.getPropertyName())) { assertEquals(evt.getNewValue(), ((AbstractActionExt) evt.getSource()).isSelected()); } } }; action.addPropertyChangeListener(l); action.putValue("selected", true); } //--------------------- core: selected is not a bean property /** * unexpected core behaviour: selected is not a bound property! * PENDING: is it in Mustang? */ public void testToggleButtonPropertyChangeSelected() { JToggleButton button = new JToggleButton(); PropertyChangeReport report = new PropertyChangeReport(); button.addPropertyChangeListener(report); boolean selected = button.isSelected(); button.setSelected(!selected); // sanity... assertEquals(selected, !button.isSelected()); assertEquals("must have one event for selected", 1, report.getEventCount("selected")); } public void testCheckBoxPropertyChangeSelected() { JCheckBox button = new JCheckBox(); PropertyChangeReport report = new PropertyChangeReport(); button.addPropertyChangeListener(report); boolean selected = button.isSelected(); button.setSelected(!selected); // sanity... assertEquals(selected, !button.isSelected()); assertEquals("must have one event for selected", 1, report.getEventCount("selected")); } public void testRadioButtonPropertyChangeSelected() { JRadioButton button = new JRadioButton(); PropertyChangeReport report = new PropertyChangeReport(); button.addPropertyChangeListener(report); boolean selected = button.isSelected(); button.setSelected(!selected); // sanity... assertEquals(selected, !button.isSelected()); assertEquals("must have one event for selected", 1, report.getEventCount("selected")); } public void testCheckBoxMenuItemPropertyChangeSelected() { JMenuItem button = new JCheckBoxMenuItem(); PropertyChangeReport report = new PropertyChangeReport(); button.addPropertyChangeListener(report); boolean selected = button.isSelected(); button.setSelected(!selected); // sanity... assertEquals(selected, !button.isSelected()); assertEquals("must have one event for selected", 1, report.getEventCount("selected")); } /** * Template to try and test memory leaks (from Palantir blog). * TODO apply for listener problems */ public void testMemory() { //create test object Object testObject = new Object(); // create queue and weak reference ReferenceQueue queue = new ReferenceQueue(); WeakReference ref = new WeakReference(testObject, queue); // set hard reference to null testObject = null; // force garbage collection System.gc(); // soft reference should now be enqueued (no leak) assertTrue(ref.isEnqueued()); } } swingx-1.0-src/src/test/org/jdesktop/swingx/action/TargetableActionTest.java0000644000175000017500000002210311210401722026075 0ustar tonytony/* * $Id: TargetableActionTest.java,v 1.5 2008/12/05 14:34:57 kschaefe Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.action; import java.awt.BorderLayout; import java.awt.Component; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.util.ArrayList; import java.util.List; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.JToolBar; import javax.swing.JTree; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableModel; import junit.framework.TestCase; import org.jdesktop.swingx.JXEditorPane; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTree; import org.jdesktop.swingx.JXTreeTable; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * A unit test for targetable actions. */ @RunWith(JUnit4.class) public class TargetableActionTest extends TestCase { @Test public void testDummy() { } public static void main(String[] args) { showActionMaps(); showUI(); } /** * These are cover methods for the same methods in ActionFactory. */ public static TargetableAction createTargetableAction(String id, String name) { return createTargetableAction(id, name, null); } public static TargetableAction createTargetableAction(String id, String name, String mnemonic) { return createTargetableAction(id, name, mnemonic, false); } public static TargetableAction createTargetableAction(String id, String name, String mnemonic, boolean toggle) { return ActionFactory.createTargetableAction(id, name, mnemonic, toggle, null); } public static TargetableAction createTargetableAction(String id, String name, String mnemonic, boolean toggle, String group) { return ActionFactory.createTargetableAction(id, name, mnemonic, toggle, group); } public static void showUI() { ActionManager manager = new ActionManager(); ActionManager.setInstance(manager); // The action id must map to the action-ids in the component. manager.addAction(createTargetableAction("cut-to-clipboard", "Cut", "C")); manager.addAction(createTargetableAction("copy-to-clipboard", "Copy", "P")); manager.addAction(createTargetableAction("paste-from-clipboard", "Paste", "T")); manager.addAction(createTargetableAction("print", "Print", "P")); manager.addAction(createTargetableAction("find", "Find", "F")); manager.addAction(createTargetableAction("collapse-all", "Collapse", "l")); manager.addAction(createTargetableAction("expand-all", "Expand", "x")); // More toggle actions for a group manager.addAction(createTargetableAction("left-justify", "Left", "L", true, "position-group")); manager.addAction(createTargetableAction("center-justify", "Center", "C", true, "position-group")); manager.addAction(createTargetableAction("right-justify", "Right", "R", true, "position-group")); List list = new ArrayList(); list.add("cut-to-clipboard"); list.add("copy-to-clipboard"); list.add("paste-from-clipboard"); list.add(null); list.add("left-justify"); list.add("center-justify"); list.add("right-justify"); list.add(null); list.add("print"); list.add("find"); list.add("collapse-all"); list.add("expand-all"); // Use the factory to build components from lists. ActionContainerFactory factory = new ActionContainerFactory(manager); JToolBar toolbar = factory.createToolBar(list); JPanel panel = new JPanel(new GridLayout(2,2, 5, 5)); JXEditorPane editor = new JXEditorPane("text/html", "This is an example of some text"); panel.add(editor); panel.add(new JXEditorPane()); panel.add(createTabbedPane()); panel.add(createTree()); JFrame frame = new JFrame(); frame.getContentPane().add(toolbar, BorderLayout.NORTH); frame.getContentPane().add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } public static JComponent createTabbedPane() { JTabbedPane pane = new JTabbedPane(); pane.add(createTable()); pane.add(createTable()); pane.add(createTable()); pane.add(createTable()); // XXX - this is a way to support setting a target manager. // There are some bugs with this approach. Namely, there is no // reliable way for the TargetManager to be reset when th pane.addFocusListener(new FocusListener() { public void focusGained(FocusEvent evt) { // System.out.println("FocusGained: " + evt); JTabbedPane pane = (JTabbedPane)evt.getSource(); Component comp = pane.getSelectedComponent(); if (comp instanceof Targetable) { TargetManager.getInstance().setTarget((Targetable)comp); } } public void focusLost(FocusEvent evt) { //System.out.println("FocusLost: " + evt); if (!evt.isTemporary()) { TargetManager.getInstance().setTarget(null); } } }); pane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent evt) { JTabbedPane pane = (JTabbedPane)evt.getSource(); Component comp = pane.getSelectedComponent(); if (comp instanceof Targetable) { TargetManager.getInstance().setTarget((Targetable)comp); } } }); return pane; } public static int tableNum = 0; public static JComponent createTable() { TableModel dataModel = new AbstractTableModel() { public int getColumnCount() { return 4; } public int getRowCount() { return 4;} public Object getValueAt(int row, int col) { return new Integer(row*col); } public boolean isCellEditable(int row, int col) { return true; } }; JXTable table = new JXTable(dataModel); table.setName("Table: " + tableNum++); return table; } public static JComponent createTree() { JTree jtree = new JTree(); JXTree tree = new JXTree(jtree.getModel()); tree.setEditable(true); // Stuff the action map. ActionMap map = tree.getActionMap(); Action action = new MyAction("print", "Print on JTree"); map.put(action.getValue(Action.NAME), action); action = new MyAction("find", "Find on JTree"); map.put(action.getValue(Action.NAME), action); return tree; } /** * Simple action which displays a string when invoked. */ public static class MyAction extends AbstractAction { private String description; public MyAction(String name, String desc) { super(name); this.description = desc; } public void actionPerformed(ActionEvent evt) { System.out.println(getValue(Action.NAME) + " has been invoked: " + description); } } public static void showActionMaps() { System.out.println("\nActionMap keys for JXTable\n==================="); showActionMap(new JXTable()); System.out.println("\nActionMap keys for JXEditorPane\n=================="); showActionMap(new JXEditorPane()); System.out.println("\nActionMap keys for an HTML JXEditorPane\n=================="); showActionMap(new JXEditorPane("text/html", "")); System.out.println("\nActionMap keys for JXTree\n===================="); showActionMap(new JXTree()); System.out.println("\nActionMap keys for JXTreeTable\n===================="); showActionMap(new JXTreeTable()); } public static void showActionMap(JComponent comp) { ActionMap map = comp.getActionMap(); Object[] keys = map.allKeys(); if (keys != null) { for (int i = 0; i < keys.length; i++) { System.out.println(keys[i]); } } } } swingx-1.0-src/src/test/org/jdesktop/swingx/tree/0000755000175000017500000000000011210401734020651 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/tree/TreeModelSupportTest.java0000644000175000017500000002237211210401722025634 0ustar tonytony/* * $Id: TreeModelSupportTest.java,v 1.2 2008/10/11 20:42:33 rah003 Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.tree; import javax.swing.event.TreeModelEvent; import javax.swing.tree.TreePath; import junit.framework.TestCase; import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; import org.jdesktop.swingx.treetable.DefaultTreeTableModel; import org.jdesktop.swingx.treetable.TreeTableModel; import org.jdesktop.test.TreeModelReport; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * Unit tests around Tree/Table/ModelEvent notification. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class TreeModelSupportTest extends TestCase { /** the treeModelSupport to test */ private TreeModelSupport support; /** the TreeTableModel is instantiated with. */ private TreeTableModel model; /** the report listening to the support. */ private TreeModelReport report; // TODO - implement and test precondition failure of added/removed // notification @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } /** * test modelSupport pathChanged: * not null path must not be empty, (checked by TreePath) * path elements must not be null (core issue - should be checked * by TreePath but isn't) */ @Test public void testPathChangedNotNullPathElements() { TreePath path = new TreePath(new Object[] {null}); try { support.firePathChanged(path); fail("must not allow null path elements"); } catch (NullPointerException e) { // expected } // unexpected exception } /** * test modelSupport pathChanged: * throw on null path */ @Test public void testPathChangedNotNullPath() { try { support.firePathChanged(null); fail("must not allow null path elements"); } catch (NullPointerException e) { // expected } // unexpected exception } /** * test modelSupport treeStructureChanged: null path. * */ @Test public void testTreeStructureChangedNullPath() { support.fireTreeStructureChanged(null); assertEquals(1, report.getEventCount()); assertEquals(1, report.getStructureEventCount()); TreeModelEvent structureEvent = report.getLastStructureEvent(); assertNull(structureEvent.getChildren()); assertNull(structureEvent.getTreePath()); assertNull(structureEvent.getPath()); } /** * test modelSupport treeStructureChanged: * not null path must not be empty, (checked by TreePath) * path elements must not be null (core issue - should be checked * by TreePath but isn't) * first element must be root (? not sure so don't enforce). * * */ @Test public void testTreeStructureChangedNotNullPathElements() { TreePath path = new TreePath(new Object[] {null}); try { support.fireTreeStructureChanged(path); fail("must not allow null path elements"); } catch (NullPointerException e) { // expected } // unexpected exception } /** * test modelSupport treeStructureChanged: * not null path must not be empty, * first element must be root (? not sure so don't enforce). * * */ @Test public void testTreeStructureChangedNotNullPath() { Object root = model.getRoot(); Object child = model.getChild(root, 0); TreePath path = new TreePath(new Object[] {root, child}); support.fireTreeStructureChanged(path); assertEquals(1, report.getEventCount()); assertEquals(1, report.getStructureEventCount()); TreeModelEvent structureEvent = report.getLastStructureEvent(); assertEquals(path, structureEvent.getTreePath()); } /** * test modelSupport newRoot: not null root. * */ @Test public void testNewRootNull() { DefaultTreeTableModel model = new DefaultTreeTableModel(); assertNull(model.getRoot()); TreeModelSupport support = new TreeModelSupport(model); support.addTreeModelListener(report); support.fireNewRoot(); assertEquals(1, report.getEventCount()); assertEquals(1, report.getStructureEventCount()); TreeModelEvent structureEvent = report.getLastStructureEvent(); assertNull(structureEvent.getChildren()); assertNull(structureEvent.getTreePath()); assertNull(structureEvent.getPath()); } /** * test modelSupport newRoot: not null root. * */ @Test public void testNewRootNotNull() { support.fireNewRoot(); assertEquals(1, report.getEventCount()); assertEquals(1, report.getStructureEventCount()); TreeModelEvent structureEvent = report.getLastStructureEvent(); assertNull(structureEvent.getChildren()); assertEquals(model.getRoot(), structureEvent.getTreePath().getLastPathComponent()); assertEquals(1, structureEvent.getPath().length); } /** * sanity to characterize TreeModelEvents: structureChanged * constructor has null children but empty childIndices. * */ @Test public void testTreeStructureChangedConstructor() { TreePath path = new TreePath(model.getRoot()); TreeModelEvent structureChanged = new TreeModelEvent(model, path); assertEquals(model, structureChanged.getSource()); assertEquals(path, structureChanged.getTreePath()); assertNull(structureChanged.getChildren()); // not documented ... assertNotNull(structureChanged.getChildIndices()); assertEquals(0, structureChanged.getChildIndices().length); } /** * sanity to characterize TreeModelEvents: constructor for * changed/inserted/removed. The api doc is not overly clear, * but the childIndices/children should not be null? */ @Test public void testTreeModifiedConstructor() { TreePath path = new TreePath(model.getRoot()); int[] childIndices = new int[] { 0 }; Object[] children = new Object[] { model.getChild(model.getRoot(), childIndices[0]) }; TreeModelEvent changed = new TreeModelEvent(model, path, childIndices, children); assertEquals(model, changed.getSource()); // returns the path as-is assertEquals(path, changed.getTreePath()); // returns a defensive copy assertEquals(children[0], changed.getChildren()[0]); assertEquals(childIndices[0], changed.getChildIndices()[0]); } //------------------------------ factory and housekeeping //copied from JTree and modified to use TTNs protected TreeTableModel getDefaultTreeTableModel() { DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode( "JXTreeTable"); DefaultMutableTreeTableNode parent; parent = new DefaultMutableTreeTableNode("colors"); root.add(parent); parent.add(new DefaultMutableTreeTableNode("blue")); parent.add(new DefaultMutableTreeTableNode("violet")); parent.add(new DefaultMutableTreeTableNode("red")); parent.add(new DefaultMutableTreeTableNode("yellow")); parent = new DefaultMutableTreeTableNode("sports"); root.add(parent); parent.add(new DefaultMutableTreeTableNode("basketball")); parent.add(new DefaultMutableTreeTableNode("soccer")); parent.add(new DefaultMutableTreeTableNode("football")); parent.add(new DefaultMutableTreeTableNode("hockey")); parent = new DefaultMutableTreeTableNode("food"); root.add(parent); parent.add(new DefaultMutableTreeTableNode("hot dogs")); parent.add(new DefaultMutableTreeTableNode("pizza")); parent.add(new DefaultMutableTreeTableNode("ravioli")); parent.add(new DefaultMutableTreeTableNode("bananas")); return new DefaultTreeTableModel(root); } @Override protected void setUp() throws Exception { model = getDefaultTreeTableModel(); support = new TreeModelSupport(model); report = new TreeModelReport(); support.addTreeModelListener(report); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXListVisualCheck.java0000644000175000017500000001771011210401722024057 0ustar tonytony/* * Created on 10.06.2006 * */ package org.jdesktop.swingx; import java.awt.Color; import java.awt.Cursor; import java.awt.event.ActionEvent; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.DefaultListModel; import javax.swing.JList; import org.jdesktop.swingx.decorator.ColorHighlighter; import org.jdesktop.swingx.decorator.FilterPipeline; import org.jdesktop.swingx.decorator.HighlightPredicate; import org.jdesktop.swingx.decorator.HighlighterFactory; import org.jdesktop.swingx.decorator.PatternFilter; import org.jdesktop.swingx.decorator.PatternPredicate; import org.jdesktop.swingx.hyperlink.EditorPaneLinkVisitor; import org.jdesktop.swingx.hyperlink.LinkModel; import org.jdesktop.swingx.hyperlink.LinkModelAction; import org.jdesktop.swingx.renderer.DefaultListRenderer; import org.jdesktop.swingx.renderer.HyperlinkProvider; public class JXListVisualCheck extends JXListTest { @SuppressWarnings("all") private static final Logger LOG = Logger.getLogger(JXListVisualCheck.class .getName()); public static void main(String[] args) { setSystemLF(true); JXListVisualCheck test = new JXListVisualCheck(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Rollover.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #377-swingx: JXList (it's wrapping model) fires incorrect events. * * */ public void interactiveFilterMutateModel() { final DefaultListModel model = createAscendingListModel(0, 5); final JXList list = new JXList(model, true); list.setFilters(new FilterPipeline(new PatternFilter())); JXFrame frame = wrapWithScrollingInFrame(list, "Mutate model with filter"); Action addItem = new AbstractAction("add item") { public void actionPerformed(ActionEvent e) { int selected = list.getSelectedIndex(); if (selected >= 0) { selected = list.convertIndexToModel(selected); } if (selected > 0) { model.add(selected - 1, model.getSize()); } else { model.addElement(model.getSize()); } } }; addAction(frame, addItem); Action removeItem = new AbstractAction("remove item") { public void actionPerformed(ActionEvent e) { int selected = list.getSelectedIndex(); if (selected >= 0) { selected = list.convertIndexToModel(selected); } if (selected > 0) { model.remove(selected - 1); } } }; addAction(frame, removeItem); Action changeItem = new AbstractAction("change item") { public void actionPerformed(ActionEvent e) { int selected = list.getSelectedIndex(); if (selected >= 0) { selected = list.convertIndexToModel(selected); } if (selected > 0) { int newValue = ((Integer) model.getElementAt(selected - 1)).intValue() + 10; model.set(selected - 1, newValue); } } }; addAction(frame, changeItem); Action flush = new AbstractAction("toggle sort") { public void actionPerformed(ActionEvent e) { list.toggleSortOrder(); } }; addAction(frame, flush); show(frame); } public void interactiveTestSort() { final JXList list = new JXList(listModel, true); JXFrame frame = wrapWithScrollingInFrame(list, "Toggle sorter"); Action toggleSortOrder = new AbstractAction("Toggle Sort Order") { public void actionPerformed(ActionEvent e) { list.toggleSortOrder(); } }; addAction(frame, toggleSortOrder); Action resetSortOrder = new AbstractAction("Reset Sort Order") { public void actionPerformed(ActionEvent e) { list.resetSortOrder(); } }; addAction(frame, resetSortOrder); frame.setVisible(true); } public void interactiveTestCompareFocusedCellBackground() { JXList xlist = new JXList(listModel); xlist.setBackground(new Color(0xF5, 0xFF, 0xF5)); JList list = new JList(listModel); list.setBackground(new Color(0xF5, 0xFF, 0xF5)); showWithScrollingInFrame(xlist, list, "unselectedd focused background: JXList/JList"); } public void interactiveTestTablePatternFilter5() { JXList list = new JXList(listModel); String pattern = "Row"; list.setHighlighters(new ColorHighlighter(// columns not really important, ListAdapter.getXXValue // uses row only new PatternPredicate(pattern, 0), null, Color.red)); showWithScrollingInFrame(list, "PatternHighlighter: " + pattern); } public void interactiveTestTableAlternateHighlighter1() { JXList list = new JXList(listModel); list.addHighlighter( HighlighterFactory.createSimpleStriping(HighlighterFactory.LINE_PRINTER)); showWithScrollingInFrame(list, "AlternateRowHighlighter - lineprinter"); } /** * Plain rollover highlight, had been repaint issues. * */ public void interactiveTestRolloverHighlight() { JXList list = new JXList(listModel); list.setRolloverEnabled(true); ColorHighlighter rollover = new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW, new Color(0xF0, 0xF0, 0xE0), null); list.addHighlighter(rollover); showWithScrollingInFrame(list, "rollover highlight"); } /** * Plain rollover highlight in multi-column layout, had been repaint issues. * */ public void interactiveTestRolloverHighlightMultiColumn() { JXList list = new JXList(listModel); list.setRolloverEnabled(true); list.setLayoutOrientation(JList.HORIZONTAL_WRAP); list.addHighlighter(new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW, new Color(0xF0, 0xF0, 0xE0), null)); showWithScrollingInFrame(list, "rollover highlight - horz. Wrap"); } /** * Issue #503-swingx: rolloverEnabled disables custom cursor * */ public void interactiveTestRolloverHighlightCustomCursor() { JXList list = new JXList(listModel); list.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); list.setRolloverEnabled(true); list.addHighlighter(new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW, new Color(0xF0, 0xF0, 0xE0), null)); showWithScrollingInFrame(list, "rollover highlight - custom cursor"); } /** * Issue #20: Highlighters and LinkRenderers don't work together * fixed with overhaul of SwingX renderers? */ public void interactiveTestRolloverHighlightAndLink() { JXList list = new JXList(createListModelWithLinks()); EditorPaneLinkVisitor editorPaneLinkVisitor = new EditorPaneLinkVisitor(); LinkModelAction action = new LinkModelAction(editorPaneLinkVisitor); HyperlinkProvider h = new HyperlinkProvider(action, LinkModel.class); list.setCellRenderer(new DefaultListRenderer(h)); list.setRolloverEnabled(true); list.addHighlighter(new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW, new Color(0xF0, 0xF0, 0xE0), null)); showWithScrollingInFrame(list, editorPaneLinkVisitor.getOutputComponent(), "rollover highlight with links"); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXTreeTableVisualCheck.java0000644000175000017500000014662411210401722025022 0ustar tonytony/* * $Id: JXTreeTableVisualCheck.java,v 1.77 2009/03/20 15:41:32 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.CellEditor; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.event.CellEditorListener; import javax.swing.event.ChangeEvent; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreePath; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.decorator.AbstractHighlighter; import org.jdesktop.swingx.decorator.ColorHighlighter; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.Filter; import org.jdesktop.swingx.decorator.FilterPipeline; import org.jdesktop.swingx.decorator.HighlightPredicate; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.HighlighterFactory; import org.jdesktop.swingx.decorator.PatternFilter; import org.jdesktop.swingx.decorator.PatternPredicate; import org.jdesktop.swingx.decorator.ShadingColorHighlighter; import org.jdesktop.swingx.decorator.ShuttleSorter; import org.jdesktop.swingx.decorator.HighlightPredicate.AndHighlightPredicate; import org.jdesktop.swingx.decorator.HighlightPredicate.ColumnHighlightPredicate; import org.jdesktop.swingx.decorator.HighlightPredicate.DepthHighlightPredicate; import org.jdesktop.swingx.renderer.DefaultTreeRenderer; import org.jdesktop.swingx.test.ComponentTreeTableModel; import org.jdesktop.swingx.test.XTestUtils; import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; import org.jdesktop.swingx.treetable.DefaultTreeTableModel; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.swingx.treetable.TreeTableModel; import org.jdesktop.test.AncientSwingTeam; /** * @author Jeanette Winzenburg */ public class JXTreeTableVisualCheck extends JXTreeTableUnitTest { @SuppressWarnings("all") private static final Logger LOG = Logger .getLogger(JXTreeTableVisualCheck.class.getName()); public static void main(String[] args) { // NOTE JW: this property has be set "very early" in the application life-cycle // it's immutable once read from the UIManager (into a final static field!!) // System.setProperty("sun.swing.enableImprovedDragGesture", "true" ); setSystemLF(true); JXTreeTableVisualCheck test = new JXTreeTableVisualCheck(); try { // test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Hierarchical.*"); // test.runInteractiveTests("interactive.*ToolTip.*"); // test.runInteractiveTests("interactive.*DnD.*"); // test.runInteractiveTests("interactive.*Compare.*"); // test.runInteractiveTests("interactive.*RowHeightCompare.*"); // test.runInteractiveTests("interactive.*RToL.*"); // test.runInteractiveTests("interactive.*Insert.*"); test.runInteractiveTests("interactive.*Edit.*"); } catch (Exception ex) { } } /** * Issue #730-swingx: editor's stop not always called. * * - start edit a cell in the hierarchical column, * - click into another cell of the hierarchical column * - edit sometimes canceled instead of stopped * * seems to happen if click into text of cell, okay if outside. * Trying to fix in TreeTableHacker: first try to stop editing * cancel if unsuccessful. * * PENDING JW: why didn't we do that in the first place? Any * possibility that the edit will end up in the wrong node * in expand/collapse? * * Okay, checked again: the cancel is needed because otherwise * the edited value might end up in the wrong row, that is the * one after the currently edited if the parent of the edited * is collapsed while editing (old issue #120-jdnc). * * To fight the regression, the hacker's completeEditing now is * called before updating renderer's (tree) expansion state. Seems * to fix both issues now. */ public void interactiveEditingCanceledStopped() { final JTextField field = new JTextField(); DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode("ROOT"); DefaultMutableTreeTableNode a = new DefaultMutableTreeTableNode("A"); DefaultMutableTreeTableNode a1 = new DefaultMutableTreeTableNode("A1"); DefaultMutableTreeTableNode b = new DefaultMutableTreeTableNode("B"); a.add(a1); root.add(a); root.add(b); // default table: hack around #120-jdnc introduces #730 final JXTreeTable xTable = new JXTreeTable(); xTable.setTreeTableModel(new DefaultTreeTableModel(root)); xTable.expandAll(); xTable.setVisibleColumnCount(10); xTable.packColumn(0, -1); CellEditor editor = xTable.getCellEditor(0, 0); CellEditorListener l = new CellEditorListener() { public void editingCanceled(ChangeEvent e) { field.setText("canceled"); LOG.info("canceled"); } public void editingStopped(ChangeEvent e) { field.setText("stopped"); LOG.info("stopped"); }}; editor.addCellEditorListener(l); JXFrame frame = wrapWithScrollingInFrame(xTable, "#730-swingx: click sometimes cancels"); Action toggleExpansion = new AbstractAction("toggle") { public void actionPerformed(ActionEvent arg0) { boolean isExpanded = xTable.isExpanded(0); if (isExpanded) { xTable.collapseRow(0); } else { xTable.expandRow(0); } } }; KeyStroke stroke = KeyStroke.getKeyStroke("F1"); xTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(stroke, "toggleExpansion"); xTable.getActionMap().put("toggleExpansion", toggleExpansion); frame.add(field, BorderLayout.SOUTH); addStatusMessage(frame, "F1 to toggle expansion of first row"); show(frame); } /** * Issue #862-swingx: JXTree - add api for selection colors. * Here: check colors when used in JXTreeTable */ public void interactiveSelectionColors() { final JXTreeTable tree = new JXTreeTable(new FileSystemModel()); // use SwingX renderer which is aware of per-tree selection colors tree.setTreeCellRenderer(new DefaultTreeRenderer()); final Color uiBackground = tree.getSelectionBackground(); final Color uiForeground = tree.getSelectionForeground(); Action toggleSelectionColors = new AbstractAction("toggle selection colors") { public void actionPerformed(ActionEvent e) { if (tree.getSelectionBackground() == uiBackground) { tree.setSelectionBackground(Color.BLUE); tree.setSelectionForeground(Color.RED); } else { tree.setSelectionBackground(uiBackground); tree.setSelectionForeground(uiForeground); } } }; JXFrame frame = wrapWithScrollingInFrame(tree, "selection colors"); addAction(frame, toggleSelectionColors); show(frame); } /** * Issue #853-swingx: tree is not disabled. * */ public void interactiveDisabledTreeColumn() { final JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()); JXFrame frame = showWithScrollingInFrame(treeTable, "disabled - tree follows table"); Action action = new AbstractActionExt("toggle enabled") { public void actionPerformed(ActionEvent e) { treeTable.setEnabled(!treeTable.isEnabled()); } }; addAction(frame, action); show(frame); } /** * Reported: toggling LAF doesn't update treetable? * WorksforMe. */ public void interactiveToggleLAF() { JXTreeTable table = new JXTreeTable(treeTableModel); JXFrame frame = wrapInFrame(new JScrollPane(table), "Toggle LAF", true); show(frame); } /** * Issue #??-swingx: Tooltip by highlighter in hierarchical column * * Not reliably updated. * * To reproduce: * - move to some row over the hierarchical column where the tooltip is showing * - move the next row, typically the tooltip is not showing */ public void interactiveHierarchicalToolTip() { final JXTreeTable table = new JXTreeTable(treeTableModel); Highlighter toolTip = new AbstractHighlighter( new AndHighlightPredicate( new ColumnHighlightPredicate(0), HighlightPredicate.ROLLOVER_ROW)) { @Override protected Component doHighlight(Component component, ComponentAdapter adapter) { ((JComponent) component).setToolTipText(adapter.getString()); return component; } }; table.addHighlighter(toolTip); JXFrame frame = wrapWithScrollingInFrame(table, "ToolTip with Highlighter (hierarchical column)"); addComponentOrientationToggle(frame); frame.setVisible(true); } /** * Issue #544-swingx: problem with simple striping in JXTreeTable. * start with cross-platform == okay, bluish striping * toggle to system (win) == striping color silver, * but second row bluish, background not reset? * toggle back to cross-platform == no striping, all bluish * * start with system (win) == okay, silver striping * toggle to cross-platform == okay, bluish striping * back to system == trouble as above * * JXTable looks okay. */ public void interactiveUIHighlight() { JXTable table = new JXTable(20, 4); JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()); treeTable.setHighlighters(HighlighterFactory.createSimpleStriping()); table.setHighlighters(treeTable.getHighlighters()); final JXFrame frame = wrapWithScrollingInFrame(treeTable, table, "update ui-specific striping"); Action toggle = new AbstractActionExt("toggle LF") { boolean system; public void actionPerformed(ActionEvent e) { String lfName = system ? UIManager.getSystemLookAndFeelClassName() : UIManager.getCrossPlatformLookAndFeelClassName(); try { UIManager.setLookAndFeel(lfName); SwingUtilities.updateComponentTreeUI(frame); } catch (Exception e1) { LOG.info("exception when setting LF to " + lfName); LOG.log(Level.FINE, "caused by ", e1); } system = !system; } }; addAction(frame, toggle); frame.setVisible(true); } /** * Issue #471-swingx: No selection on click into hierarchical column outside * node. * * Check patch and bidi-compliance. */ public void interactiveHierarchicalSelectionAndRToL() { final JXTreeTable table = new JXTreeTable(treeTableModel); final JXFrame frame = wrapWithScrollingInFrame(table, "Selection/Expansion Hacks and Bidi Compliance"); addComponentOrientationToggle(frame); frame.setVisible(true); } /** * visual check what happens on toggling the largeModel property. * It's okay for ComponentTreeModel, blows up for FileSystemModel. * */ public void interactiveLargeModel() { final JXTreeTable treeTable = new JXTreeTable(createMutableVisualizeModel()); treeTable.setRootVisible(true); ToolTipManager.sharedInstance().unregisterComponent(treeTable); Action action = new AbstractAction("toggle largeModel") { public void actionPerformed(ActionEvent e) { treeTable.setLargeModel(!treeTable.isLargeModel()); } }; JXFrame frame = wrapWithScrollingInFrame(treeTable, "large model"); addAction(frame, action); frame.setVisible(true); } private ComponentTreeTableModel createMutableVisualizeModel() { JXPanel frame = new JXPanel(); frame.setName("somename for root"); JTextField textField = new JTextField(); textField.setName("firstchild"); frame.add(textField); JComponent box = Box.createVerticalBox(); box.setName("dumyybox"); frame.add(box); JComponent inner = Box.createHorizontalBox(); inner.setName("inner"); box.add(inner); inner.add(new JButton()); inner.add(new JXFindPanel()); frame.add(new JComboBox()); frame.add(new JXDatePicker()); return new ComponentTreeTableModel(frame); } /** * Issue #575-swingx: JXTreeTable - scrollsOnExpand has no effect. * * Compare tree/table: * - tree expands if property is true and * expand triggered by mouse (not programmatically?). * - treeTable never * * * related issue #296-swingx: expose scrollPathToVisible in JXTreeTable. */ public void interactiveScrollPathTreeExpand() { final JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()); final JXTree tree = new JXTree(treeTable.getTreeTableModel()); treeTable.setScrollsOnExpand(tree.getScrollsOnExpand()); tree.setRowHeight(treeTable.getRowHeight()); Action toggleScrolls = new AbstractAction("Toggle Scroll") { public void actionPerformed(ActionEvent e) { tree.setScrollsOnExpand(!tree.getScrollsOnExpand()); treeTable.setScrollsOnExpand(tree.getScrollsOnExpand()); } }; Action expand = new AbstractAction("Expand") { public void actionPerformed(ActionEvent e) { int[] selectedRows = tree.getSelectionRows(); if (selectedRows.length > 0) { tree.expandRow(selectedRows[0]); } int selected = treeTable.getSelectedRow(); if (selected >= 0) { treeTable.expandRow(selected); } } }; JXFrame frame = wrapWithScrollingInFrame(tree, treeTable, "Compare Tree/Table expand properties "); addAction(frame, toggleScrolls); addAction(frame, expand); frame.setVisible(true); } /** * issue #296-swingx: expose scrollPathToVisible in JXTreeTable. * * Treetable should behave exactly like Tree - so * simply passing through to the hierarchical renderer is not quite * enough - need to force a scrollTo after expanding. * Not really: all scrolling is piped through scrollRectToVisible, * so that looks like the central place to fix (f.i. delegate to * the enclosing treeTable). Related issue #575-swingx. * * note: the action is not guarded against overshooting * at the end of the model! */ public void interactiveScrollPathToVisible() { // PENDING: FileSystemModel throws occasional NPE on getChildCount() final TreeTableModel model = new FileSystemModel(); final JXTreeTable table = new JXTreeTable(model); table.setColumnControlVisible(true); final JXTree tree = new JXTree(model); Action action = new AbstractAction("path visible") { public void actionPerformed(ActionEvent e) { Rectangle visible = table.getVisibleRect(); int lastRow = table.rowAtPoint(new Point(5, visible.y + visible.height + 100)); TreePath path = table.getPathForRow(lastRow); Object last = path.getLastPathComponent(); while (model.isLeaf(last) || model.getChildCount(last) == 0) { lastRow++; path = table.getPathForRow(lastRow); last = path.getLastPathComponent(); } // we have a node with children int childCount = model.getChildCount(last); Object lastChild = model.getChild(last, childCount - 1); path = path.pathByAddingChild(lastChild); table.scrollPathToVisible(path); tree.scrollPathToVisible(path); } }; JXFrame frame = wrapWithScrollingInFrame(table, tree, "compare scrollPathtovisible"); addAction(frame, action); frame.setVisible(true); } /** * http://forums.java.net/jive/thread.jspa?threadID=13966&tstart=0 * adjust hierarchical column width on expansion. The expansion * listener looks like doing the job. Important: auto-resize off, * otherwise the table will run out of width to distribute! * */ public void interactiveUpdateWidthOnExpand() { final JXTreeTable tree = new JXTreeTable(treeTableModel); tree.setColumnControlVisible(true); JTree renderer = (JTree) tree.getCellRenderer(0, tree.getHierarchicalColumn()); renderer.addTreeExpansionListener(new TreeExpansionListener(){ public void treeCollapsed(TreeExpansionEvent event) { } public void treeExpanded(TreeExpansionEvent event) { final JTree renderer = (JTree)event.getSource(); SwingUtilities.invokeLater(new Runnable(){ public void run() { tree.getColumnModel().getColumn(0).setPreferredWidth(renderer.getPreferredSize().width); } }); } }); JXFrame frame = wrapWithScrollingInFrame(tree, "adjust column on expand"); frame.setVisible(true); } /** * visualize editing of the hierarchical column, both * in a tree and a treeTable * */ public void interactiveTreeTableModelEditing() { final TreeTableModel model = createMutableVisualizeModel(); final JXTreeTable table = new JXTreeTable(model); JTree tree = new JTree(model) { @Override public String convertValueToText(Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { if (value instanceof Component) { return ((Component) value).getName(); } return super.convertValueToText(value, selected, expanded, leaf, row, hasFocus); } }; tree.setEditable(true); final JXFrame frame = wrapWithScrollingInFrame(table, tree, "Editing: compare treetable and tree"); addComponentOrientationToggle(frame); frame.setVisible(true); } /** * Issue #248-swingx: update probs with insert into empty model when root * not visible. * * Looks like a core JTree problem: a collapsed root is not automatically expanded * on hiding. Should it? Yes, IMO (JW). * * this exposed a slight glitch in JXTreeTable: toggling the initially invisible * root to visible did not result in showing the root in the the table. Needed * to modify setRootVisible to force a revalidate. * */ public void interactiveTestInsertNodeEmptyModel() { final DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode(); final InsertTreeTableModel model = new InsertTreeTableModel(root, true); final JTree tree = new JTree(model); tree.setRootVisible(false); final JXTreeTable treeTable = new JXTreeTable(model); treeTable.addHighlighter( HighlighterFactory.createSimpleStriping(HighlighterFactory.LINE_PRINTER)); treeTable.setColumnControlVisible(true); // treetable root invisible by default JXFrame frame = wrapWithScrollingInFrame(tree, treeTable, "JTree vs. JXTreeTable: insert into empty model"); Action insertAction = new AbstractAction("insert node") { public void actionPerformed(ActionEvent e) { model.addChild(root); } }; addAction(frame, insertAction); Action toggleRoot = new AbstractAction("toggle root visible") { public void actionPerformed(ActionEvent e) { boolean rootVisible = !tree.isRootVisible(); treeTable.setRootVisible(rootVisible); tree.setRootVisible(rootVisible); } }; addAction(frame, toggleRoot); addMessage(frame, "model reports root as non-leaf"); frame.pack(); frame.setVisible(true); } /** * Issue #254-swingx: collapseAll/expandAll behaviour depends on * root visibility (same for treeTable/tree) * * initial: root not visible, all root children visible * do: collapse all - has no effect, unexpected? * do: toggle root - root and all children visible, expected * do: collapse all - only root visible, expected * do: toggle root - all nodes invisible, expected * do: expand all - still all nodes invisible, unexpected? * * */ public void interactiveTestInsertNodeEmptyModelExpand() { final DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode(); final InsertTreeTableModel model = new InsertTreeTableModel(root, true); for (int i = 0; i < 5; i++) { model.addChild(root); } final JXTree tree = new JXTree(model); tree.setRootVisible(false); final JXTreeTable treeTable = new JXTreeTable(model); treeTable.addHighlighter( HighlighterFactory.createSimpleStriping(HighlighterFactory.LINE_PRINTER)); treeTable.setColumnControlVisible(true); // treetable root invisible by default JXFrame frame = wrapWithScrollingInFrame(tree, treeTable, "collaps/expand root"); Action toggleRoot = new AbstractAction("toggle root") { public void actionPerformed(ActionEvent e) { boolean rootVisible = !tree.isRootVisible(); treeTable.setRootVisible(rootVisible); tree.setRootVisible(rootVisible); } }; addAction(frame, toggleRoot); Action expandAll = new AbstractAction("expandAll") { public void actionPerformed(ActionEvent e) { treeTable.expandAll(); tree.expandAll(); } }; addAction(frame, expandAll); Action collapseAll = new AbstractAction("collapseAll") { public void actionPerformed(ActionEvent e) { treeTable.collapseAll(); tree.collapseAll(); } }; addAction(frame, collapseAll); frame.setVisible(true); } /** * Issue #247-swingx: update probs with insert node. * The insert under a collapsed node fires a dataChanged on the table * which results in the usual total "memory" loss (f.i. selection) * to reproduce: run example, select root's child in both the tree and the * treetable (left and right view), press the insert button, treetable looses * selection, tree doesn't (the latter is the correct behaviour) * * couldn't reproduce the reported loss of expansion state. Hmmm.. * */ public void interactiveTestInsertUnderCollapsedNode() { final DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode(); final InsertTreeTableModel model = new InsertTreeTableModel(root); DefaultMutableTreeTableNode childA = model.addChild(root); final DefaultMutableTreeTableNode childB = model.addChild(childA); model.addChild(childB); DefaultMutableTreeTableNode secondRootChild = model.addChild(root); model.addChild(secondRootChild); JXTree tree = new JXTree(model); final JXTreeTable treeTable = new JXTreeTable(model); treeTable.addHighlighter( HighlighterFactory.createSimpleStriping(HighlighterFactory.LINE_PRINTER)); treeTable.setColumnControlVisible(true); treeTable.setRootVisible(true); JXFrame frame = wrapWithScrollingInFrame(tree, treeTable, "JXTree vs. JXTreeTable insert node to nested child"); Action insertAction = new AbstractAction("insert node") { public void actionPerformed(ActionEvent e) { model.addChild(childB); } }; addAction(frame, insertAction); addMessage(frame, "insert nested child must not loose selection/expanseion state"); frame.pack(); frame.setVisible(true); } /** * Issue #246-swingx: update probs with insert node. * * The reported issue is an asymmetry in updating the parent: it's done only * if not expanded. With the arguments of #82-swingx, parent's appearance * might be effected by child changes if expanded as well. *

* Here's a test for insert: the crazy renderer removes the icon if * childCount exceeds a limit (here > 3). Select a node, insert a child, * expand the node and keep inserting children. Interestingly the parent is * always updated in the treeTable, but not in the tree *

* Quick test if custom icons provided by the renderer are respected. They * should appear and seem to do. * */ public void interactiveTestInsertNodeAndChangedParentRendering() { final Icon topIcon = XTestUtils.loadDefaultIcon("wellTop.gif"); final DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode(); final InsertTreeTableModel model = new InsertTreeTableModel(root); JXTree tree = new JXTree(model); final JXTreeTable treeTable = new JXTreeTable(model); treeTable.setColumnControlVisible(true); TreeCellRenderer renderer = new DefaultTreeCellRenderer() { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component comp = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); TreePath path = tree.getPathForRow(row); if (path != null) { Object node = path.getLastPathComponent(); if ((node != null) && (tree.getModel().getChildCount(node) > 2)) { setIcon(topIcon); } } return comp; } }; tree.setCellRenderer(renderer); treeTable.setTreeCellRenderer(renderer); treeTable.setRootVisible(true); JXFrame frame = wrapWithScrollingInFrame(tree, treeTable, "JXTree vs. JXTreeTable - update parent on insert child"); Action insertAction = new AbstractAction("insert node selected treetable") { public void actionPerformed(ActionEvent e) { int selected = treeTable.getSelectedRow(); if (selected < 0 ) return; TreePath path = treeTable.getPathForRow(selected); DefaultMutableTreeTableNode parent = (DefaultMutableTreeTableNode) path.getLastPathComponent(); model.addChild(parent); } }; addAction(frame, insertAction); addMessage(frame, " - rendering changed for > 2 children"); frame.pack(); frame.setVisible(true); } /** * Issue #82-swingx: update probs with insert node. * * Adapted from example code in report. * Insert node under selected in treetable (or under root if none selected) * Here: old problem with root not expanded because it's reported as a leaf. */ public void interactiveTestInsertNode() { final DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode(); final InsertTreeTableModel model = new InsertTreeTableModel(root); JTree tree = new JTree(model); tree.setRootVisible(false); final JXTreeTable treeTable = new JXTreeTable(model); treeTable.addHighlighter( HighlighterFactory.createSimpleStriping(HighlighterFactory.GENERIC_GRAY)); Highlighter hl = new ShadingColorHighlighter( new ColumnHighlightPredicate(0)); treeTable.addHighlighter(hl); JXFrame frame = wrapWithScrollingInFrame(tree, treeTable, "JTree vs. JXTreeTable - insert to collapsed root"); Action insertAction = new AbstractAction("insert node") { public void actionPerformed(ActionEvent e) { int selected = treeTable.getSelectedRow(); DefaultMutableTreeTableNode parent; if (selected < 0 ) { parent = root; } else { TreePath path = treeTable.getPathForRow(selected); parent = (DefaultMutableTreeTableNode) path.getLastPathComponent(); } model.addChild(parent); } }; addAction(frame, insertAction); addMessage(frame, "insert into root-only model - does not show"); frame.pack(); frame.setVisible(true); } /** * Issue #224-swingx: TreeTableEditor not bidi compliant. * * the textfield for editing is at the wrong position in RToL. */ public void interactiveRToLTreeTableEditor() { final TreeTableModel model = createMutableVisualizeModel(); final JXTreeTable table = new JXTreeTable(model); final JXFrame frame = wrapWithScrollingInFrame(table, "Editor: position follows Component orientation"); addComponentOrientationToggle(frame); frame.setVisible(true); } /** * Issue #223-swingx: Icons lost when editing. * Regression after starting to fix #224-swingx? * * */ public void interactiveTreeTableEditorIcons() { final TreeTableModel model = createMutableVisualizeModel(); final JXTreeTable table = new JXTreeTable(model); JXFrame frame = wrapWithScrollingInFrame(table, "Editor: icons showing"); frame.setVisible(true); } /** * see effect of switching treeTableModel. * Problem when toggling back to FileSystemModel: hierarchical * column does not show filenames, need to click into table first. * JW: fixed. The issue was updating of the conversionMethod * field - needed to be done before calling super.setModel(). * */ public void interactiveTestSetModel() { final JXTreeTable treeTable = new JXTreeTable(treeTableModel); treeTable.setColumnControlVisible(true); JXFrame frame = wrapWithScrollingInFrame(treeTable, "toggle model"); frame.setVisible(true); final TreeTableModel model = new ComponentTreeTableModel(frame); Action action = new AbstractAction("Toggle model") { public void actionPerformed(ActionEvent e) { TreeTableModel myModel = treeTable.getTreeTableModel(); treeTable.setTreeTableModel(myModel == model ? treeTableModel : model); } }; addAction(frame, action); } /** * compare treeTable/table height: default gridlines * */ public void interactiveTestAlternateHighlightAndRowGridLines() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); treeTable.setRowHeight(22); // treeTable.setRootVisible(true); // this leads to lines not properly drawn, as always, // the margins need to be set as well. // treeTable.setShowGrid(true); treeTable.setShowGrid(true, true); treeTable.addHighlighter( HighlighterFactory.createSimpleStriping(HighlighterFactory.LINE_PRINTER)); JXTable table = new JXTable(new AncientSwingTeam()); table.addHighlighter( HighlighterFactory.createSimpleStriping(HighlighterFactory.LINE_PRINTER)); table.setRowHeight(22); JFrame frame = wrapWithScrollingInFrame(treeTable, table, "AlternateRow LinePrinter-with Gridlines"); frame.setVisible(true); } /** * compare table/table height: * with and without default gridlines and margins * */ public void interactiveTestAlternateHighlightAndNoGridLines() { JXTable treeTable = new JXTable(new AncientSwingTeam()); treeTable.setRowHeight(22); treeTable.addHighlighter( HighlighterFactory.createSimpleStriping(HighlighterFactory.LINE_PRINTER)); JXTable table = new JXTable(new AncientSwingTeam()); table.addHighlighter( HighlighterFactory.createSimpleStriping(HighlighterFactory.LINE_PRINTER)); table.setRowHeight(22); table.setShowGrid(false, false); JFrame frame = wrapWithScrollingInFrame(treeTable, table, "AlternateRow LinePrinter- left== with, right == out Gridlines"); frame.setVisible(true); } /** * compare treeTable/tree height * */ public void interactiveTestHighlightAndRowHeightCompareTree() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); treeTable.setRowHeight(22); treeTable.setShowGrid(true, false); Highlighter hl = new ShadingColorHighlighter( new ColumnHighlightPredicate(0)); treeTable.setHighlighters( HighlighterFactory.createSimpleStriping(HighlighterFactory.GENERIC_GRAY), hl); final JXTree tree = new JXTree(treeTableModel); JXTree renderer = (JXTree) treeTable.getCellRenderer(0, treeTable .getHierarchicalColumn()); tree.setRowHeight(renderer.getRowHeight()); JFrame frame = wrapWithScrollingInFrame(treeTable, tree, "LinePrinter-, ColumnHighlighter and RowHeight"); frame.setVisible(true); } /** * compare treeTable/tree height * */ public void interactiveTestHighlighterRowHeightCompareTree() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); treeTable.addHighlighter(new ColorHighlighter(Color.orange, null)); treeTable.setIntercellSpacing(new Dimension(15, 15)); treeTable.setRowHeight(48); treeTable.setShowHorizontalLines(true); final JXTree tree = new JXTree(treeTableModel); JXTree renderer = (JXTree) treeTable.getCellRenderer(0, treeTable .getHierarchicalColumn()); tree.setRowHeight(renderer.getRowHeight()); JFrame frame = wrapWithScrollingInFrame(treeTable, tree, "compare rowheight of treetable vs tree - rowheight 48, margin 15"); frame.setVisible(true); } /** * Issue #168-jdnc: dnd enabled breaks node collapse/expand. * Regression? Dnd doesn't work at all? * */ public void interactiveToggleDnDEnabled() { final JXTreeTable treeTable = new JXTreeTable(treeTableModel); treeTable.setColumnControlVisible(true); final JXTree tree = new JXTree(treeTableModel); JXTree renderer = (JXTree) treeTable.getCellRenderer(0, 0); tree.setRowHeight(renderer.getRowHeight()); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "toggle dragEnabled (starting with false)"); frame.setVisible(true); Action action = new AbstractActionExt("Toggle dnd: false") { public void actionPerformed(ActionEvent e) { boolean dragEnabled = !treeTable.getDragEnabled(); treeTable.setDragEnabled(dragEnabled); tree.setDragEnabled(dragEnabled); setName("Toggle dnd: " + dragEnabled); } }; addAction(frame, action); } /** * Issue #226: no per-cell tooltips in TreeColumn. * Note: this explicitly uses core default renderers! */ public void interactiveTestToolTipsCoreRenderer() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); treeTable.setTreeCellRenderer(createTreeRenderer()); treeTable.setDefaultRenderer(Object.class, createTableRenderer()); JXTree tree = new JXTree(treeTableModel); tree.setCellRenderer(createTreeRenderer()); // I'm registered to do tool tips so we can draw tips for the renderers ToolTipManager toolTipManager = ToolTipManager.sharedInstance(); toolTipManager.registerComponent(tree); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "tooltips with core renderers"); frame.setVisible(true); } /** * Creates and returns a core default table cell renderer with tooltip. * @return */ private TableCellRenderer createTableRenderer() { final TableCellRenderer delegate = new DefaultTableCellRenderer(); TableCellRenderer l = new TableCellRenderer() { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component result = delegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); ((JComponent) result).setToolTipText(String.valueOf(value)); return result; } }; return l; } /** * Creates and returns a core default tree cell renderer with tooltip. * @return */ private TreeCellRenderer createTreeRenderer() { final TreeCellRenderer delegate = new DefaultTreeCellRenderer(); TreeCellRenderer renderer = new TreeCellRenderer() { public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component result = delegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); ((JComponent) result).setToolTipText(String.valueOf(tree.getPathForRow(row))); return result; } }; return renderer; } /** * setting tree properties: tree not updated correctly. */ public void interactiveTestTreeProperties() { final JXTreeTable treeTable = new JXTreeTable(treeTableModel); Action toggleHandles = new AbstractAction("Toggle Handles") { public void actionPerformed(ActionEvent e) { treeTable.setShowsRootHandles(!treeTable.getShowsRootHandles()); } }; Action toggleRoot = new AbstractAction("Toggle Root") { public void actionPerformed(ActionEvent e) { treeTable.setRootVisible(!treeTable.isRootVisible()); } }; treeTable.setRowHeight(22); JXFrame frame = wrapWithScrollingInFrame(treeTable, "Toggle Tree properties "); addAction(frame, toggleRoot); addAction(frame, toggleHandles); frame.setVisible(true); } /** * Issue #242: CCE when setting icons. Not reproducible? * Another issue: icon setting does not repaint (with core default renderer) * Does not work at all with SwingX renderer (not surprisingly, the * delegating renderer in JXTree looks for a core default to wrap). * Think: tree/table should trigger repaint? */ public void interactiveTestTreeIcons() { final JXTreeTable treeTable = new JXTreeTable(treeTableModel); final Icon downIcon = XTestUtils.loadDefaultIcon("wellbottom.gif"); final Icon upIcon = XTestUtils.loadDefaultIcon("welltop.gif"); Action toggleClosedIcon = new AbstractAction("Toggle closed icon") { boolean down; public void actionPerformed(ActionEvent e) { if (down) { treeTable.setClosedIcon(downIcon); } else { treeTable.setClosedIcon(upIcon); } down = !down; // need to force - but shouldn't that be done in the // tree/table itself? and shouldn't the tree fire a // property change? //treeTable.repaint(); } }; treeTable.setRowHeight(22); JXFrame frame = wrapWithScrollingInFrame(treeTable, "Toggle Tree icons "); // addAction(frame, toggleRoot); addAction(frame, toggleClosedIcon); frame.setVisible(true); } /** issue #148 * did not work on LFs which normally respect lineStyle * winLF does not respect it anyway... */ public void interactiveTestFilterHighlightAndLineStyle() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); // issue #148 // did not work on LFs which normally respect lineStyle // winLF does not respect it anyway... treeTable.putClientProperty("JTree.lineStyle", "Angled"); treeTable.setRowHeight(22); // add a bunch of highlighters directly treeTable.addHighlighter( HighlighterFactory.createSimpleStriping(HighlighterFactory.QUICKSILVER)); Highlighter hl = new ShadingColorHighlighter( new ColumnHighlightPredicate(0)); treeTable.addHighlighter(hl); treeTable.addHighlighter(new ColorHighlighter(new PatternPredicate(Pattern.compile("^s", Pattern.CASE_INSENSITIVE), 0), null, Color.red)); JFrame frame = wrapWithScrollingInFrame(treeTable, "QuickSilver-, Column-, PatternHighligher and LineStyle"); frame.setVisible(true); } /** * Issue #204: weird filtering. * */ public void interactiveTestFilters() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); treeTable.putClientProperty("JTree.lineStyle", "Angled"); treeTable.setRowHeight(22); treeTable.setFilters(new FilterPipeline(new Filter[] { new PatternFilter( "^d", Pattern.CASE_INSENSITIVE, 0), })); JFrame frame = wrapWithScrollingInFrame(treeTable, "PatternFilter"); frame.setVisible(true); } /** * Issue #??: weird sorting. * */ public void interactiveTestSortingFilters() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); treeTable.setRowHeight(22); treeTable.setFilters(new FilterPipeline(new Filter[] { new ShuttleSorter(1, false), })); JFrame frame = wrapWithScrollingInFrame(treeTable, "SortingFilter"); frame.setVisible(true); } public void interactiveTestHighlightAndRowHeight() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); treeTable.setRowHeight(22); Highlighter hl = new ShadingColorHighlighter( new ColumnHighlightPredicate(0)); treeTable.setHighlighters( HighlighterFactory.createSimpleStriping(HighlighterFactory.LINE_PRINTER), hl); JFrame frame = wrapWithScrollingInFrame(treeTable, "LinePrinter-, ColumnHighlighter and RowHeight"); frame.setVisible(true); } public void interactiveTestAlternateRowHighlighter() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); treeTable.addHighlighter( HighlighterFactory.createSimpleStriping(HighlighterFactory.LINE_PRINTER)); treeTable.setRowHeight(22); JFrame frame = wrapWithScrollingInFrame(treeTable, "ClassicLinePrinter and RowHeight"); frame.setVisible(true); } public void interactiveTestBackgroundHighlighter() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); Highlighter hl = new ShadingColorHighlighter( new ColumnHighlightPredicate(0)); treeTable.setHighlighters( HighlighterFactory.createSimpleStriping(HighlighterFactory.LINE_PRINTER), hl); treeTable.setBackground(new Color(0xFF, 0xFF, 0xCC)); // notepad treeTable.setGridColor(Color.cyan.darker()); treeTable.setRowHeight(22); treeTable.setShowGrid(true, false); JFrame frame = wrapWithScrollingInFrame(treeTable, "NotePadBackground- HierarchicalColumnHighlighter and horiz lines"); frame.setVisible(true); } public void interactiveTestLedgerBackground() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); treeTable.setBackground(new Color(0xF5, 0xFF, 0xF5)); // ledger treeTable.setGridColor(Color.cyan.darker()); treeTable.setRowHeight(22); treeTable.setShowGrid(true, false); JFrame frame = wrapWithScrollingInFrame(treeTable, "LedgerBackground"); frame.setVisible(true); } /** * Requirement: color the leafs of the hierarchical columns differently. * * http://forums.java.net/jive/thread.jspa?messageID=165876 * * */ public void interactiveTestHierarchicalColumnHighlightConditional() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); HighlightPredicate hierarchical = new ColumnHighlightPredicate(0); treeTable.addHighlighter(new ShadingColorHighlighter(hierarchical)); HighlightPredicate predicate = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { return adapter.isLeaf(); } }; ColorHighlighter highlighter = new ColorHighlighter(new AndHighlightPredicate(hierarchical, predicate), new Color(247,246,239), null); treeTable.addHighlighter(highlighter); showWithScrollingInFrame(treeTable, "HierarchicalColumn And Conditional "); } public void interactiveTestHierarchicalColumnHighlight() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); Highlighter hl = new ShadingColorHighlighter( new ColumnHighlightPredicate(0)); treeTable.addHighlighter(hl); JFrame frame = wrapWithScrollingInFrame(treeTable, "HierarchicalColumnHigh"); frame.setVisible(true); } public void interactiveTestIntercellSpacing1() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); treeTable.setIntercellSpacing(new Dimension(1, 1)); treeTable.setShowGrid(true); JFrame frame = wrapWithScrollingInFrame(treeTable, "Intercellspacing 1"); frame.setVisible(true); } public void interactiveTestIntercellSpacing2() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); treeTable.setIntercellSpacing(new Dimension(2, 2)); treeTable.setShowGrid(true); JFrame frame = wrapWithScrollingInFrame(treeTable, "Intercellspacing 2"); frame.setVisible(true); } public void interactiveTestIntercellSpacing3() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); treeTable.setIntercellSpacing(new Dimension(3, 3)); treeTable.setShowGrid(true); JFrame frame = wrapWithScrollingInFrame(treeTable, "Intercellspacing 3"); frame.setVisible(true); } public void interactiveTestHighlighterRowHeight() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); treeTable.addHighlighter(new ColorHighlighter(Color.orange, null)); treeTable.setIntercellSpacing(new Dimension(15, 15)); treeTable.setRowHeight(48); JFrame frame = wrapWithScrollingInFrame(treeTable, "Orange, big rowheight"); frame.setVisible(true); } public void interactiveTestDepthHighlighter() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); treeTable.addHighlighter(new ColorHighlighter(new DepthHighlightPredicate(1), Color.MAGENTA, null)); treeTable.setIntercellSpacing(new Dimension(15, 15)); treeTable.setRowHeight(48); JFrame frame = wrapWithScrollingInFrame(treeTable, "Magenta depth 1, big rowheight"); frame.setVisible(true); } public void interactiveTestHighlighters() { JXTreeTable treeTable = new JXTreeTable(treeTableModel); treeTable.setIntercellSpacing(new Dimension(15, 15)); treeTable.setRowHeight(48); // not supported in JXTreeTable // treeTable.setRowHeight(0, 96); treeTable.setShowGrid(true); // set a bunch of highlighters as a pipeline Highlighter hl = new ShadingColorHighlighter( new ColumnHighlightPredicate(0)); treeTable.setHighlighters( new ColorHighlighter(Color.orange, null), hl, new ColorHighlighter(new PatternPredicate("D", 0), null, Color.red)); HighlightPredicate predicate = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { return adapter.hasFocus(); } }; // add the conditional highlighter laterb treeTable.addHighlighter(new ColorHighlighter(new AndHighlightPredicate(predicate, new ColumnHighlightPredicate(0)), Color.BLUE, Color.WHITE)); JFrame frame = wrapWithScrollingInFrame(treeTable, "Highlighters: conditional, orange, hierarchy, pattern D"); frame.setVisible(true); } } swingx-1.0-src/src/test/org/jdesktop/swingx/graphics/0000755000175000017500000000000011210401736021514 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/graphics/GraphicsUtilitiesVisualCheck.java0000644000175000017500000000443111210401722030132 0ustar tonytony/* * $Id: GraphicsUtilitiesVisualCheck.java,v 1.1 2008/03/21 12:57:39 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.graphics; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXImagePanel; /** * GraphicsUtilities visual checks. * * @author rah003 */ public class GraphicsUtilitiesVisualCheck extends InteractiveTestCase { public static void main(String[] args) { GraphicsUtilitiesVisualCheck test = new GraphicsUtilitiesVisualCheck(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #524-swingx: Thumbnails not generated correctly. * */ public void interactiveMistargetedKeyStrokes() throws Exception { BufferedImage im = ImageIO.read(getClass().getResourceAsStream( "/org/jdesktop/swingx/resources/images/500by500.png")); System.out.println("size:" + im.getWidth() + ", " + im.getHeight()); BufferedImage im2 = GraphicsUtilities.createThumbnail(im, 100); JXImagePanel ipa = new JXImagePanel(); ipa.setImage(im2); showInFrame(ipa, "default - for debugging only"); } /** * do nothing test - keep the test runner happy. */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/graphics/BlenderVisualCheck.java0000644000175000017500000001002111210401722026041 0ustar tonytony/* * $Id: BlenderVisualCheck.java,v 1.3 2008/01/11 14:01:33 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.graphics; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.JComponent; import javax.swing.JPanel; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXImagePanel; import org.jdesktop.swingx.JXMonthViewVisualCheck; /** * JW: renamed from PainterInteractiveTest to fix the build failure. Revisit! * @author rbair */ public class BlenderVisualCheck extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(JXMonthViewVisualCheck.class .getName()); public static void main(String[] args) { // setSystemLF(true); BlenderVisualCheck test = new BlenderVisualCheck(); try { test.runInteractiveTests(); // test.runInteractiveTests(".*Move.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #563-swingx: arrow keys active even if not focused. * focus the button and use the arrow keys: selection moves. * Reason was that the WHEN_IN_FOCUSED_WINDOW key bindings * were always installed. * * Fixed by dynamically bind/unbind component input map bindings * based on the JXMonthView's componentInputMapEnabled property. * */ public void interactiveMistargetedKeyStrokes() throws Exception { JComponent panel = new JPanel(); JXImagePanel ipa = new JXImagePanel() { @Override public void paint(Graphics g) { g.setColor(Color.BLACK); g.fillRect(0, 0, getWidth(), getHeight()); super.paint(g); } }; ipa.setImage(ImageIO.read(getClass().getResourceAsStream("/org/jdesktop/swingx/resources/images/dog.jpg"))); showInFrame(ipa, "default - for debugging only"); } /** * Issue #563-swingx: arrow keys active even if not focused. * focus the button and use the arrow keys: selection moves. * Reason was that the WHEN_IN_FOCUSED_WINDOW key bindings * were always installed. * * Fixed by dynamically bind/unbind component input map bindings * based on the JXMonthView's componentInputMapEnabled property. * */ public void interactiveMistargetedKeyStrokes2() throws Exception { JXImagePanel ipa = new JXImagePanel() { @Override public void paint(Graphics g) { super.paint(g); BlendComposite bc = BlendComposite.getInstance(BlendComposite.BlendingMode.COLOR); ((Graphics2D) g).setComposite(bc); g.setColor(Color.BLACK); g.fillRect(0, 0, getWidth(), getHeight()); } }; ipa.setImage(ImageIO.read(getClass().getResourceAsStream("/org/jdesktop/swingx/resources/images/dog.jpg"))); showInFrame(ipa, "default - for debugging only"); } /** * do nothing test - keep the testrunner happy. */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXTaskPaneIssues.java0000644000175000017500000001101511210401724023716 0ustar tonytony/* * $Id: JXTaskPaneIssues.java,v 1.10 2008/09/04 10:27:05 kleopatra Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.logging.Logger; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.KeyStroke; import org.jdesktop.swingx.action.AbstractActionExt; /** * * @author Jeanette Winzenburg */ public class JXTaskPaneIssues extends InteractiveTestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger.getLogger(JXTaskPaneIssues.class .getName()); public static void main(String[] args) { JXTaskPaneIssues test = new JXTaskPaneIssues(); try { test.runInteractiveTests(); } catch (Exception e) { e.printStackTrace(); } } /** * Trying to resize a top-level window on collapsed state changes of a taskpane. * Need to listen to "animationState" which is fired when animation is complete. */ public void interactiveDialogWithCollapsible() { JXTaskPane pane = new JXTaskPane(); pane.setTitle("dummy ... with a looooooooooooong title"); Action action = new AbstractActionExt("something to click") { public void actionPerformed(ActionEvent e) { LOG.info("got me"); } }; JComponent button = (JComponent) pane.add(action); Object actionKey = "dummy"; button.getActionMap().put(actionKey, action); KeyStroke keyStroke = KeyStroke.getKeyStroke("F3"); button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, actionKey); final JXDialog dialog = new JXDialog(pane); PropertyChangeListener l = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if ("animationState".equals(evt.getPropertyName())) { dialog.pack(); } } }; pane.addPropertyChangeListener(l); dialog.pack(); dialog.setVisible(true); } /** * Quick check to see if hidden comps receive a keybinding (no). */ public void interactiveDialogWithHidden() { JXPanel pane = new JXPanel(new BorderLayout()); final JButton label = new JButton("dummy ... with a looooooooooooong title"); Action action = new AbstractActionExt("something to click") { public void actionPerformed(ActionEvent e) { LOG.info("got me"); } }; pane.add(label); Object actionKey = "dummy"; label.getActionMap().put(actionKey, action); KeyStroke keyStroke = KeyStroke.getKeyStroke("F3"); label.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, actionKey); Action hide = new AbstractActionExt("hide other, then press F3") { public void actionPerformed(ActionEvent e) { // OOPS ... visible is _not_ a bean property // so property change listener is useless if we want to pack label.setVisible(!label.isVisible()); } }; pane.add(new JButton(hide), BorderLayout.NORTH); final JXDialog dialog = new JXDialog(pane); dialog.setTitle("hiding a component plain "); dialog.pack(); dialog.setVisible(true); } /** * Empty test method to keep the test runner happy if we have no * open issues. */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXTableUnitTest.java0000644000175000017500000044242011210401722023551 0ustar tonytony/* * $Id: JXTableUnitTest.java,v 1.147 2009/03/01 16:55:46 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GraphicsEnvironment; import java.awt.KeyboardFocusManager; import java.beans.PropertyChangeListener; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.sql.Time; import java.sql.Timestamp; import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Set; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.swing.Action; import javax.swing.DefaultCellEditor; import javax.swing.DefaultListSelectionModel; import javax.swing.InputMap; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; import org.jdesktop.swingx.JXTable.GenericEditor; import org.jdesktop.swingx.action.BoundAction; import org.jdesktop.swingx.decorator.AbstractHighlighter; import org.jdesktop.swingx.decorator.ColorHighlighter; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.Filter; import org.jdesktop.swingx.decorator.FilterPipeline; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.PatternFilter; import org.jdesktop.swingx.decorator.PatternPredicate; import org.jdesktop.swingx.decorator.ShuttleSorter; import org.jdesktop.swingx.decorator.SortKey; import org.jdesktop.swingx.decorator.SortOrder; import org.jdesktop.swingx.decorator.Sorter; import org.jdesktop.swingx.hyperlink.LinkModel; import org.jdesktop.swingx.renderer.DefaultTableRenderer; import org.jdesktop.swingx.renderer.StringValue; import org.jdesktop.swingx.renderer.StringValues; import org.jdesktop.swingx.rollover.RolloverController; import org.jdesktop.swingx.rollover.RolloverProducer; import org.jdesktop.swingx.rollover.TableRolloverController; import org.jdesktop.swingx.table.ColumnControlButton; import org.jdesktop.swingx.table.ColumnFactory; import org.jdesktop.swingx.table.NumberEditorExt; import org.jdesktop.swingx.table.TableColumnExt; import org.jdesktop.test.AncientSwingTeam; import org.jdesktop.test.CellEditorReport; import org.jdesktop.test.PropertyChangeReport; import org.jdesktop.test.TestUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests of JXTable. * * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class JXTableUnitTest extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(JXTableUnitTest.class .getName()); protected DynamicTableModel tableModel = null; protected TableModel sortableTableModel; // flag used in setup to explicitly choose LF private boolean defaultToSystemLF; // stored ui properties to reset in teardown private Object uiTableRowHeight; public JXTableUnitTest() { super("JXTable unit test"); } @Before public void setUpJu4() throws Exception { // just a little conflict between ant and maven builds // junit4 @before methods needs to be public, while // junit3 setUp() inherited from super is protected this.setUp(); } @Override protected void setUp() throws Exception { super.setUp(); // set loader priority to normal if (tableModel == null) { tableModel = new DynamicTableModel(); } sortableTableModel = new AncientSwingTeam(); // make sure we have the same default for each test defaultToSystemLF = true; setSystemLF(defaultToSystemLF); uiTableRowHeight = UIManager.get("JXTable.rowHeight"); } @Override @After public void tearDown() throws Exception { UIManager.put("JXTable.rowHeight", uiTableRowHeight); super.tearDown(); } /** * Issue #847-swingx: JXTable respect custom corner if columnControl not visible * * LAF provided corners are handled in core since jdk6u10. */ @Test public void testCornerRespectLAF() { Object corner = UIManager.get("Table.scrollPaneCornerComponent"); if (!(corner instanceof Class)) { LOG.info("cannont run - LAF doesn't provide corner component"); return; } final JXTable table = new JXTable(10, 2); final JScrollPane scrollPane = new JScrollPane(table); table.addNotify(); assertNotNull(scrollPane.getCorner(JScrollPane.UPPER_TRAILING_CORNER)); assertEquals(corner, scrollPane.getCorner(JScrollPane.UPPER_TRAILING_CORNER).getClass()); } /** * Issue #924-swingx: problems indy rowheight and filters. * * ArrayIndexOutOfBounds on insert. * */ @Test public void testIndividualRowHeightAndFilterInsert() { JXTable table = new JXTable(createAscendingModel(0, 50)); table.setRowHeightEnabled(true); table.setRowHeight(1, 100); final FilterPipeline filterPipeline = new FilterPipeline(new PatternFilter("[123]",0,0)); table.setFilters(filterPipeline); // sanity assertEquals(1, table.getValueAt(0, 0)); ((DefaultTableModel) table.getModel()).addRow(new Object[] {1, null, null, null}); } /** * Issue #924-swingx: problems indy rowheight and filters. * * ArrayIndexOutOfBounds on remove. * */ @Test public void testIndividualRowHeightAndFilterRemove() { JXTable table = new JXTable(createAscendingModel(0, 50)); table.setRowHeightEnabled(true); table.setRowHeight(1, 100); final FilterPipeline filterPipeline = new FilterPipeline(new PatternFilter("[123]",0,0)); table.setFilters(filterPipeline); // sanity assertEquals(1, table.getValueAt(0, 0)); ((DefaultTableModel) table.getModel()).removeRow(table.getModel().getRowCount() - 1); } /** * Issue #550-swingx: xtable must not reset columns' pref/size on * structureChanged if autocreate is false. * * here: width (was no problem, default columnFactory only sets pref) */ @Test public void testInitializeColumnWidth() { JXTable table = new JXTable(10, 2); table.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF); table.setAutoCreateColumnsFromModel(false); int width = table.getColumn(0).getWidth() + 2; table.getColumn(0).setWidth(width); assertEquals("sanity: ", width, table.getColumn(0).getWidth()); table.tableChanged(null); assertEquals("structure changed must not resize column", width, table.getColumn(0).getWidth() ); } /** * Issue #550-swingx: xtable must not reset columns' pref/width on * structureChanged if autocreate is false. * * here: prefWidth */ @Test public void testInitializeColumnPrefWidth() { JXTable table = new JXTable(10, 2); table.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF); table.setAutoCreateColumnsFromModel(false); int width = table.getColumn(0).getPreferredWidth() + 2; table.getColumn(0).setPreferredWidth(width); assertEquals("sanity: ", width, table.getColumn(0).getPreferredWidth()); table.tableChanged(null); assertEquals("structure changed must not resize column", width, table.getColumn(0).getPreferredWidth() ); } /** * Issue #847-swingx: JXTable respect custom corner if columnControl not visible * * Test correct un-/config on toggling the controlVisible property */ @Test public void testColumnControlVisible() { JXTable table = new JXTable(10, 2); JScrollPane scrollPane = new JScrollPane(table); table.setColumnControlVisible(true); assertSame("sanity: column control set", table.getColumnControl(), scrollPane.getCorner(JScrollPane.UPPER_TRAILING_CORNER)); table.setColumnControlVisible(false); assertEquals("columnControl must be removed from corner if not visible", null, scrollPane.getCorner(JScrollPane.UPPER_TRAILING_CORNER)); } /** * Issue #847-swingx: JXTable respect custom corner if columnControl not visible * * @throws Exception */ @Test public void testCornerRespectCustom() throws Exception { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run testCornerNPE - headless environment"); return; } final JXTable table = new JXTable(10, 2); final JScrollPane scrollPane = new JScrollPane(table); final JFrame frame = new JFrame(); frame.add(scrollPane); frame.pack(); SwingUtilities.invokeAndWait(new Runnable() { public void run() { JPanel panel = new JPanel(); scrollPane.setCorner(JScrollPane.UPPER_TRAILING_CORNER, panel); assertEquals("sanity ...", panel, scrollPane.getCorner(JScrollPane.UPPER_TRAILING_CORNER)); frame.remove(scrollPane); frame.add(scrollPane); if (table.isColumnControlVisible()) { assertEquals(table.getColumnControl(), scrollPane.getCorner(JScrollPane.UPPER_TRAILING_CORNER)); } else { assertEquals("xTable respects custom corner if columnControl invisible", panel, scrollPane.getCorner(JScrollPane.UPPER_TRAILING_CORNER)); } } }); } /** * Issue #844-swingx: JXTable throws NPE with custom corner. * * @throws Exception */ @Test public void testCornerNPE() throws Exception { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run testCornerNPE - headless environment"); return; } JXTable table = new JXTable(10, 2); final JScrollPane scrollPane = new JScrollPane(table); final JFrame frame = new JFrame(); frame.add(scrollPane); frame.pack(); SwingUtilities.invokeAndWait(new Runnable() { public void run() { scrollPane.setCorner(JScrollPane.UPPER_TRAILING_CORNER, new JPanel()); assertNotNull("sanity ...", scrollPane.getCorner(JScrollPane.UPPER_TRAILING_CORNER)); frame.remove(scrollPane); frame.add(scrollPane); } }); } /** * Issue #844-swingx: JXTable throws NPE with custom corner. * Regression testing (Issue #155-swingx) - scrollpane policy must be respected. * @throws Exception */ @Test public void testCornerNPEVerticalSPPolicy() throws Exception { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run testCornerNPE - headless environment"); return; } final JXTable table = new JXTable(10, 2); final JScrollPane scrollPane = new JScrollPane(table); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); table.setColumnControlVisible(true); final JFrame frame = new JFrame(); frame.add(scrollPane); frame.pack(); SwingUtilities.invokeAndWait(new Runnable() { public void run() { frame.remove(scrollPane); frame.add(scrollPane); assertSame(table.getColumnControl(), scrollPane.getCorner(JScrollPane.UPPER_TRAILING_CORNER)); table.setColumnControlVisible(false); assertEquals(JScrollPane.VERTICAL_SCROLLBAR_NEVER, scrollPane.getVerticalScrollBarPolicy()); } }); } /** * Issue #844-swingx: JXTable throws NPE with custom corner. * Regression testing (Issue #155-swingx) - scrollpane policy must be respected. */ @Test public void testCornerNPEVerticalSPOnUpdateUI(){ final JXTable table = new JXTable(10, 2); final JScrollPane scrollPane = new JScrollPane(table); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); table.setColumnControlVisible(true); table.updateUI(); table.setColumnControlVisible(false); assertEquals(JScrollPane.VERTICAL_SCROLLBAR_NEVER, scrollPane.getVerticalScrollBarPolicy()); } /** * Issue #838-swingx: table.prepareRenderer adds bogey listener to column highlighter. * */ @Test public void testColumnHighlighterListener() { JXTable table = new JXTable(10, 2); ColorHighlighter highlighter = new ColorHighlighter(); table.getColumnExt(0).addHighlighter(highlighter); int listenerCount = highlighter.getChangeListeners().length; assertEquals(1, listenerCount); table.prepareRenderer(table.getCellRenderer(0, 0), 0, 0); assertEquals(listenerCount, highlighter.getChangeListeners().length); } /** * Issue #767-swingx: consistent string representation. * * Here: test api on JXTable. */ @Test public void testGetString() { JXTable table = new JXTable(new AncientSwingTeam()); StringValue sv = new StringValue() { public String getString(Object value) { if (value instanceof Color) { Color color = (Color) value; return "R/G/B: " + color.getRGB(); } return StringValues.TO_STRING.getString(value); } }; table.setDefaultRenderer(Color.class, new DefaultTableRenderer(sv)); String text = table.getStringAt(0, 2); assertEquals(sv.getString(table.getValueAt(0, 2)), text); } @Test public void testCancelEditEnabled() { JXTable table = new JXTable(10, 3); table.editCellAt(0, 0); // sanity assertTrue(table.isEditing()); assertEquals(table.isEditing(), table.getActionMap().get("cancel").isEnabled()); } @Test public void testCancelEditDisabled() { JXTable table = new JXTable(10, 3); // sanity assertFalse(table.isEditing()); assertEquals(table.isEditing(), table.getActionMap().get("cancel").isEnabled()); } /** * NPE if Generic editor barks about constructor. Hacked around ... * * PENDING JW: too verbose ... strip down to essentials */ @Test public void testGenericEditorNPE() { Date date = new Date(); java.sql.Date sqlDate = new java.sql.Date(date.getTime()); Timestamp stamp = new Timestamp(date.getTime()); Time time = new Time(date.getTime()); DefaultTableModel model = new DefaultTableModel(1, 5) { @Override public Class getColumnClass(int columnIndex) { if (getRowCount() > 0) { Object value = getValueAt(0, columnIndex); if (value != null) { return value.getClass(); } } return super.getColumnClass(columnIndex); } }; model.setColumnIdentifiers(new Object[]{"Date - normal", "SQL Date", "SQL Timestamp", "SQL Time", "Date - as time"}); model.setValueAt(date, 0, 0); model.setValueAt(sqlDate, 0, 1); model.setValueAt(stamp, 0, 2); model.setValueAt(time, 0, 3); model.setValueAt(date, 0, 4); JXTable table = new JXTable(model); table.editCellAt(0, 1); } /** * test that transferFocus methods try to stop edit. * * Here: do nothing if !isTerminateEditOnFocusLost. * */ @Test public void testFocusTransferBackwardTerminateEditFalse() { JXTable table = new JXTable(10, 2); table.setTerminateEditOnFocusLost(false); DefaultCellEditor editor = new DefaultCellEditor(new JTextField()); // need to replace generic editor - which fires twice table.setDefaultEditor(Object.class, editor); table.editCellAt(0, 0); // sanity assertTrue(table.isEditing()); CellEditorReport report = new CellEditorReport(); table.getCellEditor().addCellEditorListener(report); table.transferFocusBackward(); assertTrue("table must be editing", table.isEditing()); assertEquals("", 0, report.getEventCount()); } /** * test that transferFocus methods try to stop edit. * * Here: do nothing if !isTerminateEditOnFocusLost. * */ @Test public void testFocusTransferForwardTerminateEditFalse() { JXTable table = new JXTable(10, 2); table.setTerminateEditOnFocusLost(false); DefaultCellEditor editor = new DefaultCellEditor(new JTextField()); // need to replace generic editor - which fires twice table.setDefaultEditor(Object.class, editor); table.editCellAt(0, 0); // sanity assertTrue(table.isEditing()); CellEditorReport report = new CellEditorReport(); table.getCellEditor().addCellEditorListener(report); table.transferFocus(); assertTrue("table must be editing", table.isEditing()); assertEquals("", 0, report.getEventCount()); } /** * test that transferFocus methods try to stop edit. * * Here: respect false on backward. * */ @Test public void testFocusTransferBackwardStopEditingFalse() { JXTable table = new JXTable(10, 2); DefaultCellEditor editor = new DefaultCellEditor(new JTextField()){ @Override public boolean stopCellEditing() { return false; } }; // need to replace generic editor - which fires twice table.setDefaultEditor(Object.class, editor); table.editCellAt(0, 0); // sanity assertTrue(table.isEditing()); CellEditorReport report = new CellEditorReport(); table.getCellEditor().addCellEditorListener(report); table.transferFocusBackward(); assertTrue("table must be editing", table.isEditing()); assertEquals("", 0, report.getEventCount()); } /** * test that transferFocus methods try to stop edit. * * Here: respect editor false on forward. * */ @Test public void testFocusTransferForwardStopEditingFalse() { JXTable table = new JXTable(10, 2); DefaultCellEditor editor = new DefaultCellEditor(new JTextField()){ @Override public boolean stopCellEditing() { return false; } }; // need to replace generic editor - which fires twice table.setDefaultEditor(Object.class, editor); table.editCellAt(0, 0); // sanity assertTrue(table.isEditing()); CellEditorReport report = new CellEditorReport(); table.getCellEditor().addCellEditorListener(report); table.transferFocus(); assertTrue("table must be editing", table.isEditing()); assertEquals("", 0, report.getEventCount()); } /** * test that transferFocus methods try to stop edit. * * Here: edit stopped and editor fires on backward. * */ @Test public void testFocusTransferBackwardStopEditing() { JXTable table = new JXTable(10, 2); // need to replace generic editor - which fires twice table.setDefaultEditor(Object.class, new DefaultCellEditor(new JTextField())); table.editCellAt(0, 0); // sanity assertTrue(table.isEditing()); CellEditorReport report = new CellEditorReport(); table.getCellEditor().addCellEditorListener(report); table.transferFocusBackward(); assertFalse("table must not be editing", table.isEditing()); assertEquals("", 1, report.getEventCount()); assertEquals("", 1, report.getStoppedEventCount()); } /** * test that transferFocus methods try to stop edit. * * Here: edit stopped and editor fired. * */ @Test public void testFocusTransferForwardStopEditing() { JXTable table = new JXTable(10, 2); // need to replace generic editor - which fires twice table.setDefaultEditor(Object.class, new DefaultCellEditor(new JTextField())); table.editCellAt(0, 0); // sanity assertTrue(table.isEditing()); CellEditorReport report = new CellEditorReport(); table.getCellEditor().addCellEditorListener(report); table.transferFocus(); assertFalse("table must not be editing", table.isEditing()); assertEquals("", 1, report.getEventCount()); assertEquals("", 1, report.getStoppedEventCount()); } /** * test that we have actions registered for forwared/backward * focus transfer. * */ @Test public void testFocusTransferActions() { JXTable table = new JXTable(); assertNotNull("must have forward action", table.getActionMap().get(JXTable.FOCUS_NEXT_COMPONENT)); assertNotNull("must have backward action", table.getActionMap().get(JXTable.FOCUS_PREVIOUS_COMPONENT)); } /** * test that we have bindings for forward/backward * focusTransfer. * */ @Test public void testFocusTransferKeyBinding() { JTable core = new JTable(); Set forwardKeys = core.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS); Set backwardKeys = core.getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS); JXTable table = new JXTable(); for (Object key : forwardKeys) { InputMap map = table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); assertNotNull("must have binding for forward focus transfer " + key, map.get((KeyStroke) key)); } for (Object key : backwardKeys) { InputMap map = table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); assertNotNull("must have binding for backward focus transfer " + key, map.get((KeyStroke) key)); } } /** * test that we have no focusTransfer keys set. * */ @Test public void testFocusTransferNoDefaultKeys() { JXTable table = new JXTable(); assertTrue(table.getFocusTraversalKeys( KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS).isEmpty()); assertTrue(table.getFocusTraversalKeys( KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS).isEmpty()); } /** * test that pref scrollable width is updated after structure changed. * */ @Test public void testPrefScrollableUpdatedOnStructureChanged() { JXTable compare = new JXTable(new AncientSwingTeam()); Dimension compareDim = compare.getPreferredScrollableViewportSize(); JXTable table = new JXTable(10, 6); Dimension initialDim = table.getPreferredScrollableViewportSize(); assertFalse("configured must be different from default width", compareDim.width == initialDim.width); table.setModel(compare.getModel()); assertEquals(compareDim.width, table.getPreferredScrollableViewportSize().width); } /** * Issue #508-swingx: cleanup scrollable support. * */ @Test public void testVisibleRowCountUpdateSize() { JXTable table = new JXTable(10, 6); Dimension dim = table.getPreferredScrollableViewportSize(); table.setVisibleRowCount(table.getVisibleRowCount() * 2); // change the pref width of a column, the pref scrollable width must not // be changed. This is testing the table internal reset code. TableColumnExt columnExt = table.getColumnExt(0); columnExt.setPreferredWidth(columnExt.getPreferredWidth() * 2); assertEquals(dim.height * 2, table.getPreferredScrollableViewportSize().height); assertEquals(dim.width, table.getPreferredScrollableViewportSize().width); } /** * Issue #508-swingx: cleanup scrollable support * */ @Test public void testVisibleColumnCountUpdateSize() { JXTable table = new JXTable(10, 14); table.setVisibleColumnCount(6); Dimension dim = table.getPreferredScrollableViewportSize(); table.setVisibleColumnCount(table.getVisibleColumnCount() * 2); assertEquals(dim.width * 2, table.getPreferredScrollableViewportSize().width); assertEquals(dim.height, table.getPreferredScrollableViewportSize().height); } /** * Issue #508-swingx: cleanup pref scrollable size. * test preference of explicit setting (over calculated). * */ @Test public void testPrefScrollableSetPreference() { JXTable table = new JXTable(10, 6); Dimension dim = table.getPreferredScrollableViewportSize(); Dimension other = new Dimension(dim.width + 20, dim.height + 20); table.setPreferredScrollableViewportSize(other); assertEquals(other, table.getPreferredScrollableViewportSize()); } /** * Issue #508-swingx: cleanup pref scrollable size. * test that max number of columns used for the preferred * scrollable width i getVisibleColumnCount * */ @Test public void testPrefScrollableWidthMoreColumns() { JXTable table = new JXTable(10, 7); table.setVisibleColumnCount(6); Dimension dim = table.getPreferredScrollableViewportSize(); // sanity assertEquals(table.getVisibleColumnCount() + 1, table.getColumnCount()); int width = 0; for (int i = 0; i < table.getVisibleColumnCount(); i++) { width += table.getColumn(i).getPreferredWidth(); } assertEquals(width, dim.width); } /** * Issue #508-swingx: cleanup pref scrollable size. * test that max number of columns used for the preferred * scrollable width i getVisibleColumnCount * */ @Test public void testPrefScrollableWidthLessColumns() { JXTable table = new JXTable(10, 5); table.setVisibleColumnCount(6); Dimension dim = table.getPreferredScrollableViewportSize(); // sanity assertEquals(table.getVisibleColumnCount() - 1, table.getColumnCount()); int width = 0; for (int i = 0; i < table.getColumnCount(); i++) { width += table.getColumn(i).getPreferredWidth(); } width += 75; assertEquals(width, dim.width); } /** * test change back to default sizing (use-all) * */ @Test public void testVisibleColumnCountNegative() { JXTable table = new JXTable(10, 7); Dimension dim = table.getPreferredScrollableViewportSize(); int visibleCount = table.getVisibleColumnCount(); // custom table.setVisibleColumnCount(4); // change back to default table.setVisibleColumnCount(visibleCount); assertEquals(dim, table.getPreferredScrollableViewportSize()); } /** * test default sizing: use all visible columns. * */ @Test public void testPrefScrollableWidthDefault() { JXTable table = new JXTable(10, 7); Dimension dim = table.getPreferredScrollableViewportSize(); assertEquals("default must use all visible columns", table.getColumnCount() * 75, dim.width); } /** * Issue #508-swingx: cleanup pref scrollable size. * Sanity: test initial visible column count. * */ @Test public void testDefaultVisibleColumnCount() { JXTable table = new JXTable(10, 6); assertEquals(-1, table.getVisibleColumnCount()); } /** * Issue #508-swingx: cleanup pref scrollable size. * test custom setting of visible column count. * */ @Test public void testVisibleColumnCount() { JXTable table = new JXTable(30, 10); int visibleColumns = 7; table.setVisibleColumnCount(visibleColumns); assertEquals(visibleColumns, table.getVisibleColumnCount()); Dimension dim = table.getPreferredScrollableViewportSize(); assertEquals(visibleColumns * 75, dim.width); } /** * Issue #508-swingx: cleanup pref scrollable size. * test that column widths are configured after setModel. * */ @Test public void testPrefColumnSetModel() { JXTable compare = new JXTable(new AncientSwingTeam()); // make sure the init is called compare.getPreferredScrollableViewportSize(); // table with arbitrary model JXTable table = new JXTable(30, 7); // make sure the init is called table.getPreferredScrollableViewportSize(); // following should init the column width ... table.setModel(compare.getModel()); for (int i = 0; i < table.getColumnCount(); i++) { assertEquals("prefwidths must be same at index " + i, compare.getColumnExt(i).getPreferredWidth(), table.getColumnExt(i).getPreferredWidth()); } } /** * Test bound property visibleRowCount. * */ @Test public void testVisibleRowCountProperty() { JXTable table = new JXTable(10, 7); int count = table.getVisibleRowCount(); PropertyChangeReport report = new PropertyChangeReport(); table.addPropertyChangeListener(report); table.setVisibleRowCount(count + 1); TestUtils.assertPropertyChangeEvent(report, "visibleRowCount", count, count+1); } /** * Test bound property visibleColumnCount. * */ @Test public void testVisibleColumnCountProperty() { JXTable table = new JXTable(10, 7); int count = table.getVisibleColumnCount(); PropertyChangeReport report = new PropertyChangeReport(); table.addPropertyChangeListener(report); table.setVisibleColumnCount(count + 1); TestUtils.assertPropertyChangeEvent(report, "visibleColumnCount", count, count+1); } /** * test doc'ed behaviour: set visible row count must * throw on negative row. * */ @Test public void testVisibleRowCountNegative() { JXTable table = new JXTable(10, 7); try { table.setVisibleRowCount(-2); fail("negative count must throw IllegalArgument"); } catch (IllegalArgumentException e) { // expected exception } } /** * Issue #547-swingx: return copy of pref scrollable size * */ @Test public void testPrefScrollableSafeCalculatedDim() { JXTable table = new JXTable(10, 6); // sanity: compare the normal dim returns assertNotSame("pref size must not be the same", table.getPreferredSize(), table.getPreferredSize()); assertNotSame("pref scrollable dim must not be the same", table.getPreferredScrollableViewportSize(), table.getPreferredScrollableViewportSize()); } /** * Issue #547-swingx: return copy of pref scrollable size * This is a super prob - does use the dim as set. */ @Test public void testPrefScrollableSafeFixedDim() { JXTable table = new JXTable(10, 6); Dimension dim = new Dimension(200, 400); // sanity: compare to super prf size when set table.setPreferredSize(dim); assertEquals(dim, table.getPreferredSize()); assertNotSame(dim, table.getPreferredSize()); table.setPreferredScrollableViewportSize(dim); assertNotSame("pref scrollable dim must not be the same", dim, table.getPreferredScrollableViewportSize()); } /** * Issue #547-swingx: pref scrollable height included header. * */ @Test public void testPrefScrollableHeight() { JXTable table = new JXTable(10, 6); Dimension dim = table.getPreferredScrollableViewportSize(); assertNotNull("pref scrollable must not be null", dim); assertEquals("scrollable height must no include header", table.getVisibleRowCount() * table.getRowHeight(), dim.height); } /** * Sanity: default visible row count == 20. * */ @Test public void testDefaultVisibleRowCount() { JXTable table = new JXTable(10, 6); assertEquals(20, table.getVisibleRowCount()); } /** * Issue #547-swingx: NPE in ColumnFactory configureColumnWidth * for hidden column * */ @Test public void testPrefHiddenColumnNPE() { JXTable table = new JXTable(new AncientSwingTeam()); TableColumnExt columnExt = table.getColumnExt(0); columnExt.setPrototypeValue("Jessesmariaandjosefsapperlottodundteufel"); columnExt.setVisible(false); // NPE table.getColumnFactory().configureColumnWidths(table, columnExt); } /** * Issue #547-swingx: NPE in ColumnFactory configureColumnWidth * for empty table .. no: doesn't because * table.getCellRenderer(row,column) does not use the row * coordinate - so the illegal argument doesn't hurt. * */ @Test public void testPrefEmptyTableNPE() { JXTable table = new JXTable(0, 4); TableColumnExt columnExt = table.getColumnExt(0); columnExt.setPrototypeValue("Jessesmariaandjosefsapperlottodundteufel"); // NPE table.getColumnFactory().configureColumnWidths(table, columnExt); } /** * Issue #547-swingx: hidden columns' pref width not initialized. * * PENDING: the default initialize is working as expected only * if the config is done before setting the model, that is * in the ColumnFactory. Need public api to programatically * trigger the init after the fact? */ @Test public void testPrefHiddenColumn() { JXTable table = new JXTable(new AncientSwingTeam()); TableColumnExt columnExt = table.getColumnExt(0); columnExt.setPrototypeValue("Jessesmariaandjosefsapperlottodundteufel"); TableCellRenderer renderer = table.getCellRenderer(0, 0); Component comp = renderer.getTableCellRendererComponent(null, columnExt.getPrototypeValue(), false, false, -1, -1); columnExt.setVisible(false); // make sure the column pref is initialized table.initializeColumnWidths(); assertEquals("hidden column's pref must be set", comp.getPreferredSize().width + table.getColumnMargin(), columnExt.getPreferredWidth()); } /** * Issue #547-swingx: columns' pref width - header not taken * if no prototype * */ @Test public void testPrefColumnTitle() { JXTable table = new JXTable(new AncientSwingTeam()); TableColumnExt columnExt = table.getColumnExt(0); columnExt.setHeaderValue("Jessesmariaandjosefsapperlottodundteufel"); TableCellRenderer renderer = table.getTableHeader().getDefaultRenderer(); Component comp = renderer.getTableCellRendererComponent(table, columnExt.getHeaderValue(), false, false, -1, -1); // need to store the pref - header renderer is used during initialize! Dimension prefSize = comp.getPreferredSize(); // make sure the column pref is initialized table.initializeColumnWidths(); assertEquals("header must be measured", prefSize.width + table.getColumnMargin(), columnExt.getPreferredWidth()); } /** * Issue #547-swingx: columns' pref width - without * prototype the pref is minimally the (magic) standard if * the header doesn't exceed it. * */ @Test public void testPrefStandardMinWithoutPrototype() { JXTable table = new JXTable(10, 6); TableColumnExt columnExt = table.getColumnExt(0); int standardWidth = columnExt.getPreferredWidth(); // make sure the column pref is initialized table.getPreferredScrollableViewportSize(); assertEquals("column pref width must be unchanged", standardWidth, columnExt.getPreferredWidth()); } /** * Issue #547-swingx: columns' pref width - added margin twice * if has prototype. * * PENDING: the default initialize is working as expected only * if the config is done before setting the model, that is * in the ColumnFactory. Need public api to programatically * trigger the init after the fact? */ @Test public void testPrefColumnsDuplicateMargin() { JXTable table = new JXTable(new AncientSwingTeam()); TableColumnExt columnExt = table.getColumnExt(0); // force the prototype longer than the title // to avoid that header measuring is triggered // header renderer can have bigger fonts columnExt.setPrototypeValue(columnExt.getTitle() + "longer"); TableCellRenderer renderer = table.getCellRenderer(0, 0); Component comp = renderer.getTableCellRendererComponent(null, columnExt.getPrototypeValue(), false, false, -1, -1); // make sure the column pref is initialized table.initializeColumnWidths(); assertEquals("column margin must be added once", table.getColumnMargin(), columnExt.getPreferredWidth() - comp.getPreferredSize().width); } /** * Issue #530-swingx: problems indy rowheight and filters * */ @Test public void testIndividualRowHeightAndFilter() { JXTable table = new JXTable(createAscendingModel(0, 50)); table.setRowHeightEnabled(true); table.setRowHeight(1, 100); final FilterPipeline filterPipeline = new FilterPipeline(new PatternFilter("[123]",0,0)); table.setFilters(filterPipeline); // sanity assertEquals(1, table.getValueAt(0, 0)); assertEquals(100, table.getRowHeight(0)); } /** * core issue: JTable cannot cope with null selection background. * */ @Test public void testSetSelectionBackground() { JXTable table = new JXTable(); PropertyChangeReport report = new PropertyChangeReport(); table.addPropertyChangeListener(report); Color oldBackground = table.getSelectionBackground(); Color color = Color.RED; table.setSelectionBackground(color); assertFalse(oldBackground.equals(table.getSelectionBackground())); assertEquals(color, table.getSelectionBackground()); TestUtils.assertPropertyChangeEvent(report, "selectionBackground", oldBackground, color); } /** * core issue: JTable cannot cope with null selection background. * */ @Test public void testNullSelectionBackground() { JXTable table = new JXTable(); table.setSelectionBackground(null); } /** * core issue: JTable cannot cope with null selection background. * */ @Test public void testSetSelectionForeground() { JXTable table = new JXTable(); PropertyChangeReport report = new PropertyChangeReport(); table.addPropertyChangeListener(report); Color oldForeground = table.getSelectionForeground(); Color color = Color.RED; table.setSelectionForeground(color); assertFalse(oldForeground.equals(table.getSelectionForeground())); assertEquals(color, table.getSelectionForeground()); TestUtils.assertPropertyChangeEvent(report, "selectionForeground", oldForeground, color); } /** * core issue: JTable cannot cope with null selection background. * */ @Test public void testNullSelectionForeground() { JXTable table = new JXTable(); table.setSelectionForeground(null); } /** * Test default behaviour: hack around DefaultTableCellRenderer * color memory is on. * */ @Test public void testDTCRendererHackEnabled() { JXTable table = new JXTable(10, 2); DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); table.setDefaultRenderer(Object.class, renderer); table.prepareRenderer(renderer, 0, 0); assertEquals(Boolean.TRUE, table.getClientProperty(JXTable.USE_DTCR_COLORMEMORY_HACK)); assertNotNull(renderer.getClientProperty("rendererColorMemory.background")); assertNotNull(renderer.getClientProperty("rendererColorMemory.foreground")); } /** * Test custom behaviour: hack around DefaultTableCellRenderer * color memory is disabled. * */ @Test public void testDTCRendererHackDisabled() { JXTable table = new JXTable(10, 2); table.putClientProperty(JXTable.USE_DTCR_COLORMEMORY_HACK, null); DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); table.setDefaultRenderer(Object.class, renderer); table.prepareRenderer(renderer, 0, 0); assertNull(renderer.getClientProperty("rendererColorMemory.background")); assertNull(renderer.getClientProperty("rendererColorMemory.foreground")); } /** * Issue #282-swingx: compare disabled appearance of * collection views. * */ @Test public void testDisabledRenderer() { JXList list = new JXList(new Object[] {"one", "two"}); list.setEnabled(false); // sanity assertFalse(list.isEnabled()); Component comp = list.getCellRenderer().getListCellRendererComponent(list, "some", 0, false, false); assertEquals(list.isEnabled(), comp.isEnabled()); JXTable table = new JXTable(10, 2); table.setEnabled(false); // sanity assertFalse(table.isEnabled()); comp = table.prepareRenderer(table.getCellRenderer(0, 0), 0, 0); assertEquals(table.isEnabled(), comp.isEnabled()); } /** * Test assumptions of accessing table model/view values through * the table's componentAdapter. * * PENDING: the default's getValue() implementation is incorrect! * */ @Test public void testComponentAdapterCoordinates() { JXTable table = new JXTable(createAscendingModel(0, 10)); Object originalFirstRowValue = table.getValueAt(0,0); Object originalLastRowValue = table.getValueAt(table.getRowCount() - 1, 0); assertEquals("view row coordinate equals model row coordinate", table.getModel().getValueAt(0, 0), originalFirstRowValue); // sort first column - actually does not change anything order table.toggleSortOrder(0); // sanity asssert assertEquals("view order must be unchanged ", table.getValueAt(0, 0), originalFirstRowValue); // invert sort table.toggleSortOrder(0); // sanity assert assertEquals("view order must be reversed changed ", table.getValueAt(0, 0), originalLastRowValue); ComponentAdapter adapter = table.getComponentAdapter(); assertEquals("adapter filteredValue expects row view coordinates", table.getValueAt(0, 0), adapter.getFilteredValueAt(0, 0)); // adapter coordinates are view coordinates adapter.row = 0; adapter.column = 0; assertEquals("adapter.getValue must return value at adapter coordinates", table.getValueAt(0, 0), adapter.getValue()); assertEquals("adapter.getValue must return value at adapter coordinates", table.getValueAt(0, 0), adapter.getValue(0)); } /** * Issue 373-swingx: table must unsort column on sortable change. * * Here we test if switching sortable to false on the sorted column * resets the sorting, special case hidden column. This fails * because columnModel doesn't fire property change events for * hidden columns (see Issue #369-swingx). * */ @Test public void testTableUnsortedColumnOnHiddenColumnSortableChange() { JXTable table = new JXTable(10, 2); TableColumnExt columnExt = table.getColumnExt(0); Object identifier = columnExt.getIdentifier(); table.toggleSortOrder(identifier); assertTrue(table.getSortOrder(identifier).isSorted()); columnExt.setVisible(false); assertTrue(table.getSortOrder(identifier).isSorted()); columnExt.setSortable(false); assertFalse("table must have unsorted column on sortable change", table.getSortOrder(identifier).isSorted()); } /** * Issue 373-swingx: table must unsort column on sortable change. * * Here we test if switching sortable to false on the sorted column * resets the sorting. * */ @Test public void testTableUnsortedColumnOnColumnSortableChange() { JXTable table = new JXTable(10, 2); TableColumnExt columnExt = table.getColumnExt(0); table.toggleSortOrder(0); assertTrue(table.getSortOrder(0).isSorted()); columnExt.setSortable(false); assertFalse("table must have unsorted column on sortable change", table.getSortOrder(0).isSorted()); } /** * Issue 373-swingx: table must unsort column on sortable change. * * Here we test if switching sortable to false on unsorted column has * no effect. */ @Test public void testTableSortedColumnOnNotSortedColumnSortableChange() { JXTable table = new JXTable(10, 2); int unsortedColumn = 1; TableColumnExt columnExt = table.getColumnExt(unsortedColumn); table.toggleSortOrder(0); assertTrue(table.getSortOrder(0).isSorted()); columnExt.setSortable(false); assertTrue("table must keep sortorder on unsorted column sortable change", table.getSortOrder(0).isSorted()); } /** * Issue 372-swingx: table must cancel edit if column property * changes to not editable. * Here we test if the table actually canceled the edit. */ @Test public void testTableCanceledEditOnColumnEditableChange() { JXTable table = new JXTable(10, 2); TableColumnExt columnExt = table.getColumnExt(0); table.editCellAt(0, 0); // sanity assertTrue(table.isEditing()); assertEquals(0, table.getEditingColumn()); TableCellEditor editor = table.getCellEditor(); CellEditorReport report = new CellEditorReport(); editor.addCellEditorListener(report); columnExt.setEditable(false); // sanity assertFalse(table.isCellEditable(0, 0)); assertEquals("editor must have fired canceled", 1, report.getCanceledEventCount()); assertEquals("editor must not have fired stopped",0, report.getStoppedEventCount()); } /** * Issue 372-swingx: table must cancel edit if column property * changes to not editable. * Here we test if the table is not editing after editable property * of the currently edited column is changed to false. */ @Test public void testTableNotEditingOnColumnEditableChange() { JXTable table = new JXTable(10, 2); TableColumnExt columnExt = table.getColumnExt(0); table.editCellAt(0, 0); // sanity assertTrue(table.isEditing()); assertEquals(0, table.getEditingColumn()); columnExt.setEditable(false); assertFalse(table.isCellEditable(0, 0)); assertFalse("table must have terminated edit",table.isEditing()); } /** * Issue 372-swingx: table must cancel edit if column property * changes to not editable. * Here we test if the table is still editing after the editability * change of a non-edited column. * */ @Test public void testTableEditingOnNotEditingColumnEditableChange() { JXTable table = new JXTable(10, 2); int notEditingColumn = 1; TableColumnExt columnExt = table.getColumnExt(notEditingColumn); table.editCellAt(0, 0); // sanity assertTrue(table.isEditing()); assertEquals(0, table.getEditingColumn()); columnExt.setEditable(false); assertFalse(table.isCellEditable(0, notEditingColumn)); assertTrue("table must still be editing", table.isEditing()); } /** * Issue 372-swingx: table must cancel edit if column property * changes to not editable. * Here we test if the table is still editing after the editability * change of a non-edited column, special case of hidden column.

* NOTE: doesn't really test, the columnModel doesn't * fire propertyChanges for hidden columns (see Issue #??-swingx) * */ @Test public void testTableEditingOnHiddenColumnEditableChange() { JXTable table = new JXTable(10, 2); int hiddenNotEditingColumn = 1; TableColumnExt columnExt = table.getColumnExt(hiddenNotEditingColumn); columnExt.setVisible(false); table.editCellAt(0, 0); // sanity assertTrue(table.isEditing()); assertEquals(0, table.getEditingColumn()); columnExt.setEditable(false); assertTrue("table must still be editing", table.isEditing()); } /** * Test if default column creation and configuration is * controlled completely by ColumnFactory. * */ @Test public void testColumnConfigControlledByFactory() { ColumnFactory factory = new ColumnFactory() { @Override public void configureTableColumn(TableModel model, TableColumnExt columnExt) { assertNull(columnExt.getHeaderValue()); } }; JXTable table = new JXTable(); table.setColumnFactory(factory); table.setModel(new DefaultTableModel(10, 2)); assertEquals(null, table.getColumn(0).getHeaderValue()); } /** * Sanity test for cleanup of createDefaultColumns. * */ @Test public void testColumnFactory() { JXTable table = new JXTable(sortableTableModel); List columns = table.getColumns(); // for all model columns and in same order.. assertEquals(sortableTableModel.getColumnCount(), columns.size()); for (int i = 0; i < sortableTableModel.getColumnCount(); i++) { // there must have been inserted a TableColumnExt with // title == headerValue == column name in model assertTrue(columns.get(i) instanceof TableColumnExt); assertEquals(sortableTableModel.getColumnName(i), String.valueOf(columns.get(i).getHeaderValue())); } } /** * Tests per-table ColumnFactory: bound property, reset to shared. * */ @Test public void testSetColumnFactory() { JXTable table = new JXTable(); PropertyChangeReport report = new PropertyChangeReport(); table.addPropertyChangeListener(report); ColumnFactory factory = createCustomColumnFactory(); table.setColumnFactory(factory); assertEquals(1, report.getEventCount()); assertTrue(report.hasEvents("columnFactory")); assertSame(factory, report.getLastNewValue("columnFactory")); assertSame(ColumnFactory.getInstance(), report.getLastOldValue("columnFactory")); report.clear(); table.setColumnFactory(null); assertEquals(1, report.getEventCount()); assertTrue(report.hasEvents("columnFactory")); assertSame(factory, report.getLastOldValue("columnFactory")); assertSame(ColumnFactory.getInstance(), report.getLastNewValue("columnFactory")); } /** * Tests per-table ColumnFactory: use individual. * */ @Test public void testUseCustomColumnFactory() { JXTable table = new JXTable(); PropertyChangeReport report = new PropertyChangeReport(); table.addPropertyChangeListener(report); ColumnFactory factory = createCustomColumnFactory(); table.setColumnFactory(factory); // sanity... assertSame(factory, report.getLastNewValue("columnFactory")); table.setModel(new DefaultTableModel(2, 5)); assertEquals(String.valueOf(0), table.getColumnExt(0).getTitle()); } /** * Creates and returns a custom columnFactory for testing. * Sets column title to modelIndex. * * @return the custom ColumnFactory. */ protected ColumnFactory createCustomColumnFactory() { ColumnFactory factory = new ColumnFactory() { @Override public void configureTableColumn(TableModel model, TableColumnExt columnExt) { super.configureTableColumn(model, columnExt); columnExt.setTitle(String.valueOf(columnExt.getModelIndex())); } }; return factory; } /** * Issue #4614616: renderer lookup broken for interface types. * */ @Test public void testNPERendererForInterface() { DefaultTableModel model = new DefaultTableModel(10, 2) { @Override public Class getColumnClass(int columnIndex) { return Comparable.class; } }; JXTable table = new JXTable(model); table.prepareRenderer(table.getCellRenderer(0, 0), 0, 0); } /** * Issue #366-swingx: enhance generic editor to take custom * textfield as argument. * */ @Test public void testGenericEditor() { JTextField textField = new JTextField(20); GenericEditor editor = new GenericEditor(textField); assertEquals("Table.editor", textField.getName()); // sanity assertSame(textField, editor.getComponent()); } /** * test default rowHeight calculation with default font. * Beware: the default height is the font's height + 2, but * bounded by a "magic" minimum of 18. */ @Test public void testRowHeightFromFont() { // sanity assertNull("no ui rowheight", UIManager.get("JXTable.rowHeight")); JXTable table = new JXTable(); // wrong assumption: there's a "magic" minimum of 18! int fontDerivedHeight = table.getFontMetrics(table.getFont()).getHeight() + 2; assertEquals("default rowHeight based on fontMetrics height " + "plus top plus bottom border (== 2)", Math.max(18, fontDerivedHeight), table.getRowHeight()); } /** * test default rowHeight calculation with bigger font. * */ @Test public void testRowHeightFromBigFont() { // sanity assertNull("no ui rowheight", UIManager.get("JXTable.rowHeight")); JXTable table = new JXTable(); table.setFont(table.getFont().deriveFont(table.getFont().getSize() * 2f)); table.updateUI(); assertEquals("default rowHeight based on fontMetrics height " + "plus top plus bottom border (== 2)", table.getFontMetrics(table.getFont()).getHeight() + 2, table.getRowHeight()); } /** * Issue #359-swingx: table doesn't respect ui-setting of rowheight. * * lower bound is enforced to "magic number", 18 * */ @Test public void testUIRowHeightLowerBound() { int tinyRowHeight = 5; UIManager.put("JXTable.rowHeight", tinyRowHeight); JXTable table = new JXTable(); assertEquals("table must respect ui rowheight", tinyRowHeight, table.getRowHeight()); } /** * Issue #359-swingx: table doesn't respect ui-setting of rowheight. * * upper bound is taken correctly. */ @Test public void testUIRowHeightUpperBound() { int monsterRowHeight = 50; UIManager.put("JXTable.rowHeight", monsterRowHeight); JXTable table = new JXTable(); assertEquals("table must respect ui rowheight", monsterRowHeight, table.getRowHeight()); } /** * Issue #342-swingx: default margins in JXTreeTable. * * This is not only a treeTable issue: the coupling of * margins to showing gridlines (and still get a "nice" * looking selection) is not overly obvious in JTable as * well. Added convenience method to adjust margins to * 0/1 if hiding/showing grid lines. * */ @Test public void testShowGrid() { JXTable table = new JXTable(10, 3); // sanity: initial margins are (1, 1), grid on assertEquals(1, table.getRowMargin()); assertTrue(table.getShowHorizontalLines()); assertEquals(1, table.getColumnMargin()); assertTrue(table.getShowVerticalLines()); // hide grid boolean show = false; table.setShowGrid(show, show); assertEquals(0, table.getRowMargin()); assertEquals(show, table.getShowHorizontalLines()); assertEquals(0, table.getColumnMargin()); assertEquals(show, table.getShowVerticalLines()); } /** * Issue ??-swingx: NPE if tableChanged is messaged with a null event. * */ @Test public void testNullTableEventNPE() { JXTable table = new JXTable(); // don't throw null events table.tableChanged(null); assertFalse(table.isUpdate(null)); assertFalse(table.isDataChanged(null)); assertTrue(table.isStructureChanged(null)); // correct detection of structureChanged TableModelEvent structureChanged = new TableModelEvent(table.getModel(), -1, -1); assertFalse(table.isUpdate(structureChanged)); assertFalse(table.isDataChanged(structureChanged)); assertTrue(table.isStructureChanged(structureChanged)); // correct detection of insert/remove TableModelEvent insert = new TableModelEvent(table.getModel(), 0, 10, -1, TableModelEvent.INSERT); assertFalse(table.isUpdate(insert)); assertFalse(table.isDataChanged(insert)); assertFalse(table.isStructureChanged(insert)); // correct detection of update TableModelEvent update = new TableModelEvent(table.getModel(), 0, 10); assertTrue(table.isUpdate(update)); assertFalse(table.isDataChanged(update)); assertFalse(table.isStructureChanged(update)); // correct detection of dataChanged TableModelEvent dataChanged = new TableModelEvent(table.getModel()); assertFalse(table.isUpdate(dataChanged)); assertTrue(table.isDataChanged(dataChanged)); assertFalse(table.isStructureChanged(dataChanged)); } /** * test new mutable columnControl api. * */ @Test public void testSetColumnControl() { JXTable table = new JXTable(); JComponent columnControl = table.getColumnControl(); assertTrue(columnControl instanceof ColumnControlButton); JComponent newControl = new JButton(); PropertyChangeReport report = new PropertyChangeReport(); table.addPropertyChangeListener(report); table.setColumnControl(newControl); assertSame(newControl, table.getColumnControl()); assertEquals(1, report.getEventCount()); assertEquals(1, report.getEventCount("columnControl")); assertSame(newControl, report.getLastNewValue("columnControl")); } /** * characterization tests: constructors and exceptions. * */ @Test public void testConstructorsWithNullArguments() { try { new JXTable((Object[][]) null, (Object[]) null); fail("null arrays must throw NPE"); } catch (NullPointerException e) { // nothing to do - expected } catch (Exception e) { fail("unexpected exception type (expected NPE)" + e); } try { new JXTable((Object[][]) null, new Object[] { }); fail("null arrays must throw NPE"); } catch (NullPointerException e) { // nothing to do - expected } catch (Exception e) { fail("unexpected exception type (expected NPE)" + e); } try { new JXTable(new Object[][] {{ }, { }}, (Object[]) null); fail("null arrays throw NPE"); } catch (NullPointerException e) { // nothing to do - expected } catch (Exception e) { fail("unexpected exception type (expected NPE)" + e); } } /** * expose JTable.autoStartsEdit. * */ @Test public void testAutoStartEdit() { JXTable table = new JXTable(10, 2); assertTrue(table.isAutoStartEditOnKeyStroke()); PropertyChangeReport report = new PropertyChangeReport(); table.addPropertyChangeListener(report); table.setAutoStartEditOnKeyStroke(false); assertFalse("autoStart must be toggled to false", table.isAutoStartEditOnKeyStroke()); // the following assumption is wrong because the old client property key is // different from the method name, leading to two events fired. // assertEquals(1, report.getEventCount()); assertEquals(1, report.getEventCount("autoStartEditOnKeyStroke")); } /** * add editable property. * */ @Test public void testEditable() { JXTable table = new JXTable(10, 2); assertTrue("default editable must be true", table.isEditable()); PropertyChangeReport report = new PropertyChangeReport(); table.addPropertyChangeListener(report); table.setEditable(!table.isEditable()); assertFalse("editable must be toggled to false", table.isEditable()); assertEquals(1, report.getEventCount()); assertEquals(1, report.getEventCount("editable")); } /** * test effect of editable on cell editing. * */ @Test public void testCellEditable() { JXTable table = new JXTable(10, 2); assertTrue("default table editable must be true", table.isEditable()); assertTrue("default cell editable must be true", table.isCellEditable(0, 0)); table.setEditable(!table.isEditable()); assertFalse("editable must be toggled to false", table.isEditable()); assertFalse("each cell must be not editable", table.isCellEditable(0, 0)); } /** * */ @Test public void testSetValueCellNotEditable() { JXTable table = new JXTable(10, 2); Object value = table.getValueAt(0, 0); table.setEditable(false); // sanity... assertFalse("each cell must be not editable", table.isCellEditable(0, 0)); table.setValueAt("wrong", 0, 0); assertEquals("cell value must not be changed", value, table.getValueAt(0, 0)); } /** * Issue #262-swingx: expose terminateEditOnFocusLost as property. * * setting client property is reflected in getter and results in event firing. * */ @Test public void testGetTerminateEditOnFocusLost() { JXTable table = new JXTable(); // sanity assert: setting client property set's property PropertyChangeReport report = new PropertyChangeReport(); table.addPropertyChangeListener(report); table.putClientProperty("terminateEditOnFocusLost", !table.isTerminateEditOnFocusLost()); assertEquals(table.getClientProperty("terminateEditOnFocusLost"), table.isTerminateEditOnFocusLost()); assertEquals(1, report.getEventCount()); assertEquals(1, report.getEventCount("terminateEditOnFocusLost")); } /** * Issue #262-swingx: expose terminateEditOnFocusLost as property. * * default value is true. * */ @Test public void testInitialTerminateEditOnFocusLost() { JXTable table = new JXTable(); assertTrue("terminate edit must be on by default", table.isTerminateEditOnFocusLost()); } /** * Issue #262-swingx: expose terminateEditOnFocusLost as property. * * setter is same as setting client property and results in event firing. */ @Test public void testSetTerminateEditOnFocusLost() { JXTable table = new JXTable(); // sanity assert: setting client property set's property PropertyChangeReport report = new PropertyChangeReport(); table.addPropertyChangeListener(report); table.setTerminateEditOnFocusLost(!table.isTerminateEditOnFocusLost()); assertEquals(table.getClientProperty("terminateEditOnFocusLost"), table.isTerminateEditOnFocusLost()); assertEquals(1, report.getEventCount()); assertEquals(1, report.getEventCount("terminateEditOnFocusLost")); assertEquals(Boolean.FALSE, report.getLastNewValue("terminateEditOnFocusLost")); } /** * sanity test while cleaning up: * getColumns() should return the exact same * ordering as getColumns(false); * */ @Test public void testColumnSequence() { JXTable table = new JXTable(10, 20); table.getColumnExt(5).setVisible(false); table.getColumnModel().moveColumn(table.getColumnCount() - 1, 0); assertEquals(table.getColumns(), table.getColumns(false)); } /** * programmatic sorting of hidden column (through table api). * */ @Test public void testSetSortOrderHiddenColumn() { JXTable table = new JXTable(new AncientSwingTeam()); Object identifier = "Last Name"; TableColumnExt columnExt = table.getColumnExt(identifier); columnExt.setVisible(false); table.setSortOrder(identifier, SortOrder.ASCENDING); assertEquals("sorted column must be at " + identifier, columnExt, table.getSortedColumn()); assertEquals("column must be sorted after setting sortOrder on " + identifier, SortOrder.ASCENDING, table.getSortOrder(identifier)); Object otherIdentifier = "First Name"; table.setSortOrder(otherIdentifier, SortOrder.UNSORTED); assertNull("table must be unsorted after resetting sortOrder on " + otherIdentifier, table.getSortedColumn()); } /** * added xtable.setSortOrder(Object, SortOrder) * */ @Test public void testSetSortOrderByIdentifier() { JXTable table = new JXTable(new AncientSwingTeam()); Object identifier = "Last Name"; TableColumnExt columnExt = table.getColumnExt(identifier); table.setSortOrder(identifier, SortOrder.ASCENDING); assertEquals("sorted column must be at " + identifier, columnExt, table.getSortedColumn()); assertEquals("column must be sorted after setting sortOrder on " + identifier, SortOrder.ASCENDING, table.getSortOrder(identifier)); Object otherIdentifier = "First Name"; table.setSortOrder(otherIdentifier, SortOrder.UNSORTED); assertNull("table must be unsorted after resetting sortOrder on " + otherIdentifier, table.getSortedColumn()); } /** * JXTable has responsibility to respect TableColumnExt * sortable property. * */ @Test public void testSetSortOrderByIdentifierColumnNotSortable() { JXTable table = new JXTable(new AncientSwingTeam()); Object identifier = "Last Name"; TableColumnExt columnX = table.getColumnExt(identifier); // make column not sortable. columnX.setSortable(false); table.setSortOrder(identifier, SortOrder.ASCENDING); assertEquals("unsortable column must be unsorted", SortOrder.UNSORTED, table.getSortOrder(0)); } /** * testing new sorter api: * toggleSortOrder(Object), resetSortOrder. * */ @Test public void testToggleSortOrderByIdentifier() { JXTable table = new JXTable(sortableTableModel); Object firstColumn = "First Name"; Object secondColumn = "Last Name"; assertSame(SortOrder.UNSORTED, table.getSortOrder(secondColumn)); table.toggleSortOrder(firstColumn); assertSame(SortOrder.ASCENDING, table.getSortOrder(firstColumn)); // sanity: other columns uneffected assertSame(SortOrder.UNSORTED, table.getSortOrder(secondColumn)); table.toggleSortOrder(firstColumn); assertSame(SortOrder.DESCENDING, table.getSortOrder(firstColumn)); table.resetSortOrder(); assertSame(SortOrder.UNSORTED, table.getSortOrder(firstColumn)); } /** * JXTable has responsibility to respect TableColumnExt * sortable property. * */ @Test public void testToggleSortOrderByIdentifierColumnNotSortable() { JXTable table = new JXTable(new AncientSwingTeam()); Object identifier = "Last Name"; TableColumnExt columnX = table.getColumnExt(identifier); // old way: make column not sortable. columnX.setSortable(false); table.toggleSortOrder(identifier); assertEquals("unsortable column must be unsorted", SortOrder.UNSORTED, table.getSortOrder(identifier)); } /** * added xtable.setSortOrder(int, SortOrder) * */ @Test public void testSetSortOrder() { JXTable table = new JXTable(new AncientSwingTeam()); int col = 0; TableColumnExt columnExt = table.getColumnExt(col); table.setSortOrder(col, SortOrder.ASCENDING); assertEquals("sorted column must be at " + col, columnExt, table.getSortedColumn()); assertEquals("column must be sorted after setting sortOrder on " + col, SortOrder.ASCENDING, table.getSortOrder(col)); int otherColumn = col + 1; table.setSortOrder(otherColumn, SortOrder.UNSORTED); assertNull("table must be unsorted after resetting sortOrder on " + otherColumn, table.getSortedColumn()); } /** * JXTable has responsibility to respect TableColumnExt * sortable property. * */ @Test public void testSetSortOrderColumnNotSortable() { JXTable table = new JXTable(new AncientSwingTeam()); TableColumnExt columnX = table.getColumnExt(0); // old way: make column not sortable. columnX.setSortable(false); table.setSortOrder(0, SortOrder.ASCENDING); assertEquals("unsortable column must be unsorted", SortOrder.UNSORTED, table.getSortOrder(0)); } /** * JXTable has responsibility to respect TableColumnExt * sortable property. * */ @Test public void testToggleSortOrderColumnNotSortable() { JXTable table = new JXTable(new AncientSwingTeam()); TableColumnExt columnX = table.getColumnExt(0); // old way: make column not sortable. columnX.setSortable(false); table.toggleSortOrder(0); assertEquals("unsortable column must be unsorted", SortOrder.UNSORTED, table.getSortOrder(0)); } /** * JXTable has responsibility to guarantee usage of * TableColumnExt comparator. * */ @Test public void testComparatorToPipeline() { JXTable table = new JXTable(new AncientSwingTeam()); TableColumnExt columnX = table.getColumnExt(0); columnX.setComparator(Collator.getInstance()); table.toggleSortOrder(0); SortKey sortKey = SortKey.getFirstSortKeyForColumn(table.getFilters().getSortController().getSortKeys(), 0); assertNotNull(sortKey); assertEquals(columnX.getComparator(), sortKey.getComparator()); } /** * resetSortOrders didn't check for tableHeader != null. * Didn't show up before new sorter api because method was protected and * only called from JXTableHeader. * */ @Test public void testResetSortOrderNPE() { JXTable table = new JXTable(sortableTableModel); table.setTableHeader(null); table.resetSortOrder(); } /** * testing new sorter api: * getSortOrder(int), toggleSortOrder(int), resetSortOrder(). * */ @Test public void testToggleSortOrder() { JXTable table = new JXTable(sortableTableModel); assertSame(SortOrder.UNSORTED, table.getSortOrder(0)); table.toggleSortOrder(0); assertSame(SortOrder.ASCENDING, table.getSortOrder(0)); // sanity: other columns uneffected assertSame(SortOrder.UNSORTED, table.getSortOrder(1)); table.toggleSortOrder(0); assertSame(SortOrder.DESCENDING, table.getSortOrder(0)); table.resetSortOrder(); assertSame(SortOrder.UNSORTED, table.getSortOrder(0)); } /** * Issue #256-swingX: viewport - do track height. * * */ @Test public void testTrackViewportHeight() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run trackViewportHeight - headless environment"); return; } JXTable table = new JXTable(10, 2); table.setFillsViewportHeight(true); Dimension tablePrefSize = table.getPreferredSize(); JScrollPane scrollPane = new JScrollPane(table); JXFrame frame = wrapInFrame(scrollPane, ""); frame.setSize(500, tablePrefSize.height * 2); frame.setVisible(true); assertEquals("table height be equal to viewport", table.getHeight(), scrollPane.getViewport().getHeight()); } /** * Issue #256-swingX: viewport - don't track height. * * */ @Test public void testNotTrackViewportHeight() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run notTrackViewportHeight - headless environment"); return; } JXTable table = new JXTable(10, 2); table.setFillsViewportHeight(false); Dimension tablePrefSize = table.getPreferredSize(); JScrollPane scrollPane = new JScrollPane(table); JXFrame frame = wrapInFrame(scrollPane, ""); // make sure the height is > table pref height frame.setSize(500, tablePrefSize.height * 2); frame.setVisible(true); assertEquals("table height must be unchanged", tablePrefSize.height, table.getHeight()); } /** * Issue #256-swingx: added fillsViewportHeight property. * * check "fillsViewportHeight" property change fires event. * */ @Test public void testDefaultFillsViewport() { JXTable table = new JXTable(10, 1); boolean fill = table.getFillsViewportHeight(); assertTrue("fillsViewport is on by default", fill); } /** * Issue #256-swingx: added fillsViewportHeight property. * * check "fillsViewportHeight" property change fires event. * */ @Test public void testFillsViewportProperty() { JXTable table = new JXTable(10, 1); boolean fill = table.getFillsViewportHeight(); PropertyChangeReport report = new PropertyChangeReport(); table.addPropertyChangeListener(report); table.setFillsViewportHeight(!fill); assertEquals("must have fired propertyChange for fillsViewportHeight", 1, report.getEventCount("fillsViewportHeight")); assertEquals("property must equal newValue", table.getFillsViewportHeight(), report.getLastNewValue("fillsViewportHeight")); } /** * Issue #256-swingX: viewport - don't change background * in configureEnclosingScrollPane. * * */ @Test public void testUnchangedViewportBackground() { JXTable table = new JXTable(10, 2); JScrollPane scrollPane = new JScrollPane(); scrollPane.setSize(500, 500); Color viewportColor = scrollPane.getViewport().getBackground(); Color tableColor = table.getBackground(); if ((viewportColor != null) && viewportColor.equals(tableColor)) { LOG.info("cannot run test unchanged viewport background because \n" + "viewport has same color as table. \n" + "viewport: " + viewportColor + "\n table: " + tableColor); return; } scrollPane.setViewportView(table); table.configureEnclosingScrollPane(); assertEquals("viewport background must be unchanged", viewportColor, scrollPane.getViewport().getBackground()); } /** * Issue #214-swingX: improved auto-resize. * * */ @Test public void testTrackViewportWidth() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run trackViewportWidth - headless environment"); return; } JXTable table = new JXTable(10, 2); table.setHorizontalScrollEnabled(true); Dimension tablePrefSize = table.getPreferredSize(); JScrollPane scrollPane = new JScrollPane(table); JXFrame frame = wrapInFrame(scrollPane, ""); frame.setSize(tablePrefSize.width * 2, tablePrefSize.height); frame.setVisible(true); assertEquals("table width must be equal to viewport", table.getWidth(), scrollPane.getViewport().getWidth()); } /** * Issue #214-swingX: improved auto-resize. * * */ @Test public void testSetHorizontalEnabled() { JXTable table = new JXTable(10, 2); table.setHorizontalScrollEnabled(true); assertTrue("enhanced resize property must be enabled", table.isHorizontalScrollEnabled()); assertHorizontalActionSelected(table, true); } private void assertHorizontalActionSelected(JXTable table, boolean selected) { Action showHorizontal = table.getActionMap().get( JXTable.HORIZONTALSCROLL_ACTION_COMMAND); assertEquals("horizontAction must be selected" , selected, ((BoundAction) showHorizontal).isSelected()); } /** * Issue #214-swingX: improved auto-resize. * test autoResizeOff != intelliResizeOff * after sequence a) set intelli, b) setAutoResize * */ @Test public void testNotTrackViewportWidth() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run trackViewportWidth - headless environment"); return; } JXTable table = new JXTable(10, 2); table.setHorizontalScrollEnabled(true); table.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF); Dimension tablePrefSize = table.getPreferredSize(); JScrollPane scrollPane = new JScrollPane(table); JXFrame frame = wrapInFrame(scrollPane, ""); frame.setSize(tablePrefSize.width * 2, tablePrefSize.height); frame.setVisible(true); assertEquals("table width must not be equal to viewport", table.getPreferredSize().width, table.getWidth()); } /** * Issue #214-swingX: improved auto-resize. * test autoResizeOff != intelliResizeOff * */ @Test public void testAutoResizeOffNotHorizontalScrollEnabled() { JXTable table = new JXTable(10, 2); table.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF); // sanity: horizontal action must be selected assertHorizontalActionSelected(table, false); assertFalse("autoResizeOff must not enable enhanced resize", table.isHorizontalScrollEnabled()); } /** * Issue #214-swingX: improved auto-resize. * * testing doc'd behaviour: horizscrollenabled toggles between * enhanced resizeOff and the resizeOn mode which had been active * when toggling on. * */ @Test public void testOldAutoResizeOn() { JXTable table = new JXTable(10, 2); int oldAutoResize = table.getAutoResizeMode(); table.setHorizontalScrollEnabled(true); table.setHorizontalScrollEnabled(false); assertEquals("old on-mode must be restored", oldAutoResize, table.getAutoResizeMode()); } /** * Issue #214-swingX: improved auto-resize. * * testing doc'd behaviour: horizscrollenabled toggles between * enhanced resizeOff and the resizeOn mode which had been active * when toggling on. Must not restore raw resizeOff mode. * * */ @Test public void testNotOldAutoResizeOff() { JXTable table = new JXTable(10, 2); int oldAutoResize = table.getAutoResizeMode(); table.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF); table.setHorizontalScrollEnabled(true); table.setHorizontalScrollEnabled(false); assertEquals("old on-mode must be restored", oldAutoResize, table.getAutoResizeMode()); } /** * Issue #214-swingX: improved auto-resize. * test autoResizeOff != intelliResizeOff * after sequence a) set intelli, b) setAutoResize * */ @Test public void testAutoResizeOffAfterHorizontalScrollEnabled() { JXTable table = new JXTable(10, 2); table.setHorizontalScrollEnabled(true); // sanity: intelliResizeOff enabled assertTrue(table.isHorizontalScrollEnabled()); // sanity: horizontal action must be selected assertHorizontalActionSelected(table, true); table.setAutoResizeMode(JXTable.AUTO_RESIZE_OFF); assertFalse("autoResizeOff must not enable enhanced resize", table.isHorizontalScrollEnabled()); // sanity: horizontal action must be selected assertHorizontalActionSelected(table, false); } /** * Issue 252-swingx: getColumnExt throws ClassCastException if tableColumn * is not of type TableColumnExt. * */ @Test public void testTableColumnType() { JXTable table = new JXTable(); table.setAutoCreateColumnsFromModel(false); table.setModel(new DefaultTableModel(2, 1)); TableColumnModel columnModel = new DefaultTableColumnModel(); columnModel.addColumn(new TableColumn(0)); table.setColumnModel(columnModel); // valid column index must not throw exception TableColumnExt tableColumnExt = table.getColumnExt(0); assertNull("getColumnExt must return null on type mismatch", tableColumnExt); } /** * test contract: getColumnExt(int) throws ArrayIndexOutofBounds with * invalid column index. * */ @Test public void testTableColumnExtOffRange() { JXTable table = new JXTable(2, 1); try { table.getColumnExt(1); fail("accessing invalid column index must throw ArrayIndexOutofBoundExc"); } catch (ArrayIndexOutOfBoundsException e) { // do nothing: contracted runtime exception } catch (Exception e) { fail("unexpected exception: " + e + "\n" + "accessing invalid column index must throw ArrayIndexOutofBoundExc"); } } /** * test contract: getColumn(int) throws ArrayIndexOutofBounds with * invalid column index.

* * Subtle autoboxing issue: * JTable has convenience method getColumn(Object) to access by * identifier, but doesn't have delegate method to columnModel.getColumn(int) * Clients assuming the existence of a direct delegate no longer get a * compile-time error message in 1.5 due to autoboxing. * Furthermore, the runtime exception is unexpected (IllegalArgument * instead of AIOOB).

* * Added getColumn(int) to JXTable api to solve. * */ @Test public void testTableColumnOffRange() { JXTable table = new JXTable(2, 1); try { table.getColumn(1); fail("accessing invalid column index must throw ArrayIndexOutofBoundExc"); } catch (ArrayIndexOutOfBoundsException e) { // do nothing: contracted runtime exception } catch (Exception e) { fail("unexpected exception: " + e + "\n" + "accessing invalid column index must throw ArrayIndexOutofBoundExc"); } } /** * Issue #251-swingx: JXTable doesn't respect TableColumn editability. * report, test and fix by nicfagn (Nicola Fagnani), * */ @Test public void testTableColumnEditable() { DefaultTableModel model = new DefaultTableModel( 2, 2 ); JXTable table = new JXTable( model ); // DefaultTableModel allows to edit its cells. for( int i = 0; i < model.getRowCount(); i++ ) { for( int j = 0; j < model.getRowCount(); j++ ) { assertEquals( "cell (" + i + "," + j + ") must be editable", true, table.isCellEditable( i, j ) ); } } // First column not editable. int column = 0; table.getColumnExt( column ).setEditable( false ); for( int i = 0; i < model.getRowCount(); i++ ) { for( int j = 0; j < model.getRowCount(); j++ ) { assertEquals( "cell (" + i + "," + j + ") must " + (j == column ? "not" : "") + " be editable", !(j == column), table.isCellEditable( i, j ) ); } } table.getColumnExt( column ).setEditable( true ); // Second column not editable. column = 1; table.getColumnExt( column ).setEditable( false ); for( int i = 0; i < model.getRowCount(); i++ ) { for( int j = 0; j < model.getRowCount(); j++ ) { assertEquals( "cell (" + i + "," + j + ") must " + (j == column ? "not" : "") + " be editable", !(j == column), table.isCellEditable( i, j ) ); } } table.getColumnExt( column ).setEditable( true ); } /** * Issue #232-swingx: selection not kept if selectionModel had been changed. * */ @Test public void testSelectionMapperUpdatedOnSelectionModelChange() { JXTable table = new JXTable(); ListSelectionModel model = new DefaultListSelectionModel(); table.setSelectionModel(model); assertEquals(model, table.getSelectionMapper().getViewSelectionModel()); } /** * test if LinkController/executeButtonAction is properly registered/unregistered on * setRolloverEnabled. * */ @Test public void testLinkControllerListening() { JXTable table = new JXTable(); table.setRolloverEnabled(true); assertNotNull("LinkController must be listening", getLinkControllerAsPropertyChangeListener(table, RolloverProducer.CLICKED_KEY)); assertNotNull("LinkController must be listening", getLinkControllerAsPropertyChangeListener(table, RolloverProducer.ROLLOVER_KEY)); assertNotNull("execute button action must be registered", table.getActionMap().get(RolloverController.EXECUTE_BUTTON_ACTIONCOMMAND)); table.setRolloverEnabled(false); assertNull("LinkController must not be listening", getLinkControllerAsPropertyChangeListener(table, RolloverProducer.CLICKED_KEY )); assertNull("LinkController must be listening", getLinkControllerAsPropertyChangeListener(table, RolloverProducer.ROLLOVER_KEY)); assertNull("execute button action must be de-registered", table.getActionMap().get(RolloverController.EXECUTE_BUTTON_ACTIONCOMMAND)); } private PropertyChangeListener getLinkControllerAsPropertyChangeListener(JXTable table, String propertyName) { PropertyChangeListener[] listeners = table.getPropertyChangeListeners(propertyName); for (int i = 0; i < listeners.length; i++) { if (listeners[i] instanceof TableRolloverController) { return (TableRolloverController) listeners[i]; } } return null; } /** * Issue #180-swingx: outOfBoundsEx if testColumn is hidden. * */ @Test public void testHighlighterHiddenTestColumn() { JXTable table = new JXTable(sortableTableModel); table.getColumnExt(0).setVisible(false); Highlighter highlighter = new ColorHighlighter(new PatternPredicate("a", 0), null, Color.RED); ComponentAdapter adapter = table.getComponentAdapter(); adapter.row = 0; adapter.column = 0; highlighter.highlight(new JLabel(), adapter); } /** * * Issue #173-swingx. * * table.setFilters() leads to selectionListener * notification while internal table state not yet stable. * * example (second one, from Nicola): * http://www.javadesktop.org/forums/thread.jspa?messageID=117814 * */ @Test public void testSelectionListenerNotification() { final JXTable table = new JXTable(createAscendingModel(0, 20)); final int modelRow = 0; // set a selection table.setRowSelectionInterval(modelRow, modelRow); ListSelectionListener l = new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) return; int viewRow = table.getSelectedRow(); assertTrue("view index visible", viewRow >= 0); // JW: the following checks if the reverse conversion succeeds table.convertRowIndexToModel(viewRow); } }; table.getSelectionModel().addListSelectionListener(l); table.setFilters(new FilterPipeline(new Filter[] {new PatternFilter("0", 0, 0) })); } /** * * Issue #172-swingx. * * The sequence: clearSelection() - setFilter - setRowSelectionInterval * throws Exception. * * example (first, from Diego): * http://www.javadesktop.org/forums/thread.jspa?messageID=117814 * */ @Test public void testClearSelectionAndFilter() { JXTable table = new JXTable(createAscendingModel(0, 20)); int modelRow = table.getRowCount() - 1; // set a selection near the end - will be invalid after filtering table.setRowSelectionInterval(modelRow, modelRow); table.clearSelection(); table.setFilters(new FilterPipeline(new Filter[] {new PatternFilter("9", 0, 0) })); int viewRow = table.convertRowIndexToView(modelRow); assertTrue("view index visible", viewRow >= 0); table.setRowSelectionInterval(viewRow, viewRow); } /** * * Issue #172-swingx. * * The sequence: setFilter - clearSelection() - setRowSelectionInterval * is okay. * * Looks like in SelectionMapper.setPipeline needs to check for empty * selection in view selectionModel and update the anchor/lead (in * the view selection) to valid values! * Now done in SelectionMapper.clearViewSelection, which fixes this test. * * example (first, from Diego): * http://www.javadesktop.org/forums/thread.jspa?messageID=117814 * */ @Test public void testFilterAndClearSelection() { JXTable table = new JXTable(createAscendingModel(0, 20)); int modelRow = table.getRowCount() - 1; // set a selection near the end - will be invalid after filtering table.setRowSelectionInterval(modelRow, modelRow); table.setFilters(new FilterPipeline(new Filter[] {new PatternFilter("9", 0, 0) })); table.clearSelection(); int viewRow = table.convertRowIndexToView(modelRow); assertTrue("view index visible", viewRow >= 0); table.setRowSelectionInterval(viewRow, viewRow); } /** * * Issue #172-swingx. * * * reported exception if row removed (Ray, at the end of) * http://www.javadesktop.org/forums/thread.jspa?messageID=117814 * */ @Test public void testSelectionAndRemoveRowOfMisbehavingModel() { DefaultTableModel model = new DefaultTableModel(10, 2) { @Override public void fireTableRowsDeleted(int firstRow, int lastRow) { fireTableStructureChanged(); } }; for (int i = 0; i < model.getRowCount(); i++) { model.setValueAt(i, i, 0); } JXTable table = new JXTable(model); int modelRow = table.getRowCount() - 1; table.toggleSortOrder(0); // set a selection near the end - will be invalid after filtering table.setRowSelectionInterval(modelRow, modelRow); model.removeRow(modelRow); int lastRow = table.getModel().getRowCount() - 1; int viewRow = table.convertRowIndexToView(lastRow); assertTrue("view index visible", viewRow >= 0); table.setRowSelectionInterval(viewRow, viewRow); } /** * * Issue #172-swingx. * * * reported exception if row removed (Ray, at the end of) * http://www.javadesktop.org/forums/thread.jspa?messageID=117814 * */ @Test public void testSelectionAndRemoveRowOfMisbehavingModelRay() { DefaultTableModel model = new DefaultTableModel(10, 2) { @Override public void fireTableRowsDeleted(int firstRow, int lastRow) { fireTableStructureChanged(); } }; for (int i = 0; i < model.getRowCount(); i++) { model.setValueAt(i, i, 0); } JXTable table = new JXTable(model); int modelRow = table.getRowCount() - 1; Filter[] filters = new Filter[] {new ShuttleSorter(0, true)}; FilterPipeline filterPipe = new FilterPipeline(filters); table.setFilters(filterPipe); // set a selection near the end - will be invalid after filtering table.setRowSelectionInterval(modelRow, modelRow); model.removeRow(modelRow); int lastRow = table.getModel().getRowCount() - 1; int viewRow = table.convertRowIndexToView(lastRow); // JW: here's the problem - the anchor of the selectionModel is not updated correctly // after removing the last model row // not longer valid (as of 50u6) // assertEquals("anchor must be last", lastRow, table.getSelectionModel().getAnchorSelectionIndex()); assertTrue("view index visible", viewRow >= 0); assertEquals("view index is last", viewRow, lastRow); table.setRowSelectionInterval(viewRow, viewRow); } /** * Issue #167-swingx: table looses individual row height * on update. * * This happened if the indy row is filtered and the selection is empty - * updateSelectionAndRowHeight case analysis was incomplete. Fixed. * */ @Test public void testKeepRowHeightOnUpdateAndEmptySelection() { JXTable table = new JXTable(10, 3); table.setRowHeightEnabled(true); // sanity assert assertTrue("row height enabled", table.isRowHeightEnabled()); table.setRowHeight(0, 25); // sanity assert assertEquals(25, table.getRowHeight(0)); // setting an arbitrary value table.setValueAt("dummy", 1, 0); assertEquals(25, table.getRowHeight(0)); // filter to leave only the row with the value set table.setFilters(new FilterPipeline(new Filter[] {new PatternFilter("d", 0, 0)})); assertEquals(1, table.getRowCount()); // setting an arbitrary value in the visible rows table.setValueAt("otherdummy", 0, 1); // reset filter to show all table.setFilters(null); assertEquals(25, table.getRowHeight(0)); } /** * Issue #165-swingx: IllegalArgumentException when * hiding/reshowing columns "at end" of column model. * */ @Test public void testHideShowLastColumns() { JXTable table = new JXTable(10, 3); TableColumnExt ext = table.getColumnExt(2); for (int i = table.getModel().getColumnCount() - 1; i > 0; i--) { table.getColumnExt(i).setVisible(false); } ext.setVisible(true); } /** * Issue #155-swingx: lost setting of initial scrollBarPolicy. * */ @Test public void testConserveVerticalScrollBarPolicy() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run conserveVerticalScrollBarPolicy - headless environment"); return; } JXTable table = new JXTable(0, 3); JScrollPane scrollPane1 = new JScrollPane(table); scrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); JXFrame frame = new JXFrame(); frame.add(scrollPane1); frame.setSize(500, 400); frame.setVisible(true); assertEquals("vertical scrollbar policy must be always", JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, scrollPane1.getVerticalScrollBarPolicy()); } @Test public void testEnableRowHeight() { JXTable table = new JXTable(createAscendingModel(0, 10)); table.setRowHeight(0, 25); assertEquals("indy row height must not be set if disabled", table.getRowHeight(), table.getRowHeight(0)); table.setRowHeightEnabled(true); assertEquals("indy row height must not be set on setting enabled", table.getRowHeight(), table.getRowHeight(0)); table.setRowHeight(0, 25); assertEquals(25, table.getRowHeight(0)); table.setRowHeightEnabled(false); assertEquals("indy row height must not be set if disabled", table.getRowHeight(), table.getRowHeight(0)); } @Test public void testIndividualRowHeightAfterSetModel() { JXTable table = new JXTable(createAscendingModel(0, 10)); table.setRowHeightEnabled(true); table.setRowHeight(0, 25); // sanity assert assertEquals(25, table.getRowHeight(0)); table.setModel(sortableTableModel); assertEquals("individual rowheight must be reset", table.getRowHeight(), table.getRowHeight(0)); } @Test public void testIndividualRowHeight() { JXTable table = new JXTable(createAscendingModel(0, 10)); table.setRowHeightEnabled(true); table.setRowHeight(0, 25); assertEquals(25, table.getRowHeight(0)); assertEquals(table.getRowHeight(), table.getRowHeight(1)); table.getFilters().getSortController().setSortKeys (Collections.singletonList( new SortKey(SortOrder.DESCENDING, 0))); assertEquals(table.getRowHeight(), table.getRowHeight(1)); assertEquals(25, table.getRowHeight(table.getRowCount() - 1)); table.setRowHeight(table.getRowHeight()); assertEquals(table.getRowHeight(), table.getRowHeight(table.getRowCount() - 1)); } @Test public void testResetIndividualRowHeight() { JXTable table = new JXTable(createAscendingModel(0, 10)); table.setRowHeightEnabled(true); table.setRowHeight(0, 25); table.getFilters().getSortController().setSortKeys (Collections.singletonList( new SortKey(SortOrder.DESCENDING, 0))); assertEquals("individual row height must be moved to last row", 25, table.getRowHeight(table.getRowCount() - 1)); // reset table.setRowHeight(table.getRowHeight()); assertEquals("individual row height must be reset", table.getRowHeight(), table.getRowHeight(table.getRowCount() - 1)); } /** * Issue #197: JXTable pattern search differs from * PatternHighlighter/Filter. * */ @Test public void testRespectPatternInSearch() { JXTable table = new JXTable(createAscendingModel(0, 11)); int row = 1; String lastName = table.getValueAt(row, 0).toString(); Pattern strict = Pattern.compile("^" + lastName + "$"); int found = table.getSearchable().search(strict, -1, false); assertEquals("found must be equal to row", row, found); found = table.getSearchable().search(strict, found, false); assertEquals("search must fail", -1, found); } /** * Issue #64-swingx: setFilters(null) throws NPE if has selection. * */ @Test public void testSetNullFilters() { JXTable table = new JXTable(sortableTableModel); table.setRowSelectionInterval(0, 0); table.setFilters(null); assertEquals("selected row must be unchanged", 0, table.getSelectedRow()); } /** * Issue #119: Exception if sorter on last column and setting * model with fewer columns. * * JW: related to #53-swingx - sorter not removed on column removed. * * PatternFilter does not throw - checks with modelToView if the * column is visible and returns false match if not. Hmm... * * */ @Test public void testFilterInChainOnModelChange() { JXTable table = new JXTable(createAscendingModel(0, 10, 5, true)); int columnCount = table.getColumnCount(); assertEquals(5, columnCount); Filter filter = new PatternFilter(".*", 0, columnCount - 1); FilterPipeline pipeline = new FilterPipeline(new Filter[] {filter}); table.setFilters(pipeline); assertEquals(10, pipeline.getOutputSize()); table.setModel(new DefaultTableModel(10, columnCount - 1)); } /** * Issue #119: Exception if sorter on last column and setting * model with fewer columns. * * * JW: related to #53-swingx - sorter not removed on column removed. * * Similar if sorter in filter pipeline -- absolutely need mutable * pipeline!! * Filed the latter part as Issue #55-swingx * */ @Test public void testSorterInChainOnModelChange() { JXTable table = new JXTable(new DefaultTableModel(10, 5)); int columnCount = table.getColumnCount(); Sorter sorter = new ShuttleSorter(columnCount - 1, false); FilterPipeline pipeline = new FilterPipeline(new Filter[] {sorter}); table.setFilters(pipeline); table.setModel(new DefaultTableModel(10, columnCount - 1)); } /** * Issue #119: Exception if sorter on last column and setting * model with fewer columns. * * JW: related to #53-swingx - sorter not removed on column removed. * */ @Test public void testInteractiveSorterOnModelChange() { JXTable table = new JXTable(sortableTableModel); int columnCount = table.getColumnCount(); table.toggleSortOrder(columnCount - 1); table.setModel(new DefaultTableModel(10, columnCount - 1)); assertTrue(table.getFilters().getSortController().getSortKeys().isEmpty()); } /** * add api to access the sorted column. * */ @Test public void testSortedColumn() { JXTable table = new JXTable(sortableTableModel); TableColumnExt columnX = table.getColumnExt(0); table.toggleSortOrder(0); TableColumn sortedColumn = table.getSortedColumn(); assertEquals(columnX, sortedColumn); } /** * Issue #53-swingx: interactive sorter not removed if column removed. * */ @Test public void testSorterAfterColumnRemoved() { JXTable table = new JXTable(sortableTableModel); TableColumnExt columnX = table.getColumnExt(0); table.toggleSortOrder(0); table.removeColumn(columnX); assertTrue("sorter must be removed when column removed", table.getFilters().getSortController().getSortKeys().isEmpty()); } /** * interactive sorter must be active if column is hidden. * THINK: no longer valid... check sortkeys instead? */ @Test public void testSorterAfterColumnHidden() { JXTable table = new JXTable(sortableTableModel); TableColumnExt columnX = table.getColumnExt(0); table.toggleSortOrder(0); List sortKeys = table.getFilters().getSortController().getSortKeys(); columnX.setVisible(false); assertEquals("interactive sorter must be same as sorter in column", sortKeys, table.getFilters().getSortController().getSortKeys()); } /** * Issue #54-swingx: hidden columns not removed. * */ @Test public void testRemoveAllColumns() { JXTable table = new JXTable(sortableTableModel); TableColumnExt columnX = table.getColumnExt(0); columnX.setVisible(false); // set empty model table.setModel(new DefaultTableModel(0, 0)); assertEquals("all columns must have been removed", table.getColumnCount(), table.getColumnCount(true)); } /** * Issue #54: hidden columns not removed on setModel. * */ @Test public void testRemoveAllColumsAfterModelChanged() { JXTable table = new JXTable(sortableTableModel); TableColumnExt columnX = table.getColumnExt(0); columnX.setVisible(false); table.setModel(new DefaultTableModel()); assertEquals("all columns must have been removed", 0, table.getColumnCount(true)); assertEquals("all columns must have been removed", table.getColumnCount(), table.getColumnCount(true)); assertTrue("sorter must be removed when column removed", table.getFilters().getSortController().getSortKeys().isEmpty()); } /** * testing contract of getColumnExt. * */ @Test public void testColumnExt() { JXTable table = new JXTable(sortableTableModel); /// arrgghhh... autoboxing ? // Object zeroName = table.getColumn(0).getIdentifier(); Object zeroName = table.getColumnModel().getColumn(0).getIdentifier(); Object oneName = table.getColumnModel().getColumn(1).getIdentifier(); TableColumn column = table.getColumn(zeroName); ((TableColumnExt) column).setVisible(false); try { // access the invisible column by the inherited method table.getColumn(zeroName); fail("table.getColumn(identifier) guarantees to fail if identifier " + "is unknown or column is hidden"); } catch (Exception e) { // this is what we expect } // access the invisible column by new method TableColumnExt columnZero = table.getColumnExt(zeroName); // sanity.. assertNotNull(columnZero); int viewIndexZero = table.convertColumnIndexToView(columnZero .getModelIndex()); assertTrue("viewIndex must be negative for invisible", viewIndexZero < 0); // a different way to state the same assertEquals(columnZero.isVisible(), viewIndexZero >= 0); TableColumnExt columnOne = table.getColumnExt(oneName); // sanity.. assertNotNull(columnOne); int viewIndexOne = table.convertColumnIndexToView(columnOne .getModelIndex()); assertTrue("viewIndex must be positive for visible", viewIndexOne >= 0); assertEquals(columnOne.isVisible(), viewIndexOne >= 0); } /** * Issue #189, #214: Sorter fails if content is comparable with mixed types * */ @Test public void testMixedComparableTypes() { Object[][] rowData = new Object[][] { new Object[] { Boolean.TRUE, new Integer(2) }, new Object[] { Boolean.TRUE, "BC" } }; String[] columnNames = new String[] { "Critical", "Task" }; DefaultTableModel model = new DefaultTableModel(rowData, columnNames); final JXTable table = new JXTable(model); table.toggleSortOrder(1); } /** * Issue #189, #214: Sorter fails if content is * mixed comparable/not comparable * */ @Test public void testMixedComparableTypesWithNonComparable() { Object[][] rowData = new Object[][] { new Object[] { Boolean.TRUE, new Integer(2) }, new Object[] { Boolean.TRUE, new Object() } }; String[] columnNames = new String[] { "Critical", "Task" }; DefaultTableModel model = new DefaultTableModel(rowData, columnNames); final JXTable table = new JXTable(model); table.toggleSortOrder(1); } @Test public void testIncrementalSearch() { JXTable table = new JXTable(createAscendingModel(10, 10)); int row = 0; String ten = table.getValueAt(row, 0).toString(); // sanity assert assertEquals("10", ten); int found = table.getSearchable().search("1", -1); assertEquals("must have found first row", row, found); int second = table.getSearchable().search("10", found); assertEquals("must have found incrementally at same position", found, second); } /** * Issue #196: backward search broken. * */ @Test public void testBackwardSearch() { JXTable table = new JXTable(createAscendingModel(0, 10)); int row = 1; String lastName = table.getValueAt(row, 0).toString(); int found = table.getSearchable().search(Pattern.compile(lastName), -1, true); assertEquals(row, found); } /** * Issue #187: filter update removes interactive sorter. * */ @Test public void testFilterUpdateKeepsSorter() { int rowCount = 20; int firstValue = 0; JXTable table = new JXTable(createAscendingModel(firstValue, rowCount)); table.toggleSortOrder(0); // sort descending table.toggleSortOrder(0); Object value = table.getValueAt(0, 0); assertEquals("highest value", value, firstValue + rowCount - 1); PatternFilter filter = new PatternFilter(".*", 0, 0); // set a filter table.setFilters(new FilterPipeline(new Filter[] {filter})); assertEquals("highest value unchanged", value, table.getValueAt(0, 0 )); // update the filter filter.setPattern("^1", 0); assertTrue("sorter must be active", ((Integer) table.getValueAt(0, 0)).intValue() > ((Integer) table.getValueAt(1, 0))); } /** * Issue #175: multiple registration as PipelineListener. * * */ @Test public void testRegisterUniquePipelineListener() { JXTable table = new JXTable(); PatternFilter noFilter = new PatternFilter(".*", 0, 1); table.setFilters(new FilterPipeline(new Filter[] {noFilter})); int listenerCount = table.getFilters().getPipelineListeners().length; table.setModel(createAscendingModel(0, 20)); assertEquals("pipeline listener count must not change after setModel", listenerCount, table.getFilters().getPipelineListeners().length); } /** * Issue #174: componentAdapter.hasFocus() looks for anchor instead of lead. * @throws InvocationTargetException * @throws InterruptedException * */ @Test public void testLeadFocusCell() throws InterruptedException, InvocationTargetException { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run leadFocusCell - headless environment"); return; } final JXTable table = new JXTable(); table.setModel(createAscendingModel(0, 10)); final JXFrame frame = new JXFrame(); frame.add(table); frame.pack(); frame.setVisible(true); table.requestFocus(); table.addRowSelectionInterval(table.getRowCount() - 2, table.getRowCount() - 1); final int leadRow = table.getSelectionModel().getLeadSelectionIndex(); int anchorRow = table.getSelectionModel().getAnchorSelectionIndex(); table.addColumnSelectionInterval(0, 0); final int leadColumn = table.getColumnModel().getSelectionModel().getLeadSelectionIndex(); int anchorColumn = table.getColumnModel().getSelectionModel().getAnchorSelectionIndex(); assertEquals("lead must be last row", table.getRowCount() - 1, leadRow); assertEquals("anchor must be second last row", table.getRowCount() - 2, anchorRow); assertEquals("lead must be first column", 0, leadColumn); assertEquals("anchor must be first column", 0, anchorColumn); // take a nap to make sure we are created before testing for focus on linux // w/o this the test will intermittently fail on systems using kernel 2.6 and sun java 6 Thread.sleep(500); SwingUtilities.invokeAndWait(new Runnable() { public void run() { ComponentAdapter adapter = table.getComponentAdapter(); adapter.row = leadRow; adapter.column = leadColumn; // difficult to test - hasFocus() implies that the table isFocusOwner() try { assertTrue("adapter must have focus for leadRow/Column: " + adapter.row + "/" + adapter.column, adapter.hasFocus()); } finally { frame.dispose(); } } }); } /** * Issue #33-swingx: selection not restored after refresh of interactive sorter. * * adjusted to new JXTable sorter api (after the source tag jw_before_rowsorter) * */ @Test public void testSelectionOnSorterRefresh() { JXTable table = new JXTable(createAscendingModel(0, 10)); table.toggleSortOrder(0); SortOrder sortOrder = table.getSortOrder(0); // sanity assert assertTrue(sortOrder.isAscending()); // select the first row table.setRowSelectionInterval(0, 0); // reverse sortorder table.toggleSortOrder(0); assertEquals("last row must be selected", table.getRowCount() - 1, table.getSelectedRow()); } /** * Issue #173: * ArrayIndexOOB if replacing model with one containing * fewer rows and the "excess" is selected. * */ @Test public void testSelectionAndToggleModel() { JXTable table = new JXTable(); table.setModel(createAscendingModel(0, 10)); // sort first column table.toggleSortOrder(0); // select last rows table.addRowSelectionInterval(table.getRowCount() - 2, table.getRowCount() - 1); // invert sort table.toggleSortOrder(0); // set model with less rows table.setModel(createAscendingModel(0, 8)); } /** * testing selection and adding rows. * * */ @Test public void testSelectionAndAddRows() { JXTable table = new JXTable(); DefaultTableModel model = createAscendingModel(0, 10); table.setModel(model); // sort first column table.toggleSortOrder(0); // select last rows table.addRowSelectionInterval(table.getRowCount() - 2, table.getRowCount() - 1); // invert sort table.toggleSortOrder(0); Integer highestValue = new Integer(100); model.addRow(new Object[] { highestValue }); assertEquals(highestValue, table.getValueAt(0, 0)); } /** * Issue #??: removing row throws ArrayIndexOOB on selection * */ @Test public void testSelectionRemoveRowsReselect() { JXTable table = new JXTable(); DefaultTableModel model = createAscendingModel(0, 10); table.setModel(model); // sort first column table.toggleSortOrder(0); // invert sort table.toggleSortOrder(0); // select last row int modelLast = table.getRowCount() - 1; table.setRowSelectionInterval(modelLast, modelLast); model.removeRow(table.convertRowIndexToModel(modelLast)); table.setRowSelectionInterval(table.getRowCount() - 1, table.getRowCount() - 1); } /** * Issue #16: removing row throws ArrayIndexOOB if * last row was selected * */ @Test public void testSelectionAndRemoveRows() { JXTable table = new JXTable(); DefaultTableModel model = createAscendingModel(0, 10); table.setModel(model); // sort first column table.toggleSortOrder(0); // select last rows table.addRowSelectionInterval(table.getRowCount() - 2, table.getRowCount() - 1); // invert sort table.toggleSortOrder(0); model.removeRow(0); } @Test public void testDeleteRowAboveIndividualRowHeight() { DefaultTableModel model = createAscendingModel(0, 10); JXTable table = new JXTable(model); table.setRowHeightEnabled(true); int selectedRow = table.getRowCount() - 1; table.setRowHeight(selectedRow, 25); table.toggleSortOrder(0); assertEquals("last row is individual", 25, table.getRowHeight(selectedRow)); model.removeRow(0); assertEquals("last row is individual", 25, table.getRowHeight(selectedRow - 1)); } /** * Issue #223 - part d) * * test if selection is cleared after receiving a dataChanged. * Need to specify behaviour: lead/anchor of selectionModel are * not changed in clearSelection(). So modelSelection has old * lead which is mapped as a selection in the view (may be out-of * range). Hmmm... * */ @Test public void testSelectionAfterDataChanged() { DefaultTableModel ascendingModel = createAscendingModel(0, 20, 5, false); JXTable table = new JXTable(ascendingModel); int selectedRow = table.getRowCount() - 1; table.setRowSelectionInterval(selectedRow, selectedRow); // sanity assertEquals("last row must be selected", selectedRow, table.getSelectedRow()); ascendingModel.fireTableDataChanged(); assertEquals("selection must be cleared", -1, table.getSelectedRow()); } /** * Issue #223 - part d) * * test if selection is cleared after receiving a dataChanged. * */ @Test public void testCoreTableSelectionAfterDataChanged() { DefaultTableModel ascendingModel = createAscendingModel(0, 20, 5, false); JTable table = new JTable(ascendingModel); int selectedRow = table.getRowCount() - 1; table.setRowSelectionInterval(selectedRow, selectedRow); // sanity assertEquals("last row must be selected", selectedRow, table.getSelectedRow()); ascendingModel.fireTableDataChanged(); assertEquals("selection must be cleared", -1, table.getSelectedRow()); } /** * Issue #223 * * test if selection is updated on remove row above selection. */ @Test public void testDeleteRowAboveSelection() { DefaultTableModel ascendingModel = createAscendingModel(0, 20); JXTable table = new JXTable(ascendingModel); int selectedRow = table.getRowCount() - 1; table.setRowSelectionInterval(selectedRow, selectedRow); // set a pipeline table.toggleSortOrder(0); assertEquals("last row must be selected", selectedRow, table.getSelectedRow()); ascendingModel.removeRow(0); assertEquals("last row must still be selected after remove be selected", table.getRowCount() - 1, table.getSelectedRow()); } /** * Issue #223 * * test if selection is updated on add row above selection. */ @Test public void testAddRowAboveSelection() { DefaultTableModel ascendingModel = createAscendingModel(0, 20); JXTable table = new JXTable(ascendingModel); int selectedRow = table.getRowCount() - 1; table.setRowSelectionInterval(selectedRow, selectedRow); assertEquals("last row must be selected", selectedRow, table.getSelectedRow()); ascendingModel.insertRow(0, new Object[table.getColumnCount()]); assertEquals("last row must still be selected after add above", table.getRowCount() - 1, table.getSelectedRow()); } @Test public void testAddRowAboveIndividualRowHeigh() { DefaultTableModel ascendingModel = createAscendingModel(0, 20); JXTable table = new JXTable(ascendingModel); table.setRowHeightEnabled(true); int selectedRow = table.getRowCount() - 1; table.setRowHeight(selectedRow, 25); assertEquals("last row must have indy rowheight", 25, table.getRowHeight(selectedRow)); ascendingModel.insertRow(0, new Object[table.getColumnCount()]); assertEquals("last row must still have indy rowheight after add above", 25, table.getRowHeight(selectedRow + 1)); } /** * Issue #223 * test if selection is updated on add row above selection. * */ @Test public void testAddRowAboveSelectionInvertedOrder() { DefaultTableModel ascendingModel = createAscendingModel(0, 20); JXTable table = new JXTable(ascendingModel); // select the last row in view coordinates int selectedRow = table.getRowCount() - 1; table.setRowSelectionInterval(selectedRow, selectedRow); // set a pipeline - ascending, no change table.toggleSortOrder(0); // revert order table.toggleSortOrder(0); assertEquals("first row must be selected", 0, table.getSelectedRow()); // remove row in model coordinates Object[] row = new Integer[table.getColumnCount()]; // insert high value row[0] = new Integer(100); ascendingModel.addRow(row); // selection must be moved one below assertEquals("selection must be incremented by one ", 1, table.getSelectedRow()); } @Test public void testAddRowAboveIndividualRowHeightInvertedOrder() { DefaultTableModel ascendingModel = createAscendingModel(0, 20); JXTable table = new JXTable(ascendingModel); table.setRowHeightEnabled(true); // select the last row in view coordinates int selectedRow = table.getRowCount() - 1; table.setRowHeight(selectedRow, 25); // set a pipeline - ascending, no change table.toggleSortOrder(0); // revert order table.toggleSortOrder(0); assertEquals("first row must have indy rowheight", 25, table.getRowHeight(0)); // remove row in model coordinates Object[] row = new Integer[table.getColumnCount()]; // insert high value row[0] = new Integer(100); ascendingModel.addRow(row); // selection must be moved one below assertEquals("row with indy height must be incremented by one ", 25, table.getRowHeight(1)); } /** * Issue #223 * test if selection is updated on remove row above selection. * */ @Test public void testDeleteRowAboveSelectionInvertedOrder() { DefaultTableModel ascendingModel = createAscendingModel(0, 20); JXTable table = new JXTable(ascendingModel); // select the last row in view coordinates int selectedRow = table.getRowCount() - 1; table.setRowSelectionInterval(selectedRow, selectedRow); // set a pipeline - ascending, no change table.toggleSortOrder(0); // revert order table.toggleSortOrder(0); assertEquals("first row must be selected", 0, table.getSelectedRow()); // remove row in model coordinates ascendingModel.removeRow(0); assertEquals("first row must still be selected after remove ", 0, table.getSelectedRow()); } /** * Issue #223 * test if selection is kept if row below selection is removed. * */ @Test public void testDeleteRowBelowSelection() { DefaultTableModel ascendingModel = createAscendingModel(0, 20); JXTable table = new JXTable(ascendingModel); int selectedRow = 0; table.setRowSelectionInterval(selectedRow, selectedRow); // sort ascending table.toggleSortOrder(0); assertEquals("first row must be selected", selectedRow, table.getSelectedRow()); ascendingModel.removeRow(selectedRow + 1); assertEquals("first row must still be selected after remove", selectedRow, table.getSelectedRow()); } /** * Issue #223 * test if selection is kept if row below selection is removed. * */ @Test public void testDeleteRowBelowSelectionInvertedOrder() { DefaultTableModel ascendingModel = createAscendingModel(0, 20); JXTable table = new JXTable(ascendingModel); int selectedRow = 0; table.setRowSelectionInterval(selectedRow, selectedRow); // sort ascending table.toggleSortOrder(0); // revert order table.toggleSortOrder(0); assertEquals("last row must be selected", table.getRowCount() - 1, table.getSelectedRow()); ascendingModel.removeRow(selectedRow + 1); assertEquals("last row must still be selected after remove", table.getRowCount() - 1, table.getSelectedRow()); } /** * Issue #223 * test if selection is kept if row in selection is removed. * */ @Test public void testDeleteLastRowInSelection() { DefaultTableModel ascendingModel = createAscendingModel(0, 20); JXTable table = new JXTable(ascendingModel); int selectedRow = 0; int lastSelectedRow = 1; table.setRowSelectionInterval(selectedRow, lastSelectedRow); // set a pipeline table.toggleSortOrder(0); int[] selectedRows = table.getSelectedRows(); for (int i = selectedRow; i <= lastSelectedRow; i++) { assertEquals("row must be selected " + i, i, selectedRows[i]); } ascendingModel.removeRow(lastSelectedRow); int[] selectedRowsAfter = table.getSelectedRows(); for (int i = selectedRow; i < lastSelectedRow; i++) { assertEquals("row must be selected " + i, i, selectedRowsAfter[i]); } assertFalse("removed row must not be selected " + lastSelectedRow, table.isRowSelected(lastSelectedRow)); } /** * returns a tableModel with count rows filled with * ascending integers in first column * starting from startRow. * @param startRow the value of the first row * @param count the number of rows * @return */ protected DefaultTableModel createAscendingModel(int startRow, int count) { DefaultTableModel model = new DefaultTableModel(count, 4) { @Override public Class getColumnClass(int column) { return column == 0 ? Integer.class : super.getColumnClass(column); } }; for (int i = 0; i < model.getRowCount(); i++) { model.setValueAt(new Integer(startRow++), i, 0); } return model; } /** * returns a tableModel with count rows filled with * ascending integers in first/last column depending on fillLast * starting from startRow. * with columnCount columns * @param startRow the value of the first row * @param rowCount the number of rows * @param columnCount the number of columns * @param fillLast boolean to indicate whether to ill the value in the first * or last column * @return a configured DefaultTableModel. */ protected DefaultTableModel createAscendingModel(int startRow, final int rowCount, final int columnCount, boolean fillLast) { DefaultTableModel model = new DefaultTableModel(rowCount, columnCount) { @Override public Class getColumnClass(int column) { Object value = rowCount > 0 ? getValueAt(0, column) : null; return value != null ? value.getClass() : super.getColumnClass(column); } }; int filledColumn = fillLast ? columnCount - 1 : 0; for (int i = 0; i < model.getRowCount(); i++) { model.setValueAt(new Integer(startRow++), i, filledColumn); } return model; } /** * quick check if overriding sortOnChange prevents auto-resort. * */ @Test public void testSortOnChange() { JXTable table = new JXTable(createAscendingModel(0, 10)) { @Override protected boolean shouldSortOnChange(TableModelEvent e) { if (isUpdate(e)) { return false; } return super.shouldSortOnChange(e); } }; // sort ascending table.toggleSortOrder(0); Integer first = (Integer) table.getValueAt(0, 0); Integer second = (Integer) table.getValueAt(1, 0); // sanity assertTrue(first.intValue() < second.intValue()); int high = first.intValue() + 100; // set a high value table.setValueAt(high, 0, 0); assertEquals("sort should not update after", high, table.getValueAt(0, 0)); } /** * check if setting to false really disables sortability. * */ @Test public void testSortable() { JXTable table = new JXTable(createAscendingModel(0, 10)); boolean sortable = table.isSortable(); // sanity assert: sortable defaults to true assertTrue("JXTable sortable defaults to true", sortable); table.toggleSortOrder(0); Object first = table.getValueAt(0, 0); table.setSortable(false); assertFalse(table.isSortable()); // reverse the sorting order on first column table.toggleSortOrder(0); assertEquals("sorting on a non-sortable table must do nothing", first, table.getValueAt(0, 0)); } /** * Issue #171: row-coordinate not transformed in isCellEditable (sorting) * */ @Test public void testSortedEditability() { int rows = 2; RowObjectTableModel model = createRowObjectTableModel(rows); JXTable table = new JXTable(model); RowObject firstInModel = model.getRowObject(0); assertEquals("rowObject data must be equal", firstInModel.getData1(), table.getValueAt(0, 0)); assertEquals("rowObject editability must be equal", firstInModel.isEditable(), table.isCellEditable(0, 0)); // nothing changed table.toggleSortOrder(0); Object firstDataValueInTable = table.getValueAt(0,0); boolean firstEditableValueInTable = table.isCellEditable(0, 0); assertEquals("rowObject data must be equal", firstInModel.getData1(), table.getValueAt(0, 0)); assertEquals("rowObject editability must be equal", firstInModel.isEditable(), table.isCellEditable(0, 0)); // sanity assert: first and last have different values/editability assertTrue("lastValue different from first", firstDataValueInTable != table.getValueAt(rows - 1, 0)); assertTrue("lastEditability different from first", firstEditableValueInTable != table.isCellEditable(rows - 1, 0)); // reverse order table.toggleSortOrder(0); assertEquals("last row data must be equal to former first", firstDataValueInTable, table.getValueAt(rows - 1, 0)); assertEquals("last row editability must be equal to former first", firstEditableValueInTable, table.isCellEditable(rows - 1, 0)); } /** * Issue #171: row-coordinate not transformed in isCellEditable (filtering) * */ @Test public void testFilteredEditability() { int rows = 2; RowObjectTableModel model = createRowObjectTableModel(rows); JXTable table = new JXTable(model); // sanity assert for (int i = 0; i < table.getRowCount(); i++) { assertEquals("even/uneven rows must be editable/notEditable " + i, i % 2 == 0, table.isCellEditable(i, 0)); } // need to chain two filters (to reach the "else" block in // filter.isCellEditable() PatternFilter filter = new PatternFilter("^NOT", 0, 1); PatternFilter noFilter = new PatternFilter(".*", 0, 1); table.setFilters(new FilterPipeline(new Filter[] {noFilter, filter})); assertEquals("row count is half", rows / 2, table.getRowCount()); for (int i = 0; i < table.getRowCount(); i++) { assertFalse("all rows must be not-editable " + i, table.isCellEditable(i, 0)); } } //----------------------- test data for exposing #171 (Tim Dilks) /** * create test model - all cells in even rows are editable, * in odd rows are not editable. * @param rows the number of rows to create * @return */ private RowObjectTableModel createRowObjectTableModel(int rows) { List rowObjects = new ArrayList(); for (int i = 0; i < rows; i++) { rowObjects.add(new RowObject("somedata" + i, i % 2 == 0)); } return new RowObjectTableModel(rowObjects); } /** * test object to map in test table model. */ static class RowObject { private String data1; private boolean editable; public RowObject(String data1, boolean editable) { this.data1 = data1; this.editable = editable; } public String getData1() { return data1; } public boolean isEditable() { return editable; } } /** * test TableModel wrapping RowObject. */ static class RowObjectTableModel extends AbstractTableModel { List data; public RowObjectTableModel(List data) { this.data = data; } public RowObject getRowObject(int row) { return (RowObject) data.get(row); } public int getColumnCount() { return 2; } public int getRowCount() { return data.size(); } public Object getValueAt(int row, int col) { RowObject object = getRowObject(row); switch (col) { case 0 : return object.getData1(); case 1 : return object.isEditable() ? "EDITABLE" : "NOT EDITABLE"; default : return null; } } @Override public boolean isCellEditable(int row, int col) { return getRowObject(row).isEditable(); } } /** * Issue #167: IllegalStateException if re-setting filter while * sorting. * */ @Test public void testToggleFiltersWhileSorting() { Object[][] rowData = new Object[][] { new Object[] { Boolean.TRUE, "AA" }, new Object[] { Boolean.FALSE, "AB" }, new Object[] { Boolean.FALSE, "AC" }, new Object[] { Boolean.TRUE, "BA" }, new Object[] { Boolean.FALSE, "BB" }, new Object[] { Boolean.TRUE, "BC" } }; String[] columnNames = new String[] { "Critical", "Task" }; final JXTable table = new JXTable(rowData, columnNames); // Filter filterA = new PatternFilter("A.*", Pattern.CASE_INSENSITIVE, 1); // simulates the sequence of user interaction as described in // the original bug report in // http://www.javadesktop.org/forums/thread.jspa?messageID=56285 table.setFilters(createFilterPipeline(false, 1));//new FilterPipeline(new Filter[] {filterA})); table.toggleSortOrder(1); // Filter filterB = new PatternFilter(".*", Pattern.CASE_INSENSITIVE, 1); table.setFilters(createFilterPipeline(true, 1)); //new FilterPipeline(new Filter[] {filterB})); table.toggleSortOrder(1); } /** * Issue #167: IllegalStateException if re-setting filter while * sorting. * Another variant ... * */ @Test public void testToggleFiltersWhileSortingLonger() { Object[][] rowData = new Object[][] { new Object[] { Boolean.TRUE, "AA" }, new Object[] { Boolean.FALSE, "AB" }, new Object[] { Boolean.FALSE, "AC" }, new Object[] { Boolean.TRUE, "BA" }, new Object[] { Boolean.FALSE, "BB" }, new Object[] { Boolean.TRUE, "BC" } }; String[] columnNames = new String[] { "Critical", "Task" }; final JXTable table = new JXTable(rowData, columnNames); // simulates the sequence of user interaction as described in // the follow-up bug report in // http://www.javadesktop.org/forums/thread.jspa?messageID=56285 table.setFilters(createFilterPipeline(false, 1)); table.toggleSortOrder(0); table.toggleSortOrder(1); table.setFilters(createFilterPipeline(true, 1)); table.setFilters(createFilterPipeline(false, 1)); table.toggleSortOrder(0); } private FilterPipeline createFilterPipeline(boolean matchAll, int col) { // RowSorterFilter filter = new RowSorterFilter(); // if (matchAll) { // filter.setRowFilter(RowFilter.regexFilter(".*", col)); // // } else { // filter.setRowFilter(RowFilter.regexFilter("A.*", col)); // } Filter filter; if (matchAll) { filter = new PatternFilter(".*", Pattern.CASE_INSENSITIVE, col); } else { filter = new PatternFilter("^A", Pattern.CASE_INSENSITIVE, col); } return new FilterPipeline(new Filter[] {filter}); } /** * Issue #125: setting filter to null doesn't clean up. * * A visual consequence is that the hidden (by the old * filters) rows don't appear. A not-so visual consequence * is that the sorter is out of synch and accessing a row in * the region outside of the formerly filtered. * */ @Test public void testRemoveFilterWhileSorting() { Object[][] rowData = new Object[][] { new Object[] { Boolean.TRUE, "AA" }, new Object[] { Boolean.FALSE, "AB" }, new Object[] { Boolean.FALSE, "AC" }, new Object[] { Boolean.TRUE, "BA" }, new Object[] { Boolean.FALSE, "BB" }, new Object[] { Boolean.TRUE, "BC" } }; String[] columnNames = new String[] { "Critical", "Task" }; final JXTable table = new JXTable(rowData, columnNames); int rows = table.getRowCount(); // Filter filterA = new PatternFilter("A.*", Pattern.CASE_INSENSITIVE, 1); table.setFilters(createFilterPipeline(false, 1)); //new FilterPipeline(new Filter[] {filterA})); table.toggleSortOrder(1); table.setFilters(null); assertEquals("rowCount must be original", rows, table.getRowCount()); table.getValueAt(rows - 1, 0); } /** * Symmetrical test for editors. * */ @Test public void testLazyEditorsByClass() { JXTable table = new JXTable(); assertEquals("default Boolean editor", JXTable.BooleanEditor.class, table.getDefaultEditor(Boolean.class).getClass()); assertEquals("default Number editor", NumberEditorExt.class, table.getDefaultEditor(Number.class).getClass()); assertEquals("default Double editor", NumberEditorExt.class, table.getDefaultEditor(Double.class).getClass()); } /** * Issue #150: setting filters must not re-create columns. * */ @Test public void testTableColumnsWithFilters() { JXTable table = new JXTable(tableModel); assertEquals("table columns are equal to columns of model", tableModel.getColumnCount(), table.getColumnCount()); TableColumn column = table.getColumnExt(0); table.removeColumn(column); int columnCountAfterRemove = table.getColumnCount(); assertEquals("table columns must be one less than columns of model", tableModel.getColumnCount() - 1, columnCountAfterRemove); table.setFilters(new FilterPipeline(new Filter[] { new ShuttleSorter(1, false), // column 1, descending })); assertEquals("table columns must be unchanged after setting filter", columnCountAfterRemove, table.getColumnCount()); } //-------------------------- tests for moving column control into swingx /** * hmm... sporadic ArrayIndexOOB after sequence: * * filter(column), sort(column), hide(column), setFilter(null) * */ @Test public void testColumnControlAndFilters() { final JXTable table = new JXTable(sortableTableModel); table.setColumnControlVisible(true); Filter filter = new PatternFilter("e", 0, 0); table.setFilters(new FilterPipeline(new Filter[] {filter})); // needed to make public in JXTable for testing // table.getTable().setSorter(0); table.getColumnExt(0).setVisible(false); table.setFilters(null); } public static class DynamicTableModel extends AbstractTableModel { private Object columnSamples[]; private Object columnSamples2[]; public URL linkURL; public static final int IDX_COL_LINK = 6; public DynamicTableModel() { try { linkURL = new URL("http://www.sun.com"); } catch (MalformedURLException ex) { throw new RuntimeException(ex); } columnSamples = new Object[12]; columnSamples[0] = new Integer(0); columnSamples[1] = "Simple String Value"; columnSamples[2] = new Integer(1000); columnSamples[3] = Boolean.TRUE; columnSamples[4] = new Date(100); columnSamples[5] = new Float(1.5); columnSamples[IDX_COL_LINK] = new LinkModel("Sun Micro", "_blank", linkURL); columnSamples[7] = new Integer(3023); columnSamples[8] = "John Doh"; columnSamples[9] = "23434 Testcase St"; columnSamples[10] = new Integer(33333); columnSamples[11] = Boolean.FALSE; columnSamples2 = new Object[12]; columnSamples2[0] = new Integer(0); columnSamples2[1] = "Another String Value"; columnSamples2[2] = new Integer(999); columnSamples2[3] = Boolean.FALSE; columnSamples2[4] = new Date(333); columnSamples2[5] = new Float(22.22); columnSamples2[IDX_COL_LINK] = new LinkModel("Sun Web", "new_frame", linkURL); columnSamples[7] = new Integer(5503); columnSamples[8] = "Jane Smith"; columnSamples[9] = "2343 Table Blvd."; columnSamples[10] = new Integer(2); columnSamples[11] = Boolean.TRUE; } public DynamicTableModel(Object columnSamples[]) { this.columnSamples = columnSamples; } @Override public Class getColumnClass(int column) { return columnSamples[column].getClass(); } public int getRowCount() { return 1000; } public int getColumnCount() { return columnSamples.length; } public Object getValueAt(int row, int column) { Object value; if (row % 3 == 0) { value = columnSamples[column]; } else { value = columnSamples2[column]; } return column == 0 ? new Integer(row >> 3) : column == 3 ? new Boolean(row % 2 == 0) : value; } @Override public boolean isCellEditable(int row, int column) { return (column == 1); } @Override public void setValueAt(Object aValue, int row, int column) { if (column == 1) { if (row % 3 == 0) { columnSamples[column] = aValue; } else { columnSamples2[column] = aValue; } } this.fireTableDataChanged(); } } // test per-column highlighting private static class TestingHighlighter extends AbstractHighlighter { private List events; public TestingHighlighter(List events) { this.events = events; } @Override protected Component doHighlight(Component component, ComponentAdapter adapter) { events.add(this); return component; } } @Test public void testColumnHighlighting() { JXTable table = new JXTable(tableModel); List events = new ArrayList(); Highlighter tableHighlighter = new TestingHighlighter(events); Highlighter columnHighlighter = new TestingHighlighter(events); //sanity check assertEquals(0, events.size()); table.addHighlighter(tableHighlighter); table.getColumnExt(0).addHighlighter(columnHighlighter); //explicity prepare the renderer table.prepareRenderer(new DefaultTableCellRenderer(), 0, 0); assertEquals(2, events.size()); assertSame(events.get(0), tableHighlighter); assertSame(events.get(1), columnHighlighter); events.clear(); //explicity prepare the renderer table.prepareRenderer(new DefaultTableCellRenderer(), 0, 1); assertEquals(1, events.size()); assertSame(events.get(0), tableHighlighter); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXMonthViewIssues.java0000644000175000017500000006622411210401722024142 0ustar tonytony/* * $Id: JXMonthViewIssues.java,v 1.61 2009/01/26 13:57:46 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.text.DateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.util.logging.Logger; import javax.swing.Action; import javax.swing.Box; import javax.swing.JComboBox; import javax.swing.JComponent; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.calendar.CalendarUtils; import org.jdesktop.swingx.calendar.DaySelectionModel; import org.jdesktop.swingx.calendar.DateSelectionModel.SelectionMode; import org.jdesktop.swingx.event.DateSelectionEvent.EventType; import org.jdesktop.swingx.test.DateSelectionReport; import org.jdesktop.test.PropertyChangeReport; import org.jdesktop.test.TestUtils; /** * Test to expose known issues with JXMonthView. * * @author Jeanette Winzenburg */ public class JXMonthViewIssues extends InteractiveTestCase { @SuppressWarnings("all") private static final Logger LOG = Logger.getLogger(JXMonthViewIssues.class .getName()); public static void main(String[] args) { setSystemLF(true); InteractiveTestCase test = new JXMonthViewIssues(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Locale.*"); // test.runInteractiveTests("interactive.*AutoScroll.*"); // test.runInteractiveTests("interactive.*Repaint.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } // pre-defined dates - initialized in setUpCalendar protected Date today; protected Date tomorrow; @SuppressWarnings("unused") protected Date afterTomorrow; protected Date yesterday; // the calendar to use, its date is initialized with the today-field in setUpCalendar protected Calendar calendar; public void interactiveMonthViewAntialisedPaint() { JXMonthView custom = new JXMonthView() { @Override public void paint(Graphics g) { Toolkit tk = Toolkit.getDefaultToolkit (); Map map = (Map) (tk.getDesktopProperty ("awt.font.desktophints")); LOG.info("hints " + map); if (map != null) { ((Graphics2D) g).addRenderingHints(map); } super.paint(g); } }; final JXMonthView monthView = new JXMonthView(); JComponent comp = Box.createHorizontalBox(); comp.add(custom); comp.add(monthView); JXFrame frame = wrapInFrame(comp, "antialiased 1.6paint left"); show(frame); } /** * Issue #736-swingx: monthView cannot cope with minimalDaysInFirstWeek. * */ public void interactiveDayAt() { final JXMonthView monthView = new JXMonthView(); monthView.setTraversable(true); monthView.setShowingWeekNumber(true); monthView.setShowingLeadingDays(true); monthView.setShowingTrailingDays(true); monthView.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { LOG.info("dayAt " + e.getPoint() + ": " + "\n" + monthView.getDayAtLocation(e.getX(), e.getY()) ); } }); Action action = new AbstractActionExt("toggle minimal") { public void actionPerformed(ActionEvent e) { int minimal = monthView.getSelectionModel().getMinimalDaysInFirstWeek(); monthView.getSelectionModel().setMinimalDaysInFirstWeek(minimal > 1 ? 1 : 4); } }; final JXFrame frame = wrapInFrame(monthView, "click day"); addAction(frame, action); show(frame); } /** * Issue #736-swingx: monthView cannot cope with minimalDaysInFirstWeek. * * Here: look at impact of forcing the minimalDays to a value different * from the calendar. Days must be displayed in starting from the * first row under the days-of-week. * * Not yet completely fixed: for very late firstDayOfWeek, the Jan is incompletely * painted for mininalDays > 1. Rare enough to ignore for now? */ public void interactiveMinimalDaysInFirstWeek() { final JXMonthView monthView = new JXMonthView(); monthView.setTraversable(true); monthView.setShowingWeekNumber(true); monthView.setShowingLeadingDays(true); monthView.setShowingTrailingDays(true); Action action = new AbstractActionExt("toggle minimal") { public void actionPerformed(ActionEvent e) { int minimal = monthView.getSelectionModel().getMinimalDaysInFirstWeek(); monthView.getSelectionModel().setMinimalDaysInFirstWeek(minimal > 1 ? 1 : 4); } }; final JXFrame frame = wrapInFrame(monthView, "click unselectable fires ActionEvent"); addAction(frame, action); addComponentOrientationToggle(frame); final JComboBox dayOfWeekComboBox = new JComboBox(new String[]{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}); dayOfWeekComboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int selected = dayOfWeekComboBox.getSelectedIndex(); monthView.setFirstDayOfWeek(selected + Calendar.SUNDAY); } }); dayOfWeekComboBox.setSelectedIndex(monthView.getFirstDayOfWeek() - Calendar.SUNDAY); addStatusComponent(frame, dayOfWeekComboBox); show(frame); } /** * Issue #567-swingx: JXDatepicker - clicking on unselectable date clears * picker's selection. * * Here: visualize JXMonthView's behaviour. It fires a commit ... probably the * wrong thing to do?. * PENDING: better control the bounds ... * PENDING: move into monthView after rename */ public void interactiveBoundsMonthViewClickUnselectable() { JXMonthView monthView = new JXMonthView(); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_MONTH, 7); monthView.setLowerBound(calendar.getTime()); calendar.set(Calendar.DAY_OF_MONTH, 20); monthView.setUpperBound(calendar.getTime()); ActionListener l = new ActionListener() { public void actionPerformed(ActionEvent e) { LOG.info("got action " + e); } }; monthView.addActionListener(l); showInFrame(monthView, "click unselectable fires ActionEvent"); } /** * Issue #657-swingx: JXMonthView - unintuitive week-wise navigation with bounds * * In a month, keyboard navigation beyond the upper/lower bound is prevented. * There's a leak in the region of the leading/trailing dates * when navigating week-wise. * * PENDING: move into monthView after rename */ public void interactiveBoundsNavigateBeyond() { JXMonthView monthView = new JXMonthView(); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_MONTH, 2); // access the model directly requires to "clean" the date monthView.setLowerBound(calendar.getTime()); calendar.set(Calendar.DAY_OF_MONTH, 27); monthView.setUpperBound(calendar.getTime()); ActionListener l = new ActionListener() { public void actionPerformed(ActionEvent e) { LOG.info("got action " + e); } }; monthView.addActionListener(l); showInFrame(monthView, "navigate beyond bounds"); } /** * Issue #657-swingx: JXMonthView - unintuitive week-wise navigation with bounds * * Can't navigate at all if today is beyound the bounds * PENDING: move into monthView after rename */ public void interactiveBoundsNavigateLocked() { JXMonthView monthView = new JXMonthView(); // same time as monthView's today Calendar calendar = Calendar.getInstance(); // set upper bound a week before today, // to block navigation into all directions calendar.add(Calendar.DAY_OF_MONTH, -8); monthView.setUpperBound(calendar.getTime()); ActionListener l = new ActionListener() { public void actionPerformed(ActionEvent e) { LOG.info("got action " + e); } }; monthView.addActionListener(l); showInFrame(monthView, "navigate: locked for today beyond bounds"); } //---------------------- /** * Issue #618-swingx: JXMonthView displays problems with non-default * timezones. * * Here: test that the first displayed date is offset by offset diff of * timezones. * Configure the monthView with a fixed timezone to clear up the mist ... * */ public void testTimeZoneChangeToday() { Locale componentDefault = JComponent.getDefaultLocale(); try { FixedLocaleSelectionModel model = new FixedLocaleSelectionModel(); JComponent.setDefaultLocale(model.getLocale()); Locale.setDefault(model.getLocale()); Calendar modelCal = model.getCalendar(); Date fixed = modelCal.getTime(); JXMonthView monthView = new JXMonthView(fixed, model); Calendar myCal = monthView.getCalendar(); // myCal.setTimeInMillis(myCal.getTimeInMillis() + 2667600000l); LOG.info("monthView timezone " + monthView.getTimeZone() + "\n" + myCal + "\n" + monthView.getLocale()); DateFormat format = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, monthView.getLocale()); format.setTimeZone(myCal.getTimeZone()); LOG.info("" + format.format(myCal.getTime())); // config with a known timezone and date TimeZone tz = TimeZone.getTimeZone("GMT+4"); Calendar calendar = Calendar.getInstance(tz); calendar.set(2008, Calendar.MARCH, 31, 11, 45); Date today = calendar.getTime(); monthView.setTimeZone(tz); monthView.setFirstDisplayedDay(today); Date anchor = monthView.getAnchorDate(); assertEquals(today, anchor); Date firstDisplayed = monthView.getFirstDisplayedDay(); calendar.setTime(firstDisplayed); assertTrue(CalendarUtils.isStartOfMonth(calendar)); // get another timezone with known offset TimeZone tzOther = TimeZone.getTimeZone("GMT+7"); // newOffset minus oldOffset (real time, adjusted to DST) int oldOffset = tz.getOffset(anchor.getTime()); int newOffset = tzOther.getOffset(anchor.getTime()); int realOffset = oldOffset - newOffset; monthView.setTimeZone(tzOther); Calendar otherCalendar = Calendar.getInstance(tzOther); otherCalendar.setTime(monthView.getFirstDisplayedDay()); assertTrue(CalendarUtils.isStartOfMonth(otherCalendar)); // PENDING JW: sure this is the correct direction of the shift? // yeah, think so: the anchor is fixed, moving the timezone results // in a shift into the opposite direction of the offset assertEquals("first displayed must be offset by real offset", realOffset, monthView.getFirstDisplayedDay().getTime() - firstDisplayed.getTime()); } finally { // reset componentLocale JComponent.setDefaultLocale(componentDefault); Locale.setDefault(componentDefault); } } /** * Try to track spurious timezone failures. Extended to mimic server * context 31mar2008, us/pacific timezone, en_US locale. No luck... */ public static class FixedLocaleSelectionModel extends DaySelectionModel { @Override public void setLocale(Locale locale) { this.locale = new Locale("en", "US"); //Locale.US; calendar = Calendar.getInstance(TimeZone.getTimeZone("US/Pacific"), this.locale); calendar.set(2008, Calendar.MARCH, 31, 11, 45); LOG.info("calendar timezone " + calendar.getTimeZone() + "\n" + calendar + "\n" + this.locale); DateFormat format = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, this.locale); format.setTimeZone(calendar.getTimeZone()); LOG.info("" + format.format(calendar.getTime())); fireValueChanged(EventType.CALENDAR_CHANGED); } } /** * Issue #618-swingx: JXMonthView displays problems with non-default * timezones. * * Here: test that the first displayed date is offset by offset diff of * timezones. * Configure the monthView with a fixed timezone to clear up the mist ... * */ public void testTimeZoneChangeOffsetFirstDisplayedDate() { JXMonthView monthView = new JXMonthView(); // config with a known timezone and date TimeZone tz = TimeZone.getTimeZone("GMT+4"); monthView.setTimeZone(tz); Calendar calendar = Calendar.getInstance(tz); Date today = calendar.getTime(); monthView.setFirstDisplayedDay(today); Date anchor = monthView.getAnchorDate(); assertEquals(today, anchor); Date firstDisplayed = monthView.getFirstDisplayedDay(); calendar.setTime(firstDisplayed); assertTrue(CalendarUtils.isStartOfMonth(calendar)); // get another timezone with known offset TimeZone tzOther = TimeZone.getTimeZone("GMT+7"); // newOffset minus oldOffset (real time, adjusted to DST) int oldOffset = tz.getOffset(anchor.getTime()); int newOffset = tzOther.getOffset(anchor.getTime()); int realOffset = oldOffset - newOffset; monthView.setTimeZone(tzOther); Calendar otherCalendar = Calendar.getInstance(tzOther); otherCalendar.setTime(monthView.getFirstDisplayedDay()); assertTrue(CalendarUtils.isStartOfMonth(otherCalendar)); // PENDING JW: sure this is the correct direction of the shift? // yeah, think so: the anchor is fixed, moving the timezone results // in a shift into the opposite direction of the offset assertEquals("first displayed must be offset by real offset", realOffset, monthView.getFirstDisplayedDay().getTime() - firstDisplayed.getTime()); } /** * characterize what a weekinterval selection is meant to do. * MultipleIntervalSelection where each interval is one or more weeks? * Here: does not snap start/end of week to start/end of day? */ @SuppressWarnings("deprecation") public void testWeekInterval() { JXMonthView monthView = new JXMonthView(); CalendarUtils.startOfWeek(calendar); calendar.add(Calendar.WEEK_OF_YEAR, 3); // calendar.add(Calendar.HOUR_OF_DAY, - 3); monthView.cleanupWeekSelectionDates(today, calendar.getTime()); assertNotNull("not doing anything?", monthView.modifiedEndDate); calendar.setTime(monthView.modifiedStartDate); LOG.info("start/end" + monthView.modifiedStartDate + "/" + monthView.modifiedEndDate); assertTrue("interval first must be start of week", CalendarUtils.isStartOfWeek(calendar)); calendar.setTime(monthView.modifiedEndDate); assertTrue("interval last must be end of week", CalendarUtils.isEndOfWeek(calendar)); } /** * characterize what a weekinterval selection is meant to do. * MultipleIntervalSelection where each interval is one or more weeks? * Here: does nothing if single day selected? */ @SuppressWarnings("deprecation") public void testWeekIntervalOneDay() { JXMonthView monthView = new JXMonthView(); monthView.cleanupWeekSelectionDates(today, today); calendar.setTime(monthView.modifiedEndDate); assertTrue("interval last must be end of week", CalendarUtils.isEndOfWeek(calendar)); calendar.setTime(monthView.modifiedStartDate); assertTrue("interval first must be start of week", CalendarUtils.isStartOfWeek(calendar)); LOG.info("start/end" + monthView.modifiedStartDate + "/" + monthView.modifiedEndDate); } /** * characterize what a weekinterval selection is meant to do. * MultipleIntervalSelection where each interval is one or more weeks? * Here: does nothing if two days interval? */ @SuppressWarnings("deprecation") public void testWeekIntervalTwoDays() { JXMonthView monthView = new JXMonthView(); monthView.cleanupWeekSelectionDates(today, tomorrow); calendar.setTime(monthView.modifiedEndDate); assertTrue("interval last must be end of week", CalendarUtils.isEndOfWeek(calendar)); calendar.setTime(monthView.modifiedStartDate); assertTrue("interval first must be start of week", CalendarUtils.isStartOfWeek(calendar)); LOG.info("start/end" + monthView.modifiedStartDate + "/" + monthView.modifiedEndDate); } /** * Issue #733-swingx: TimeZone in model and monthView not synched. * * Test that the selected is normalized in the monthView's timezone. */ public void testCalendarsTimeZoneFlaggedDate() { JXMonthView monthView = new JXMonthView(); // config with a known timezone and date TimeZone tz = TimeZone.getTimeZone("GMT+4"); monthView.setTimeZone(tz); Date date = new Date(); monthView.setFlaggedDates(new Date[] {date}); assertTrue(monthView.isFlaggedDate(date)); fail("no way to test same normalization for flagged and selected dates"); } /** * Issue #733-swingx: TimeZone in model and monthView not synched. * * Test selected - tells nothing, because it's normalized in the * model's (default) calendar. */ public void testCalendarsTimeZoneSelectedDate() { JXMonthView monthView = new JXMonthView(); // config with a known timezone and date TimeZone tz = TimeZone.getTimeZone("GMT+4"); monthView.setTimeZone(tz); Date date = new Date(); monthView.setSelectionDate(date); assertTrue(monthView.isSelected(date)); fail("test passes - but tells nothing"); } public void testNoSelectionMode() { // JXMonthView monthView = new JXMonthView(); // monthView.setSelectionMode(SelectionMode.NO_SELECTION); // // Date date = new Date(); // monthView.setSelectionInterval(date, date); // assertTrue(monthView.isSelectionEmpty()); fail("revisit: no selection mode"); } /** * temporarily removed weekinterval selection. * Need to review - why not in selectionModel? */ public void testWeekIntervalSelection() { // // PENDING: simplify to use pre-defined dates // JXMonthView monthView = new JXMonthView(Locale.US); // monthView.setSelectionMode(JXMonthView.SelectionMode.WEEK_INTERVAL_SELECTION); // // // Use a known date that falls on a Sunday, which just happens to be my birthday. // calendar.set(Calendar.YEAR, 2006); // calendar.set(Calendar.MONTH, Calendar.APRIL); // calendar.set(Calendar.DAY_OF_MONTH, 9); // CalendarUtils.startOfDay(calendar); // Date startDate = calendar.getTime(); //// Date startDate = cleanupDate(calendar); // // Date endDate; // calendar.set(Calendar.DAY_OF_MONTH, 13); // endDate = calendar.getTime(); // // monthView.setSelectionInterval(startDate, endDate); // SortedSet selection = monthView.getSelection(); // assertTrue(startDate.equals(selection.first())); // assertTrue(endDate.equals(selection.last())); // // calendar.set(Calendar.DAY_OF_MONTH, 20); // endDate = calendar.getTime(); // monthView.setSelectionInterval(startDate, endDate); // // calendar.set(Calendar.DAY_OF_MONTH, 22); // endDate = calendar.getTime(); // selection = monthView.getSelection(); // // assertEquals(startDate, selection.first()); // assertTrue(endDate.equals((selection.last()))); fail("revisit: week selection"); } public void testModelSelectionUpdate() { // JXMonthView monthView = new JXMonthView(); // // // The JXMonthView uses an underlying model mode of single selection when it is in no selection mode. // monthView.setSelectionMode(SelectionMode.NO_SELECTION); // assertTrue( // DateSelectionModel.SelectionMode.SINGLE_SELECTION == monthView.getSelectionModel().getSelectionMode()); // // monthView.setSelectionMode(SelectionMode.SINGLE_SELECTION); // assertTrue( // DateSelectionModel.SelectionMode.SINGLE_SELECTION == monthView.getSelectionModel().getSelectionMode()); // // monthView.setSelectionMode(SelectionMode.SINGLE_INTERVAL_SELECTION); // assertTrue( // DateSelectionModel.SelectionMode.SINGLE_INTERVAL_SELECTION == // monthView.getSelectionModel().getSelectionMode()); // // // The JXMonthView uses an underlying model mode of single interval selection when it is in week selection mode. // monthView.setSelectionMode(SelectionMode.WEEK_INTERVAL_SELECTION); // assertTrue( // DateSelectionModel.SelectionMode.SINGLE_INTERVAL_SELECTION == // monthView.getSelectionModel().getSelectionMode()); // // monthView.setSelectionMode(SelectionMode.MULTIPLE_INTERVAL_SELECTION); // assertTrue( // DateSelectionModel.SelectionMode.MULTIPLE_INTERVAL_SELECTION == // monthView.getSelectionModel().getSelectionMode()); fail("revisit: selection modes"); } /** * Issue #618-swingx: JXMonthView displays problems with non-default * timezones. * * Here: test today notification. */ public void testTimeZoneChangeTodayNotification() { JXMonthView monthView = new JXMonthView(); TimeZone other = getTimeZone(monthView.getTimeZone(), CalendarUtils.THREE_HOURS); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setTimeZone(other); Calendar calendar = Calendar.getInstance(); CalendarUtils.startOfDay(calendar); Date today = calendar.getTime(); calendar.setTimeZone(other); CalendarUtils.startOfDay(calendar); Date otherToday = calendar.getTime(); // sanity assertFalse(today.equals(otherToday)); TestUtils.assertPropertyChangeEvent(report, "today", today.getTime(), otherToday.getTime(), false); fail("spurious failures - probably wrong assumption in Timezone math"); } /** * BasicMonthViewUI: use adjusting api in keyboard actions. * Here: test add selection action. * * TODO: this fails (unrelated to the adjusting) because the * the selectionn changing event type is DATES_SET instead of * the expected DATES_ADDED. What's wrong - expectation or type? */ public void testAdjustingSetOnAdd() { JXMonthView view = new JXMonthView(); // otherwise the add action isn't called view.setSelectionMode(SelectionMode.SINGLE_INTERVAL_SELECTION); DateSelectionReport report = new DateSelectionReport(view.getSelectionModel()); Action select = view.getActionMap().get("adjustSelectionNextDay"); select.actionPerformed(null); assertTrue("ui keyboard action must have started model adjusting", view.getSelectionModel().isAdjusting()); assertEquals(2, report.getEventCount()); // assert that the adjusting is fired before the add // only: the ui fires a set instead - bug or feature? assertEquals(EventType.DATES_ADDED, report.getLastEvent().getEventType()); } //------------------- utility /** * Returns a timezone with a rawoffset with a different offset. * * * PENDING: this is acutally for european time, not really thought of * negative/rolling +/- problem? * * @param timeZone the timezone to start with * @param diffRawOffset the raw offset difference. * @return */ @SuppressWarnings("unused") private TimeZone getTimeZone(TimeZone timeZone, int diffRawOffset) { int offset = timeZone.getRawOffset(); int newOffset = offset < 0 ? offset + diffRawOffset : offset - diffRawOffset; String[] availableIDs = TimeZone.getAvailableIDs(newOffset); TimeZone newTimeZone = TimeZone.getTimeZone(availableIDs[0]); return newTimeZone; } @SuppressWarnings("unused") private String[] getTimeZoneIDs() { List zoneIds = new ArrayList(); for (int i = -12; i <= 12; i++) { String sign = i < 0 ? "-" : "+"; zoneIds.add("GMT" + sign + i); } return zoneIds.toArray(new String[zoneIds.size()]); } @Override protected void setUp() throws Exception { setUpCalendar(); } /** * Initializes the calendar to the default instance and the predefined dates * in the coordinate system of the calendar. Note that the hour is set * to "about" in all dates, to be reasonably well into the day. The time * fields of all dates are the same, the calendar is pre-set with the * today field. */ protected void setUpCalendar() { calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 5); today = calendar.getTime(); calendar.add(Calendar.DAY_OF_MONTH, -1); yesterday = calendar.getTime(); calendar.add(Calendar.DAY_OF_MONTH, 2); tomorrow = calendar.getTime(); calendar.add(Calendar.DAY_OF_MONTH, 1); afterTomorrow = calendar.getTime(); calendar.setTime(today); } } swingx-1.0-src/src/test/org/jdesktop/swingx/painter/0000755000175000017500000000000011210401736021356 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/painter/CompoundPainterIssues.java0000644000175000017500000000760111210401722026523 0ustar tonytony/* * $Id: CompoundPainterIssues.java,v 1.5 2007/06/19 10:53:37 rah003 Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.painter; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXPanel; import org.jdesktop.test.PropertyChangeReport; /** * Test to exposed known issues of CompoundPainters. * * Ideally, there would be at least one failing test method per open * Issue in the issue tracker. Plus additional failing test methods for * not fully specified or not yet decided upon features/behaviour. * * * @author Jeanette Winzenburg */ public class CompoundPainterIssues extends InteractiveTestCase { /** * Issue #??-swingx: clearCache has no detectable effect. * @throws IOException * */ public void testClearCacheDetectable() throws IOException { BufferedImage img = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB); Graphics2D g = img.createGraphics(); AbstractPainter painter = new ShapePainter() { @Override protected boolean shouldUseCache() { return isCacheable(); } }; painter.paint(g, null, 10, 10); // sanity assertFalse("clean after paint", painter.isDirty()); assertTrue("cacheable is true by default", painter.isCacheable()); assertFalse("has a cached image", painter.isCacheCleared()); PropertyChangeReport report = new PropertyChangeReport(); painter.addPropertyChangeListener(report); painter.clearCache(); assertTrue("painter must have fired change event", report.hasEvents()); } /** * Issue #??-swingx: must fire property change if contained painter * changed. * @throws IOException * */ public void testDirtyNotification() throws IOException { BufferedImage img = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB); Graphics2D g = img.createGraphics(); final ImagePainter imagePainter = new ImagePainter(ImageIO.read(JXPanel.class .getResource("resources/images/kleopatra.jpg"))); assertNotNull(imagePainter); assertTrue("initial state of dirty must be true? was: " + imagePainter.isDirty(), imagePainter.isDirty()); imagePainter.paint(g, null, 10, 10); assertFalse(imagePainter.isDirty()); CompoundPainter compound = new CompoundPainter(imagePainter); assertFalse(compound.isDirty()); PropertyChangeReport report = new PropertyChangeReport(); compound.addPropertyChangeListener(report); imagePainter.setBorderWidth(imagePainter.getBorderWidth() + 2); assertTrue(imagePainter.isDirty()); assertTrue(compound.isDirty()); assertEquals("compound painter must fire exactly one property change", 1, report.getEventCount()); assertEquals("compound painter must fire dirty property", 1, report.getEventCount("dirty")); } } swingx-1.0-src/src/test/org/jdesktop/swingx/painter/BusyPainterTest.java0000644000175000017500000000275411210401722025331 0ustar tonytony/* * $Id: BusyPainterTest.java,v 1.2 2009/02/01 16:23:17 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.painter; import junit.framework.TestCase; import org.apache.commons.collections.CollectionUtils; import org.jdesktop.test.TestUtils; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; /** * Test for AbstractPainter */ @RunWith(JUnit4.class) public class BusyPainterTest extends TestCase { /** * Issue #861-swingx: must fire PCE on property change. */ @Test public void testPaint() { TestUtils.assertPCEFiring(new BusyPainter(), CollectionUtils.EMPTY_COLLECTION); } } swingx-1.0-src/src/test/org/jdesktop/swingx/painter/TestableFilter.java0000644000175000017500000000262511210401722025132 0ustar tonytony/* * $Id: TestableFilter.java,v 1.2 2008/02/15 15:08:22 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.painter; import org.jdesktop.swingx.image.AbstractFilter; import java.awt.image.BufferedImage; /** * A useful Filter implementation for testing Painters * * @author rbair */ public class TestableFilter extends AbstractFilter { boolean filtered = false; @Override public BufferedImage filter(BufferedImage src, BufferedImage dest) { filtered = true; return src; } void reset() { filtered = false; } } swingx-1.0-src/src/test/org/jdesktop/swingx/painter/PainterIssues.java0000644000175000017500000002455611210401722025026 0ustar tonytony/* * $Id: PainterIssues.java,v 1.12 2009/02/01 15:01:07 rah003 Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.painter; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.StringTokenizer; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.logging.Logger; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.border.Border; import org.jdesktop.beans.AbstractBean; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXLabel; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.test.TestUtils; /** * Test to exposed known issues of Painters. * * Ideally, there would be at least one failing test method per open * Issue in the issue tracker. Plus additional failing test methods for * not fully specified or not yet decided upon features/behavior. * * * @author Jeanette Winzenburg */ public class PainterIssues extends InteractiveTestCase { static Logger log = Logger.getAnonymousLogger(); public static void main(String args[]) { // setSystemLF(true); PainterIssues test = new PainterIssues(); try { test.runInteractiveTests(); // test.runInteractiveTests(".*Label.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } // ------------------ visual tests /** * JXLabel default foreground painter - share between labels. * Probably illegal :-) * IMHO not illegal and sometimes even desirable (Jan). * */ public void interactiveXLabelSharedDefaultForegroundPainter() { JComponent box = Box.createVerticalBox(); final JXLabel foreground = new JXLabel( "setup: compound - default and overlay "); ShapePainter shapePainter = new ShapePainter(); AlphaPainter alpha = new AlphaPainter(); alpha.setAlpha(0.2f); alpha.setPainters(shapePainter); CompoundPainter compound = new CompoundPainter(alpha, foreground .getForegroundPainter()); foreground.setForegroundPainter(compound); box.add(foreground); JXLabel shared = new JXLabel( "setup: shared compound of first label - this doesn't show up"); shared.setForegroundPainter(compound); box.add(shared); showInFrame(box, "shared foreground painters"); } /** * JXLabel background painter not shown if opaque. * */ public void interactiveXLabelBackgroundPainter() { JComponent box = Box.createVerticalBox(); ShapePainter shapePainter = new ShapePainter(); JXLabel opaqueTrue = new JXLabel("setup: backgroundPainter, opaque = true"); opaqueTrue.setOpaque(true); opaqueTrue.setBackgroundPainter(shapePainter); box.add(opaqueTrue); JXLabel opaqueFalse = new JXLabel("setup: backgroundPainter, opaque = false"); opaqueFalse.setOpaque(false); opaqueFalse.setBackgroundPainter(shapePainter); box.add(opaqueFalse); JXLabel opaqueUnchanged = new JXLabel("setup: backgroundPainter, opaque = unchanged"); opaqueUnchanged.setBackgroundPainter(shapePainter); box.add(opaqueUnchanged); showInFrame(box, "background painters"); } /** * * Painters and textfield. Not showing? * */ public void interactiveXButtonShareForegroundPainter() { final CompoundPainter painter = new CompoundPainter(); JXXButton label = new JXXButton(); label.setText("Painter in textfield: source for shared painter"); ShapePainter shapePainter = new ShapePainter(); AlphaPainter alpha = new AlphaPainter(); alpha.setAlpha(0.2f); alpha.setPainters(shapePainter); painter.setPainters(label.getPainter(), alpha); label.setPainter(painter); JXXButton labelAP = new JXXButton(); labelAP.setText("Painter: use shared from above"); labelAP.setPainter(painter); JComponent box = Box.createVerticalBox(); box.add(label); box.add(labelAP); showInFrame(box, "shared ui painting in button"); } public static class JXXButton extends JButton { private Painter painter; @Override protected void paintComponent(Graphics g) { Painter painter = getPainter(); Graphics2D scratch = (Graphics2D) g.create(); try { painter.paint(scratch, this, getWidth(), getHeight()); ui.paint(scratch, this); } finally { scratch.dispose(); } } public Painter getPainter() { if (painter == null) { painter = new AbstractPainter() { @Override protected void doPaint(Graphics2D g, JComponent component, int width, int height) { JXXButton.super.paintComponent(g); } }; } return painter; } public void setPainter(Painter painter) { Painter old = getPainter(); this.painter = painter; firePropertyChange("painter", old, getPainter()); repaint(); } } /** * * paint doc relieves impl from restoring graphics. Who * is responsible for cleanup? * */ public void interactiveRestoreGraphics() { Border redLine = BorderFactory.createLineBorder(Color.RED, 3); final Painter permanentTranslate = new Painter() { public void paint(Graphics2D g, JComponent object, int width, int height) { g.translate(50, 0); } }; JLabel label = new JLabel() { @Override protected void paintComponent(Graphics g) { Graphics2D scratch = (Graphics2D) g.create(); try { permanentTranslate.paint(scratch, this, getWidth(), getHeight()); ui.paint(scratch, this); } finally { scratch.dispose(); } } }; label.setText("Painter: translated Graphics implement Painter"); label.setBorder(redLine); JLabel labelP = new JLabel("setup: painter with translate, no scratch") { /** * Illegal paintComponent - painter made permanent changes */ @Override protected void paintComponent(Graphics g) { permanentTranslate.paint((Graphics2D) g, this, getWidth(), getHeight()); super.paintComponent(g); } }; labelP.setBorder(redLine); final AbstractPainter painterAP = new AbstractPainter() { @Override protected void doPaint(Graphics2D g, JComponent component, int width, int height) { g.translate(50, 0); } }; JLabel labelAP = new JLabel() { @Override protected void paintComponent(Graphics g) { Graphics2D scratch = (Graphics2D) g.create(); try { painterAP.paint(scratch, this, getWidth(), getHeight()); ui.paint(scratch, this); } finally { scratch.dispose(); } } }; labelAP.setText("Painter: translated graphics subclass AbstractPainter"); labelAP.setBorder(redLine); JComponent box = Box.createVerticalBox(); box.add(label); box.add(labelAP); box.add(labelP); showInFrame(box, "unrestored graphics"); } /** * Style.None - use case? Always invisible? */ public void interactiveRenderingLabel() { JComponent box = Box.createVerticalBox(); final JXLabel label = new JXLabel("setup: ShapePainter with fillstyle none"); // fixed: NPE with null shape - but has default instead of null? final ShapePainter styleNone = new ShapePainter(); styleNone.setStyle(ShapePainter.Style.NONE); label.setBackgroundPainter(styleNone); box.add(label); final JXLabel label2 = new JXLabel("setup: default ShapePainter"); final ShapePainter painter = new ShapePainter(); label2.setBackgroundPainter(painter); box.add(label2); Action action = new AbstractActionExt("toggle painter visible") { public void actionPerformed(ActionEvent e) { styleNone.setVisible(!styleNone.isVisible()); painter.setVisible(!painter.isVisible()); label.repaint(); label2.repaint(); } }; JXFrame frame = wrapInFrame(box, "renderer label with shape painter - fillstyle none"); addAction(frame, action); frame.pack(); frame.setVisible(true); } } swingx-1.0-src/src/test/org/jdesktop/swingx/painter/AbstractPainterTest.java0000644000175000017500000003115711210401722026151 0ustar tonytony/* * $Id: AbstractPainterTest.java,v 1.7 2009/03/01 12:01:10 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.painter; import junit.framework.TestCase; import java.awt.*; import java.awt.image.BufferedImage; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.jdesktop.beans.ClassSearchUtils; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * Test for AbstractPainter */ @RunWith(JUnit4.class) public class AbstractPainterTest extends TestCase { private Graphics2D g; private BufferedImage img; private TestablePainter p; private TestableFilter filter; @Before public void setUp() { p = new TestablePainter(); img = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB); g = img.createGraphics(); filter = new TestableFilter(); } @After public void tearDown() { g.dispose(); img.flush(); } @Test public void testPaint() { //test that an NPE is thrown if Graphics is null try { p.paint(null, null, 10, 10); assertTrue(false); } catch (Exception e) { assertTrue(true); } //test that painting works if param object is null p.paint(g, null, 10, 10); assertTrue(p.painted); //test that painting works if param object is specified p.reset(); p.paint(g, "yo", 10, 10); assertTrue(p.painted); //test that no painting occurs if width and/or height is <= 0 p.reset(); p.paint(g, null, 0, 10); assertFalse(p.painted); p.paint(g, null, 10, 0); assertFalse(p.painted); p.paint(g, null, -1, 10); assertFalse(p.painted); p.paint(g, null, 10, -1); assertFalse(p.painted); p.paint(g, null, 0, 0); assertFalse(p.painted); //test that no painting occurs if visible is false p.reset(); p.setVisible(false); p.paint(g, null, 10, 10); assertFalse(p.painted); p.setVisible(true); p.paint(g, null, 10, 10); assertTrue(p.painted); //test that configureGraphics is called in all painting situations p.reset(); p.paint(g, null, 10, 10); assertTrue(p.painted); assertTrue(p.configured); assertTrue(p.configureCalledFirst); } @Test public void testCaching() { p.setCacheable(true); // empty run to fill the cache p.paint(g, null, 10, 10); p.painted = false; //test that the cache is always used UNLESS shouldUseCache is false, or isCacheCleared is true, or the Painter is dirty p.paint(g, null, 10, 10); assertEquals(!p.shouldUseCache() || p.isCacheCleared() || p.isDirty(), p.painted); // disable cache p.reset(); // setting filters means shouldUseCache() will ALWAYS return true!!! p.setFilters(filter); p.paint(g, null, 10, 10); assertEquals(p.shouldUseCache() || p.isCacheCleared() || p.isDirty(), p.painted); p.painted = false; p.paint(g, null, 10, 10); assertEquals(!p.shouldUseCache() || p.isCacheCleared() || p.isDirty(), p.painted); p.clearCache(); p.painted = false; p.paint(g, null, 10, 10); assertEquals(p.shouldUseCache() || p.isCacheCleared() || p.isDirty(), p.painted); p.painted = false; p.paint(g, null, 10, 10); assertEquals(!p.shouldUseCache() || p.isCacheCleared() || p.isDirty(), p.painted); //test that a cache is not used unless cacheable is true OR filters are set p.reset(); p.setCacheable(true); p.paint(g, null, 10, 10); assertTrue(p.painted); p.painted = false; p.paint(g, null, 10, 10); assertFalse(p.painted); p.reset(); p.setCacheable(false); p.setFilters(filter); p.paint(g, null, 10, 10); assertTrue(p.painted); p.painted = false; p.paint(g, null, 10, 10); assertFalse(p.painted); p.reset(); p.setCacheable(true); p.setFilters(filter); p.paint(g, null, 10, 10); assertTrue(p.painted); p.painted = false; p.paint(g, null, 10, 10); assertFalse(p.painted); //test that filters work p.reset(); filter.reset(); p.setFilters(filter); p.paint(g, null, 10, 10); assertTrue(filter.filtered); //test that clearing the cache works (causes the next paint to work) p.reset(); p.setCacheable(true); p.setFilters(filter); p.paint(g, null, 10, 10); assertTrue(p.painted); p.painted = false; p.paint(g, null, 10, 10); assertFalse(p.painted); p.clearCache(); p.paint(g, null, 10, 10); assertTrue(p.painted); //test that the cache is NOT used if the width/height changes p.reset(); p.setCacheable(true); p.setFilters(filter); p.paint(g, null, 10, 10); assertTrue(p.painted); p.painted = false; p.paint(g, null, 5, 5); assertTrue(p.painted); p.painted = false; p.paint(g, null, 5, 5); assertFalse(p.painted); //test that the cache is NOT used if the public state changes p.reset(); p.setCacheable(true); p.setFilters(filter); p.paint(g, null, 10, 10); assertTrue(p.painted); p.setAntialiasing(false); //these three lines are used to make SURE the state has _changed_ to false p.setAntialiasing(true); p.setAntialiasing(false); p.painted = false; p.paint(g, null, 10, 10); assertTrue(p.painted); p.painted = false; p.setAntialiasing(true); p.paint(g, null, 10, 10); assertTrue(p.painted); p.painted = false; p.setAntialiasing(true); //ah! the state has not _really_ changed p.paint(g, null, 10, 10); assertFalse(p.painted); //test that the cache is not used if dependent state has changed. For this //test, the TestablePainter remembers the last "Object" it was sent, and //does an == comparison to see if the state has changed p.reset(); p.setCacheable(true); p.setFilters(filter); p.paint(g, null, 10, 10); assertTrue(p.painted); p.painted = false; p.paint(g, null, 10, 10); assertFalse(p.painted); p.painted = false; p.paint(g, "hi!", 10, 10); assertTrue(p.painted); p.painted = false; p.paint(g, "Duke", 10, 10); assertTrue(p.painted); p.painted = false; p.paint(g, "Duke", 10, 10); assertFalse(p.painted); //using a TestableCompoundPainter, ensure that the cache is cleared if one of //the children's cache is cleared //setup... TestableCompoundPainter c = new TestableCompoundPainter(); TestablePainter p1 = new TestablePainter(); TestablePainter p2 = new TestablePainter(); TestableFilter f2 = new TestableFilter(); c.setPainters(p1, p2); p2.setFilters(f2); c.setFilters(filter); //ok, first time through, all 3 painters should be called, and both filters should be called c.paint(g, null, 10, 10); assertTrue(c.painted); assertTrue(filter.filtered); assertTrue(p1.painted); assertTrue(p2.painted); assertTrue(f2.filtered); c.painted = false; filter.filtered = false; p1.painted = false; p2.painted = false; f2.filtered = false; //next pass, nothing should be called (cache in c should be used) c.paint(g, null, 10, 10); assertFalse(c.painted); assertFalse(filter.filtered); assertFalse(p1.painted); assertFalse(p2.painted); assertFalse(f2.filtered); //next pass, cause c to be invalidated. This should cause c, filter, and p1 to be called, //but p2 should still be cached c.clearCache(); c.paint(g, null, 10, 10); assertTrue(c.painted); assertTrue(filter.filtered); assertTrue(p1.painted); assertFalse(p2.painted); assertFalse(f2.filtered); c.painted = false; filter.filtered = false; p1.painted = false; p2.painted = false; f2.filtered = false; //finally, cause p2 to be invalidated. This should cause c, filter, p1, p2, and f2 to all be called p2.clearCache(); c.paint(g, null, 10, 10); assertTrue(c.painted); assertTrue(filter.filtered); assertTrue(p1.painted); assertTrue(p2.painted); assertTrue(f2.filtered); c.painted = false; filter.filtered = false; p1.painted = false; p2.painted = false; f2.filtered = false; } @Test public void testVisibilityOfOriginallyProtectedMethodsInExtendingClasses() { List> allClasses = ClassSearchUtils.searchClassPath("org.jdesktop.swingx."); List> painters = new ArrayList>(); for (Class clazz : allClasses) { try { if (clazz.isAnonymousClass()) { // skip inner classes as those expose methods for specific purpose (either tests of to overcome some implementation issue) continue; } painters.add(clazz.asSubclass(AbstractPainter.class)); } catch (ClassCastException e) { // ignore } } // collect all protected methods Method[] methods = AbstractPainter.class.getDeclaredMethods(); List mets = new ArrayList(); for (Method m : methods) { if (Modifier.isProtected(m.getModifiers())) { mets.add(m); } } // check that the methods are not made public for (Class clazz : painters) { for (Method m : mets) { try { assertTrue("Class " + clazz.getName() + " must keep overriden AbstractPainter method " + m.getName() + " visibility intact.", Modifier.isProtected(clazz.getDeclaredMethod(m.getName(), m.getParameterTypes()).getModifiers())); } catch (NoSuchMethodException e) { // not declared - ignore } } } } //tests that compound behaviors, such as caching in compound situations, works //I don't extend CompoundPainter because I don't want to test the CompoundPainter //itself, just test the general concepts that go into *any* aggregate Painter //implementation private static final class TestableCompoundPainter extends TestablePainter { TestablePainter[] painters; public void setPainters(TestablePainter... painters) { this.painters = painters; } protected void validate(Object object) { super.validate(object); //iterate over all of the painters and query them to see if they //are valid. The first invalid one clears the cache and returns. for (TestablePainter p : painters) { p.validate(object); if ((p.shouldUseCache() && p.isCacheCleared()) || p.isDirty()) { setDirty(true); clearCache(); return; } } } protected void doPaint(Graphics2D g, Object obj, int width, int height) { super.doPaint(g, obj, width, height); for (TestablePainter p : painters) { p.paint(g, obj, width, height); } } } } swingx-1.0-src/src/test/org/jdesktop/swingx/painter/TestablePainter.java0000644000175000017500000000400011210401722025274 0ustar tonytony/* * $Id: TestablePainter.java,v 1.3 2007/06/13 13:21:26 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.painter; import java.awt.*; import java.awt.image.BufferedImageOp; /** * A useful Painter implementation for Testing purposes * @author rbair */ class TestablePainter extends AbstractPainter { boolean painted = false; boolean configured = false; boolean configureCalledFirst = false; Object last; public TestablePainter() { super(); } public TestablePainter(boolean cacheable) { super(cacheable); } protected void doPaint(Graphics2D g, Object obj, int width, int height) { painted = true; last = obj; } protected void validate(Object object) { if (last != object) { clearCache(); setDirty(true); } } protected void configureGraphics(Graphics2D g) { configured = true; configureCalledFirst = configured && !painted; } void reset() { painted = false; configured = false; setCacheable(false); clearCache(); setFilters((BufferedImageOp[])null); setDirty(false); } } swingx-1.0-src/src/test/org/jdesktop/swingx/painter/PainterVisualCheck.java0000644000175000017500000001742511210401722025751 0ustar tonytony/* * $Id: PainterVisualCheck.java,v 1.4 2008/07/02 03:01:36 kschaefe Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.painter; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.Timer; import org.jdesktop.swingx.JXButton; import org.jdesktop.swingx.JXPanel; import org.jdesktop.swingx.image.FastBlurFilter; /** * JW: renamed from PainterInteractiveTest to fix the build failure. Revisit! * @author rbair */ public class PainterVisualCheck extends RichInteractiveTestCase { public void testJXButtonTextChangeWithBlur() { //Creates a button with a blur on the text. On click events, the //button changes its text. If things are working, then the text //on the button will be changed, and reblurred. In other words, //the painter will be invalid (cache cleared), and updated on the //next paint. final JXButton button = new JXButton(); AbstractPainter p = (AbstractPainter)button.getForegroundPainter(); p.setFilters(new FastBlurFilter()); button.addActionListener(new ActionListener(){ private String[] values = new String[] {"Hello", "Goodbye", "SwingLabs", "Turkey Bowl"}; private int index = 1; public void actionPerformed(ActionEvent ae) { button.setText(values[index]); index++; if (index >= values.length) { index = 0; } } }); JPanel pa = new JPanel(); pa.add(button); assertTrue(showTest(pa, "JXButton text-change with a blur", "On click events, the button changes its text. " + "If things are working, then the text on the button " + "will be changed, and reblurred.")); } public void testCacheWithBlurAndAnimation() { //This test is also covered (more or less) by the regression tests. //This is a second line of defense test, because if the regression test //is messed up, it will be easy to notice here. //I simply have a rectangle painter and a text painter, and the text changes //over time. This should cause the text painter to be invalidated. Likewise, //there is a drop-shadow like blur applied to the whole thing. final JXPanel p = new JXPanel(); final String[] messages = new String[] { "These are the times", "That try men's souls", "And something else", "I can't quite remember" }; final TextPainter text = new TextPainter(); text.setText(messages[0]); CompoundPainter cp = new CompoundPainter( new RectanglePainter(), text ); cp.setFilters(new FastBlurFilter()); p.setBackgroundPainter(cp); Timer t = new Timer(1000, new ActionListener() { int index = 1; public void actionPerformed(ActionEvent ae) { text.setText(messages[index]); index++; if (index >= messages.length) { index = 0; } p.repaint(); } }); t.start(); try { assertTrue(showTest(p, "Test cache works with blur and animation", "In this setup, there is a TextPainter within a CompoundPainter. " + "The CompoundPainter has a filter applied, and uses caching. Thus " + "when the text changes, it is invalidating itself, and the " + "CompoundPainter should detect that and invalidate its cache. " + "If you see the text changing, then this test is passing (or the " + "cache isn't working, but whatever :-))")); } finally { t.stop(); } } public void testCacheWorks() { JXPanel p = new JXPanel(); JLabel label1 = new JLabel(); JLabel label2 = new JLabel(); SlowPainter painter1 = new SlowPainter(); painter1.setCacheable(true); SlowPainter painter2 = new SlowPainter(); painter2.setCacheable(false); p.setLayout(new GridBagLayout()); p.add(label1, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); p.add(label2, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); //fire off two background threads, and let them run until the test is over Thread t1 = new SlowTestThread(painter1, label1, "Cached Painter FPS: "); t1.start(); Thread t2 = new SlowTestThread(painter2, label2, "Normal Painter FPS: "); t2.start(); try { assertTrue(showTest(p, "Test cache works", "Simply tests that rendering speed for a cached painter is faster than " + "rendering speed of a non cached painter. Simply compare the two FPS counters. " + "(Note, I introduce a purposeful 1 second delay on " + "the non-cached version, to ensure that whenever painting occurs, it will " + "be slower than using the cache. Also, both painters are run on background " + "threads so as not to block the GUI)")); } finally { t1.interrupt(); t2.interrupt(); } } private static final class SlowPainter extends AbstractPainter { protected void doPaint(Graphics2D g, Object component, int width, int height) { try { Thread.sleep(1000); } catch (Exception e) {} } protected boolean shouldUseCache() { return isCacheable(); } } private static final class SlowTestThread extends Thread { private Graphics2D g = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB).createGraphics(); private Painter p = null; private JLabel label = null; private String prefix = null; public SlowTestThread(SlowPainter p, JLabel l, String s) { this.p = p; this.label = l; this.prefix = s; } public void run() { while(true) { double start = System.currentTimeMillis(); p.paint(g, null, 10, 10); double stop = System.currentTimeMillis(); final double fps = 1000.0/(stop - start); SwingUtilities.invokeLater(new Runnable() { public void run() { label.setText(prefix + fps); } }); } } } } swingx-1.0-src/src/test/org/jdesktop/swingx/painter/effects/0000755000175000017500000000000011210401732022771 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/painter/effects/AllEffectTest.java0000644000175000017500000000475711210401724026337 0ustar tonytonypackage org.jdesktop.swingx.painter.effects; import java.awt.Color; import java.awt.Point; import org.junit.Test; import static org.junit.Assert.*; /** * Basic effect tests to ensure default behavior is not affected by changes in abstract parents. * @author had * */ public class AllEffectTest { @Test public void testGlowPathEffect() { GlowPathEffect effect = new GlowPathEffect(); assertEquals(Color.WHITE, effect.getBrushColor()); assertEquals(10, effect.getBrushSteps()); assertEquals(10, effect.getEffectWidth()); assertEquals(new Point(0,0), effect.getOffset()); assertFalse(effect.isRenderInsideShape()); assertFalse(effect.isShouldFillShape()); } @Test public void testInnerGlowPathEffect() { InnerGlowPathEffect effect = new InnerGlowPathEffect(); assertEquals(Color.WHITE, effect.getBrushColor()); assertEquals(10, effect.getBrushSteps()); assertEquals(10, effect.getEffectWidth()); assertEquals(new Point(0,0), effect.getOffset()); assertTrue(effect.isRenderInsideShape()); assertFalse(effect.isShouldFillShape()); } @Test public void testInnerShadowPathEffect() { InnerShadowPathEffect effect = new InnerShadowPathEffect(); assertEquals(Color.BLACK, effect.getBrushColor()); assertEquals(10, effect.getBrushSteps()); assertEquals(8, effect.getEffectWidth()); assertEquals(new Point(2,2), effect.getOffset()); assertTrue(effect.isRenderInsideShape()); assertTrue(effect.isShouldFillShape()); } @Test public void testShadowPathEffect() { ShadowPathEffect effect = new ShadowPathEffect(); assertEquals(Color.BLACK, effect.getBrushColor()); assertEquals(10, effect.getBrushSteps()); assertEquals(8, effect.getEffectWidth()); assertEquals(new Point(3,3), effect.getOffset()); assertFalse(effect.isRenderInsideShape()); assertTrue(effect.isShouldFillShape()); } @Test public void testNeonBorderEffect() { NeonBorderEffect effect = new NeonBorderEffect(); assertEquals(Color.GREEN, effect.getEdgeColor()); assertEquals(Color.WHITE, effect.getCenterColor()); assertEquals(10, effect.getBrushSteps()); assertEquals(10, effect.getEffectWidth()); assertEquals(new Point(0,0), effect.getOffset()); assertFalse(effect.isRenderInsideShape()); assertFalse(effect.isShouldFillShape()); } } swingx-1.0-src/src/test/org/jdesktop/swingx/painter/RichInteractiveTestCase.java0000644000175000017500000001015711210401722026737 0ustar tonytony/* * $Id: RichInteractiveTestCase.java,v 1.4 2009/01/27 23:00:22 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.painter; import org.jdesktop.swingx.JXHeader; import org.jdesktop.swingx.JXFrame; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.lang.reflect.InvocationTargetException; import junit.framework.TestCase; /** * @author rbair */ @RunWith(JUnit4.class) public class RichInteractiveTestCase extends TestCase { private boolean retVal = false; private boolean block = true; protected boolean showTest(final JComponent c, final String title, final String instructions) { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { JXHeader h = new JXHeader(); h.setTitle(title); h.setDescription(instructions); final JXFrame frame = new JXFrame(title); frame.setDefaultCloseOperation(JXFrame.DISPOSE_ON_CLOSE); frame.add(c, BorderLayout.CENTER); frame.add(h, BorderLayout.NORTH); JButton failButton = new JButton("Fail"); failButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { frame.setVisible(false); retVal = false; block = false; } }); JButton passButton = new JButton("Pass"); passButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { frame.setVisible(false); retVal = true; block = false; } }); JPanel buttonPanel = new JPanel(); buttonPanel.add(passButton); buttonPanel.add(failButton); frame.add(buttonPanel, BorderLayout.SOUTH); frame.addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent windowEvent) { block = false; } }); frame.setSize(400, 300); frame.setStartPosition(JXFrame.StartPosition.CenterInScreen); frame.setVisible(true); } }); } catch (InterruptedException e) { e.printStackTrace(); block = false; } catch (InvocationTargetException e) { e.printStackTrace(); block = false; } while (block) { try { Thread.sleep(500); } catch (Exception e) {} } return retVal; } /** * Do nothing, make the test runner happy * (would output a warning without a test fixture). * */ @Test public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/painter/CompoundPainterTest.java0000644000175000017500000002120311210401722026161 0ustar tonytony/* * $Id: CompoundPainterTest.java,v 1.8 2008/12/05 21:45:26 kschaefe Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.painter; import junit.framework.TestCase; import java.awt.*; import java.awt.image.BufferedImage; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * @author rbair */ @RunWith(JUnit4.class) public class CompoundPainterTest extends TestCase { private Graphics2D g; private BufferedImage img; private TestableCompoundPainter cp1; private TestableFilter f1; private TestablePainter p1; private TestablePainter p2; private TestableFilter f2; private TestableCompoundPainter cp2; private TestablePainter p3; private TestablePainter p4; private TestableFilter f3; private TestablePainter p5; private TestableCompoundPainter onlyCachedPainters; @Override @Before public void setUp() { img = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB); g = img.createGraphics(); cp1 = new TestableCompoundPainter(); f1 = new TestableFilter(); p1 = new TestablePainter(); p2 = new TestablePainter(); f2 = new TestableFilter(); cp2 = new TestableCompoundPainter(); p3 = new TestablePainter(); p4 = new TestablePainter(); f3 = new TestableFilter(); p5 = new TestablePainter(); cp1.setPainters(p1, p2, cp2); cp1.setFilters(f1); p2.setFilters(f2); cp2.setPainters(p3, p4, p5); p4.setFilters(f3); onlyCachedPainters = new TestableCompoundPainter(); onlyCachedPainters.setPainters(p2, p4); onlyCachedPainters.setFilters(f1); } @Override @After public void tearDown() { g.dispose(); img.flush(); } //tests to make sure the cache is not used on the first pass through //the painting routines. That is, a cache shouldn't be used unless //something has been painted to the cache first. @Test public void testCacheNotUsedFirstPass() { cp1.paint(g, null, 10, 10); assertTrue(cp1.painted); assertTrue(f1.filtered); assertTrue(p1.painted); assertTrue(p2.painted); assertTrue(f2.filtered); assertTrue(cp2.painted); assertTrue(p3.painted); assertTrue(p4.painted); assertTrue(f3.filtered); assertTrue(p5.painted); } /** * Issue #497-swingx: setPainters can't cope with null. * */ @Test public void testSetNullPainters() { CompoundPainter painter = new CompoundPainter(); // changed to cast to Painter, since uncasted it is equivalent to // Painter[], which is checked in the next test painter.setPainters((Painter) null); } /** * Issue #497-swingx: setPainters can't cope with null. * */ @Test public void testSetEmptyPainters() { CompoundPainter painter = new CompoundPainter(); // okay painter.setPainters(); // fails painter.setPainters((Painter[]) null); } @Test public void testCacheNotUsedFirstPass2() { onlyCachedPainters.paint(g, null, 10, 10); assertTrue(onlyCachedPainters.painted); assertTrue(f1.filtered); assertTrue(p2.painted); assertTrue(f2.filtered); assertTrue(p4.painted); assertTrue(f3.filtered); } @Test public void testCacheUsedSecondPass() { cp1.paint(g, null, 10, 10); reset(); cp1.paint(g, null, 10, 10); assertFalse(cp1.painted); assertFalse(f1.filtered); assertFalse(p1.painted); assertFalse(p2.painted); assertFalse(f2.filtered); assertFalse(cp2.painted); assertFalse(p3.painted); assertFalse(p4.painted); assertFalse(f3.filtered); assertFalse(p5.painted); } @Test public void testCacheUsedSecondPass2() { onlyCachedPainters.paint(g, null, 10, 10); reset(); onlyCachedPainters.paint(g, null, 10, 10); assertFalse(onlyCachedPainters.painted); assertFalse(f1.filtered); assertFalse(p2.painted); assertFalse(f2.filtered); assertFalse(p4.painted); assertFalse(f3.filtered); } @Test public void testIfChildPainterIsInvalidByBeingDirty() { testCacheUsedSecondPass(); p4.setDirty(true); cp1.paint(g, null, 10, 10); assertTrue(cp1.painted); assertTrue(f1.filtered); assertTrue(p1.painted); assertFalse(p2.painted); assertFalse(f2.filtered); assertTrue(cp2.painted); assertTrue(p3.painted); assertTrue(p4.painted); assertTrue(f3.filtered); assertTrue(p5.painted); } private void reset() { cp1.painted = false; f1.filtered = false; p1.painted = false; p2.painted = false; f2.filtered = false; cp2.painted = false; p3.painted = false; p4.painted = false; f3.filtered = false; p5.painted = false; onlyCachedPainters.painted = false; } @Test public void testUncachedPainterInvalidation() { p1.setCacheable(false); p2.setCacheable(false); cp2.setCacheable(false); p3.setCacheable(false); p4.setCacheable(false); p5.setCacheable(false); cp1.paint(g, null, 10, 10); reset(); cp1.paint(g, null, 10, 10); assertFalse(cp1.painted); assertFalse(p1.painted); assertFalse(p2.painted); assertFalse(cp2.painted); assertFalse(p3.painted); assertFalse(p4.painted); assertFalse(p5.painted); p1.setDirty(true); cp1.paint(g, null, 10, 10); assertTrue(cp1.painted); assertTrue(p1.painted); // p2 has filters therefore is cacheable by default (inherited from AbstractPainter) assertFalse(p2.painted); assertTrue(cp2.painted); assertTrue(p3.painted); // p4 has filters therefore is cacheable by default (inherited from AbstractPainter) assertFalse(p4.painted); assertTrue(p5.painted); } @Test public void testAb5k() { TestableCompoundPainter base = new TestableCompoundPainter(); base.setCacheable(true); TestableCompoundPainter background = new TestableCompoundPainter(); // ... since default is now false background.setCacheable(true); TestablePainter iris = new TestablePainter(); TestablePainter[] painters = new TestablePainter[100]; for (int i=0; i { boolean painted = false; @Override protected void doPaint(Graphics2D g, Object obj, int width, int height) { painted = true; super.doPaint(g, obj, width, height); } void reset() { painted = false; } } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXLabelTest.java0000644000175000017500000000350711210401722022700 0ustar tonytony/* * $Id: JXLabelTest.java,v 1.2 2009/01/27 22:53:23 rah003 Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx; import java.util.logging.Logger; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.painter.Painter; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Base test class for JXLabel related code and issues. * * @author rah003 */ @RunWith(JUnit4.class) public class JXLabelTest extends InteractiveTestCase { static Logger log = Logger.getAnonymousLogger(); /** * Issue #??-swingx: default foreground painter not guaranteed after change. * */ @Test public void testDefaultForegroundPainter() { JXLabel label = new JXLabel(); Painter defaultForeground = label.getForegroundPainter(); // sanity assertNotNull(defaultForeground); label.setForegroundPainter(null); assertEquals(defaultForeground, label.getForegroundPainter()); } } swingx-1.0-src/src/test/org/jdesktop/swingx/treetable/0000755000175000017500000000000011210401734021661 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/treetable/TreeTableModelIssues.java0000644000175000017500000000257711210401722026560 0ustar tonytony/* * $Id: TreeTableModelIssues.java,v 1.6 2009/01/22 10:46:42 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.treetable; import java.util.logging.Logger; import javax.swing.tree.TreePath; import org.jdesktop.swingx.InteractiveTestCase; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * * Known issues around TreeTableModel and related classes. * */ @RunWith(JUnit4.class) public class TreeTableModelIssues extends InteractiveTestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger .getLogger(TreeTableModelIssues.class.getName()); public static void main(String[] args) { TreeTableModelIssues test = new TreeTableModelIssues(); try { test.runInteractiveTests(); } catch (Exception e) { e.printStackTrace(); } } /** * TreePath issue: null must not be allowed as path element. * The constructor doesn't cope with array containing null. */ @Test public void testTreeStructureChangedEmptyPath() { TreePath path = new TreePath(new Object[] {null}); assertNotNull("TreePath must not contain null path elements", path.getLastPathComponent()); } } swingx-1.0-src/src/test/org/jdesktop/swingx/treetable/TreeTableModelTest.java0000644000175000017500000001340111210401722026210 0ustar tonytony/* * $Id: TreeTableModelTest.java,v 1.3 2009/01/22 10:46:41 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.treetable; import java.awt.event.ActionEvent; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JTree; import javax.swing.tree.TreeModel; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests around TreeTableModel and related classes. */ @RunWith(JUnit4.class) public class TreeTableModelTest extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(TreeTableModelTest.class .getName()); /** * Issue #??-swingx: FileSystemModel throws NPE in getChildCount. * */ @Test public void testFileSystemModelNPE() { TreeModel model = new FileSystemModel(); Object root = model.getRoot(); for (int i = 0; i < model.getChildCount(root); i++) { Object child = model.getChild(root, i); // sanity assertNotNull("child must not be null at " + i, child); model.getChildCount(child); } } /** * Issue #??-swingx: SimpleFileSystemModel throws NPE in getChildCount. */ @Test public void testFileSystemModelSimple() { SimpleFileSystemModel model = new SimpleFileSystemModel(); Object root = model.getRoot(); for (int i = 0; i < model.getChildCount(root); i++) { Object child = model.getChild(root, i); // sanity assertNotNull("child must not be null at " + i, child); model.getChildCount(child); } } /** * Issue #218-swingx: TreeTableModel impl break type contract for * hierarchical column. * * Expected contract (non-doc'ed but common sense...) * *
 
     * 
     * Object value = model.getValueAt(node, column);
     * assert((value == null) || 
     *    (model.getColumnClass(column).isAssignableFrom(value.getClass())))
     *    
     *  
* * Here: FileSystemModel. * */ @Test public void testFileSystemTTM() { TreeTableModel model = new FileSystemModel(); assertColumnClassAssignableFromValue(model); } /** * loops through all model columns to test type contract. * * * @param model the model to test. */ private void assertColumnClassAssignableFromValue(TreeTableModel model) { for (int i = 0; i < model.getColumnCount(); i++) { Class clazz = model.getColumnClass(i); Object value = model.getValueAt(model.getRoot(), i); if (value != null) { assertTrue("column class must be assignable to value class at column " + i + "\n" + "columnClass = " + model.getColumnClass(i) + "\n" + "valueClass = " + value.getClass() , clazz.isAssignableFrom(value.getClass())); } else { LOG.info("column " + i + " not testable - value == null"); } } } //---------------------- interactive /** * Issue #984-swingx: IllegalArgumentException if removing selected node. * * base reason: DefaultTreeTableModel getIndexOfChild violates super's * contract. * */ public void interactiveRemoveLargeModel() { final ClearableTreeTableModel model = new ClearableTreeTableModel(); model.addToRoot("dummy"); JTree tree = new JTree(model); tree.expandRow(0); tree.setSelectionInterval(1, 1); tree.setLargeModel(true); JXFrame frame = wrapWithScrollingInFrame(tree, "remove and large"); Action remove = new AbstractAction("remove selected") { public void actionPerformed(ActionEvent e) { model.clear(); setEnabled(false); } }; addAction(frame, remove); show(frame, 400, 200); } // Model that allows to remove all nodes except the root node public static class ClearableTreeTableModel extends DefaultTreeTableModel { public ClearableTreeTableModel() { super(new DefaultMutableTreeTableNode("Root")); } public void addToRoot(Object userObject) { DefaultMutableTreeTableNode node = new DefaultMutableTreeTableNode( userObject); insertNodeInto(node, (MutableTreeTableNode) getRoot(), 0); } public void clear() { // remove all nodes except the root node for (int i = this.getChildCount(getRoot()) - 1; i >= 0; i--) { this.removeNodeFromParent((MutableTreeTableNode) this.getChild( getRoot(), i)); } } }; } swingx-1.0-src/src/test/org/jdesktop/swingx/treetable/DefaultTreeTableModelUnitTest.java0000644000175000017500000003243211210401722030362 0ustar tonytonypackage org.jdesktop.swingx.treetable; import java.util.Vector; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; import junit.framework.TestCase; /** * */ @RunWith(JUnit4.class) public class DefaultTreeTableModelUnitTest extends TestCase { private DefaultTreeTableModel model; private DefaultMutableTreeTableNode root; private DefaultMutableTreeTableNode child1; private DefaultMutableTreeTableNode child2; private DefaultMutableTreeTableNode grandchild1; private DefaultMutableTreeTableNode grandchild2; private DefaultMutableTreeTableNode grandchild3; private DefaultMutableTreeTableNode grandchild4; private DefaultMutableTreeTableNode grandchild5; private AbstractMutableTreeTableNode grandchild6; @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } private TreeTableNode createTree() { root = new DefaultMutableTreeTableNode("root"); child1 = new DefaultMutableTreeTableNode("child1"); grandchild1 = new DefaultMutableTreeTableNode("grandchild1"); child1.add(grandchild1); grandchild2 = new DefaultMutableTreeTableNode("grandchild2"); child1.add(grandchild2); grandchild3 = new DefaultMutableTreeTableNode("grandchild3"); child1.add(grandchild3); root.add(child1); child2 = new DefaultMutableTreeTableNode("child2"); grandchild4 = new DefaultMutableTreeTableNode("grandchild4"); child2.add(grandchild4); grandchild5 = new DefaultMutableTreeTableNode("grandchild5"); child2.add(grandchild5); grandchild6 = new AbstractMutableTreeTableNode("grandchild6") { public int getColumnCount() { return 0; } public Object getValueAt(int column) { return getUserObject(); } }; child2.add(grandchild6); root.add(child2); return root; } /** * {@inheritDoc} */ @Override protected void setUp() throws Exception { super.setUp(); Vector names = new Vector(); names.add("A"); model = new DefaultTreeTableModel(createTree(), names); } @Test public void testGetPathToRoot() { TreeNode[] testGroup1 = model.getPathToRoot(grandchild3); assertEquals(testGroup1[0], root); assertEquals(testGroup1[1], child1); assertEquals(testGroup1[2], grandchild3); TreeNode[] testGroup2 = model.getPathToRoot(child2); assertEquals(testGroup2[0], root); assertEquals(testGroup2[1], child2); TreeNode[] testGroup3 = model.getPathToRoot(root); assertEquals(testGroup3[0], root); try { model.getPathToRoot(null); fail("expected NullPointerException"); } catch (NullPointerException e) { //success } try { model.getPathToRoot(new DefaultMutableTreeTableNode("failure")); fail("expected NullPointerException"); } catch (NullPointerException e) { //success } } @Test public void testGetValueAt() { //Test expected cases assertEquals(model.getValueAt(root, 0), "root"); //Outside TTN count assertNull(model.getValueAt(grandchild6, 0)); //Test boundary cases try { model.getValueAt(child1, model.getColumnCount()); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } try { model.getValueAt(grandchild4, -1); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } //Test exceptional cases try { model.getValueAt(null, 0); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } try { model.getValueAt(new Object(), 0); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } } @Test public void testSetValueAt() { //Test expected cases model.setValueAt("new", root, 0); assertEquals(model.getValueAt(root, 0), "new"); //Test boundary cases try { model.setValueAt("new", child1, model.getColumnCount()); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } try { model.setValueAt("new", grandchild4, -1); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } //Test exceptional cases try { model.setValueAt("new", null, 0); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } try { model.setValueAt("new", new Object(), 0); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } } public void testSetValueAtIssues() { //TODO what to do in this case? exception? nothing? //Outside TTN count model.setValueAt("new", grandchild6, 0); } @Test public void testGetChild() { assertEquals(model.getChild(root, 0), child1); //Test boundary cases //TODO untestable: outcome depends on how node handles OOB //should TTN document an IOOBException? //Test exceptional cases try { model.getChild(null, 0); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } try { model.getChild(new Object(), 0); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } } @Test public void testGetChildCount() { assertEquals(model.getChildCount(root), 2); assertEquals(model.getChildCount(child1), 3); assertEquals(model.getChildCount(grandchild4), 0); //Test exceptional cases try { model.getChildCount(null); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } try { model.getChildCount(new Object()); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } } /** * Testing that indexOfChild returns -1 for uncontained parent/child nodes. */ @Test public void testGetIndexOfChild() { assertEquals(model.getIndexOfChild(root,child1), 0); assertEquals(model.getIndexOfChild(root,child2), 1); assertEquals(-1, model.getIndexOfChild(null, child1)); assertEquals(-1, model.getIndexOfChild(new Object(), child1)); assertEquals(-1, model.getIndexOfChild(child1, null)); assertEquals(-1, model.getIndexOfChild(child1, new Object())); // //Test exceptional cases // try { // model.getIndexOfChild(null, child1); // fail("expected IllegalArgumentException"); // } catch (IllegalArgumentException e) { // //success // } // // try { // model.getIndexOfChild(new Object(), child1); // fail("expected IllegalArgumentException"); // } catch (IllegalArgumentException e) { // //success // } // try { // model.getIndexOfChild(child1, null); // fail("expected IllegalArgumentException"); // } catch (IllegalArgumentException e) { // //success // } // // try { // model.getIndexOfChild(child1, new Object()); // fail("expected IllegalArgumentException"); // } catch (IllegalArgumentException e) { // //success // } } @Test public void testIsCellEditable() { //Test expected cases // assertFalse(model.isLeaf(root)); // assertFalse(model.isLeaf(child2)); // assertTrue(model.isLeaf(grandchild3)); //Test boundary cases try { model.isCellEditable(root, model.getColumnCount()); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } try { model.isCellEditable(root, -1); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } //Test exceptional cases try { model.isCellEditable(null, 0); fail("IllegalArgumentException is not thrown."); } catch (IllegalArgumentException e) { //test succeeded } try { model.isCellEditable(new Object(), 0); fail("IllegalArgumentException is not thrown."); } catch (IllegalArgumentException e) { //test succeeded } } @Test public void testModelIsLeaf() { //Test expected cases assertFalse(model.isLeaf(root)); assertFalse(model.isLeaf(child2)); assertTrue(model.isLeaf(grandchild3)); //Test exceptional cases try { model.isLeaf(null); fail("IllegalArgumentException is not thrown."); } catch (IllegalArgumentException e) { //test succeeded } try { model.isLeaf(new Object()); fail("IllegalArgumentException is not thrown."); } catch (IllegalArgumentException e) { //test succeeded } } @Test public void testRemoveFromParent() { try { model.removeNodeFromParent(new DefaultMutableTreeTableNode()); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } try { DefaultMutableTreeTableNode p = new DefaultMutableTreeTableNode(); DefaultMutableTreeTableNode c = new DefaultMutableTreeTableNode(); c.setParent(p); model.removeNodeFromParent(c); fail("Expected NullPointerException"); } catch (NullPointerException e) { //success //TODO does not seem like the correct exception } TreeNode parent = grandchild6.getParent(); int count = parent.getChildCount(); model.removeNodeFromParent(grandchild6); assertNull(grandchild6.getParent()); assertEquals(parent.getChildCount(), count - 1); model.removeNodeFromParent(child1); assertNull(child1.getParent()); try { model.removeNodeFromParent(root); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } //TODO test removing already removed nodes? } @Test public void testSetRoot() { assertEquals(model.getRoot(), root); DefaultMutableTreeTableNode newRoot = new DefaultMutableTreeTableNode("a new root"); model.setRoot(newRoot); assertEquals(model.getRoot(), newRoot); } //TODO test "fire" methods and reloads @Test public void testValueForPathChanged() { //Test expected cases model.valueForPathChanged(new TreePath(root), "a new root"); assertEquals(root.getUserObject(), "a new root"); //Test exceptional cases try { model.valueForPathChanged(null, new Object()); fail("Expected NullPointerException"); } catch (NullPointerException e) { //success } try { model.valueForPathChanged(new TreePath(new Object()), new Object()); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } } @Test public void testSetUserObject() { //Test expected cases model.setUserObject(grandchild2, "a new value"); assertEquals(grandchild2.getUserObject(), "a new value"); //Test exceptional cases try { model.setUserObject(null, new Object()); fail("Expected NullPointerException"); } catch (NullPointerException e) { //success } //TODO fix model to return correct exception // try { // model.setUserObject(new DefaultMutableTreeTableNode("unmanaged"), new Object()); // fail("Expected IllegalArgumentException"); // } catch (IllegalArgumentException e) { // //success // } } } swingx-1.0-src/src/test/org/jdesktop/swingx/treetable/AbstractTreeTableModelUnitTest.java0000644000175000017500000003021211210401722030533 0ustar tonytony/* * $Id: AbstractTreeTableModelUnitTest.java,v 1.4 2008/10/11 20:42:33 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.treetable; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; import junit.framework.TestCase; @RunWith(JUnit4.class) public class AbstractTreeTableModelUnitTest extends TestCase { private static class DummyTreeTableModel extends AbstractTreeTableModel { public DummyTreeTableModel(Object root) { super(root); } //these methods are effectively no-ops public int getColumnCount() { return 0; } public Object getValueAt(Object node, int column) { return null; } public Object getChild(Object parent, int index) { return null; } public int getChildCount(Object parent) { return 0; } public int getIndexOfChild(Object parent, Object child) { return 0; } @Override public boolean isLeaf(Object node) { return false; } } private static class FailingTreeModelListener implements TreeModelListener { public void treeNodesChanged(TreeModelEvent e) { fail(e.toString()); } public void treeNodesInserted(TreeModelEvent e) { fail(e.toString()); } public void treeNodesRemoved(TreeModelEvent e) { fail(e.toString()); } public void treeStructureChanged(TreeModelEvent e) { fail(e.toString()); } } private DummyTreeTableModel dummyModel; private DummyTreeTableModel nullModel; private DefaultMutableTreeNode root; private DefaultMutableTreeNode child1; private DefaultMutableTreeNode child2; private DefaultMutableTreeNode grandchild1; private DefaultMutableTreeNode grandchild2; private DefaultMutableTreeNode grandchild3; private DefaultMutableTreeNode grandchild4; private DefaultMutableTreeNode grandchild5; private DefaultMutableTreeNode grandchild6; @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } private TreeNode createTree() { root = new DefaultMutableTreeNode("root"); child1 = new DefaultMutableTreeNode("child1"); grandchild1 = new DefaultMutableTreeNode("grandchild1"); child1.add(grandchild1); grandchild2 = new DefaultMutableTreeNode("grandchild2"); child1.add(grandchild2); grandchild3 = new DefaultMutableTreeNode("grandchild3"); child1.add(grandchild3); root.add(child1); child2 = new DefaultMutableTreeNode("child2"); grandchild4 = new DefaultMutableTreeNode("grandchild4"); child2.add(grandchild4); grandchild5 = new DefaultMutableTreeNode("grandchild5"); child2.add(grandchild5); grandchild6 = new DefaultMutableTreeNode("grandchild6"); child2.add(grandchild6); root.add(child2); return root; } /** * {@inheritDoc} */ @Override protected void setUp() throws Exception { super.setUp(); dummyModel = new DummyTreeTableModel(createTree()); nullModel = new DummyTreeTableModel(null); } @Test public void testModelGetColumnClass() { // method returns a constant, but test is useful for ensuring that the // method returns the same values over time. assertEquals(dummyModel.getColumnClass(Integer.MIN_VALUE), Object.class); assertEquals(dummyModel.getColumnClass(-1), Object.class); assertEquals(dummyModel.getColumnClass(0), Object.class); assertEquals(dummyModel.getColumnClass(1), Object.class); assertEquals(dummyModel.getColumnClass(Integer.MAX_VALUE), Object.class); //demonstrate getColumnClass unaffected by root value assertEquals(nullModel.getColumnClass(Integer.MIN_VALUE), Object.class); assertEquals(nullModel.getColumnClass(-1), Object.class); assertEquals(nullModel.getColumnClass(0), Object.class); assertEquals(nullModel.getColumnClass(1), Object.class); assertEquals(nullModel.getColumnClass(Integer.MAX_VALUE), Object.class); } @Test public void testModelGetColumnName() { assertEquals(dummyModel.getColumnName(Integer.MIN_VALUE), ""); assertEquals(dummyModel.getColumnName(-1), ""); assertEquals(dummyModel.getColumnName(0), "A"); assertEquals(dummyModel.getColumnName(1), "B"); assertEquals(dummyModel.getColumnName(26), "AA"); assertEquals(dummyModel.getColumnName(702), "AAA"); assertEquals(dummyModel.getColumnName(Integer.MAX_VALUE), "FXSHRXX"); //demonstrate getColumnName unaffected by root value assertEquals(nullModel.getColumnName(Integer.MIN_VALUE), ""); assertEquals(nullModel.getColumnName(-1), ""); assertEquals(nullModel.getColumnName(0), "A"); assertEquals(nullModel.getColumnName(1), "B"); assertEquals(nullModel.getColumnName(26), "AA"); assertEquals(nullModel.getColumnName(702), "AAA"); assertEquals(nullModel.getColumnName(Integer.MAX_VALUE), "FXSHRXX"); } @Test public void testModelGetHierarchicalColumn() { // method returns a constant, but test is useful for ensuring that the // method returns the same values over time. assertEquals(dummyModel.getHierarchicalColumn(), -1); //demonstrate getHierarchicalColumn unaffected by root value assertEquals(nullModel.getHierarchicalColumn(), -1); } @Test public void testModelGetRoot() { // method returns a constant, but test is useful for ensuring that the // method returns the same values over time. assertEquals(dummyModel.getRoot(), root); //demonstrate getRoot unaffected by root value assertNull(nullModel.getRoot()); } @Test public void testModelIsCellEditable() { // method returns a constant, but test is useful for ensuring that the // method returns the same values over time. assertFalse(dummyModel.isCellEditable(Integer.MIN_VALUE, Integer.MIN_VALUE)); assertFalse(dummyModel.isCellEditable(Integer.MIN_VALUE, -1)); assertFalse(dummyModel.isCellEditable(Integer.MIN_VALUE, 0)); assertFalse(dummyModel.isCellEditable(Integer.MIN_VALUE, 1)); assertFalse(dummyModel.isCellEditable(Integer.MIN_VALUE, Integer.MAX_VALUE)); assertFalse(dummyModel.isCellEditable(-1, Integer.MAX_VALUE)); assertFalse(dummyModel.isCellEditable(-1, -1)); assertFalse(dummyModel.isCellEditable(-1, 0)); assertFalse(dummyModel.isCellEditable(-1, 1)); assertFalse(dummyModel.isCellEditable(-1, Integer.MAX_VALUE)); assertFalse(dummyModel.isCellEditable(0, Integer.MIN_VALUE)); assertFalse(dummyModel.isCellEditable(0, -1)); assertFalse(dummyModel.isCellEditable(0, 0)); assertFalse(dummyModel.isCellEditable(0, 1)); assertFalse(dummyModel.isCellEditable(0, Integer.MAX_VALUE)); assertFalse(dummyModel.isCellEditable(1, Integer.MIN_VALUE)); assertFalse(dummyModel.isCellEditable(1, -1)); assertFalse(dummyModel.isCellEditable(1, 0)); assertFalse(dummyModel.isCellEditable(1, 1)); assertFalse(dummyModel.isCellEditable(1, Integer.MAX_VALUE)); assertFalse(dummyModel.isCellEditable(Integer.MAX_VALUE, Integer.MIN_VALUE)); assertFalse(dummyModel.isCellEditable(Integer.MAX_VALUE, -1)); assertFalse(dummyModel.isCellEditable(Integer.MAX_VALUE, 0)); assertFalse(dummyModel.isCellEditable(Integer.MAX_VALUE, 1)); assertFalse(dummyModel.isCellEditable(Integer.MAX_VALUE, Integer.MAX_VALUE)); //demonstrate isCellEditable unaffected by root value assertFalse(nullModel.isCellEditable(Integer.MIN_VALUE, Integer.MIN_VALUE)); assertFalse(nullModel.isCellEditable(Integer.MIN_VALUE, -1)); assertFalse(nullModel.isCellEditable(Integer.MIN_VALUE, 0)); assertFalse(nullModel.isCellEditable(Integer.MIN_VALUE, 1)); assertFalse(nullModel.isCellEditable(Integer.MIN_VALUE, Integer.MAX_VALUE)); assertFalse(nullModel.isCellEditable(-1, Integer.MAX_VALUE)); assertFalse(nullModel.isCellEditable(-1, -1)); assertFalse(nullModel.isCellEditable(-1, 0)); assertFalse(nullModel.isCellEditable(-1, 1)); assertFalse(nullModel.isCellEditable(-1, Integer.MAX_VALUE)); assertFalse(nullModel.isCellEditable(0, Integer.MIN_VALUE)); assertFalse(nullModel.isCellEditable(0, -1)); assertFalse(nullModel.isCellEditable(0, 0)); assertFalse(nullModel.isCellEditable(0, 1)); assertFalse(nullModel.isCellEditable(0, Integer.MAX_VALUE)); assertFalse(nullModel.isCellEditable(1, Integer.MIN_VALUE)); assertFalse(nullModel.isCellEditable(1, -1)); assertFalse(nullModel.isCellEditable(1, 0)); assertFalse(nullModel.isCellEditable(1, 1)); assertFalse(nullModel.isCellEditable(1, Integer.MAX_VALUE)); assertFalse(nullModel.isCellEditable(Integer.MAX_VALUE, Integer.MIN_VALUE)); assertFalse(nullModel.isCellEditable(Integer.MAX_VALUE, -1)); assertFalse(nullModel.isCellEditable(Integer.MAX_VALUE, 0)); assertFalse(nullModel.isCellEditable(Integer.MAX_VALUE, 1)); assertFalse(nullModel.isCellEditable(Integer.MAX_VALUE, Integer.MAX_VALUE)); } //Will only fail if an exception is thrown @Test public void testModelListenerMethods() { FailingTreeModelListener l = new FailingTreeModelListener(); dummyModel.addTreeModelListener(l); dummyModel.addTreeModelListener(null); nullModel.addTreeModelListener(l); nullModel.addTreeModelListener(null); dummyModel.removeTreeModelListener(l); dummyModel.removeTreeModelListener(null); nullModel.removeTreeModelListener(l); nullModel.removeTreeModelListener(null); } //TODO test fire methods //Will only fail if valueForPathChanged ever fire events @Test public void testModelValueForPathChanged() { FailingTreeModelListener l = new FailingTreeModelListener(); dummyModel.addTreeModelListener(l); dummyModel.valueForPathChanged(null, null); dummyModel.valueForPathChanged(null, new Object()); dummyModel.valueForPathChanged(new TreePath(new Object()), null); dummyModel.valueForPathChanged(new TreePath(new Object()), new Object()); //demonstrate valueForPathChanged unaffected by root value nullModel.addTreeModelListener(l); nullModel.valueForPathChanged(null, null); nullModel.valueForPathChanged(null, new Object()); nullModel.valueForPathChanged(new TreePath(new Object()), null); nullModel.valueForPathChanged(new TreePath(new Object()), new Object()); } } swingx-1.0-src/src/test/org/jdesktop/swingx/treetable/DefaultMutableTreeTableNodeUnitTest.java0000644000175000017500000002554611210401722031531 0ustar tonytony/** * */ package org.jdesktop.swingx.treetable; import java.util.Enumeration; import javax.swing.tree.DefaultMutableTreeNode; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; import junit.framework.TestCase; /** * */ @RunWith(JUnit4.class) public class DefaultMutableTreeTableNodeUnitTest extends TestCase { @Test public void testAdd() { DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode("root"); assertEquals(root.getChildCount(), 0); root.add(new DefaultMutableTreeTableNode("a")); assertEquals(root.getChildCount(), 1); root.add(new DefaultMutableTreeTableNode("a")); assertEquals(root.getChildCount(), 2); } @Test public void testAddDoesNotDuplicate() { DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode("root"); assertEquals(root.getChildCount(), 0); DefaultMutableTreeTableNode a = new DefaultMutableTreeTableNode("a"); root.add(a); assertEquals(root.getChildCount(), 1); root.add(a); assertEquals(root.getChildCount(), 1); } @Test public void testChildren() { DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode("root"); Enumeration children = root.children(); while (children.hasMoreElements()) { fail("This enumaration should have no elements"); } DefaultMutableTreeTableNode a = new DefaultMutableTreeTableNode("a"); DefaultMutableTreeTableNode b = new DefaultMutableTreeTableNode("b"); DefaultMutableTreeTableNode c = new DefaultMutableTreeTableNode("c"); DefaultMutableTreeTableNode d = new DefaultMutableTreeTableNode("d"); root.add(a); root.add(b); root.add(c); root.add(d); children = root.children(); assertEquals(children.nextElement(), a); assertEquals(children.nextElement(), b); assertEquals(children.nextElement(), c); assertEquals(children.nextElement(), d); assertFalse(children.hasMoreElements()); } @Test public void testAllowsChildren() { DefaultMutableTreeTableNode empty = new DefaultMutableTreeTableNode(); assertTrue(empty.getAllowsChildren()); empty.setAllowsChildren(!empty.getAllowsChildren()); assertFalse(empty.getAllowsChildren()); empty.setAllowsChildren(!empty.getAllowsChildren()); assertTrue(empty.getAllowsChildren()); DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode("root"); assertTrue(root.getAllowsChildren()); root.setAllowsChildren(!root.getAllowsChildren()); assertFalse(root.getAllowsChildren()); root.setAllowsChildren(!root.getAllowsChildren()); assertTrue(root.getAllowsChildren()); DefaultMutableTreeTableNode a = new DefaultMutableTreeTableNode("a", true); assertTrue(a.getAllowsChildren()); a.setAllowsChildren(!a.getAllowsChildren()); assertFalse(a.getAllowsChildren()); a.setAllowsChildren(!a.getAllowsChildren()); assertTrue(a.getAllowsChildren()); DefaultMutableTreeTableNode b = new DefaultMutableTreeTableNode("b", false); assertFalse(b.getAllowsChildren()); b.setAllowsChildren(!b.getAllowsChildren()); assertTrue(b.getAllowsChildren()); b.setAllowsChildren(!b.getAllowsChildren()); assertFalse(b.getAllowsChildren()); } @Test public void testGetChildAt() { DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode("root"); try { root.getChildAt(-1); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { //do nothing } try { root.getChildAt(root.getChildCount()); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { //do nothing } DefaultMutableTreeTableNode a = new DefaultMutableTreeTableNode("a"); DefaultMutableTreeTableNode b = new DefaultMutableTreeTableNode("b"); DefaultMutableTreeTableNode c = new DefaultMutableTreeTableNode("c"); DefaultMutableTreeTableNode d = new DefaultMutableTreeTableNode("d"); root.add(a); root.add(b); root.add(c); root.add(d); assertEquals(root.getChildAt(0), a); assertEquals(root.getChildAt(1), b); assertEquals(root.getChildAt(2), c); assertEquals(root.getChildAt(3), d); try { root.getChildAt(root.getChildCount()); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { //do nothing } } @Test public void testGetChildCount() { DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode("root"); assertEquals(root.getChildCount(), 0); DefaultMutableTreeTableNode a = new DefaultMutableTreeTableNode("a"); root.add(a); assertEquals(root.getChildCount(), 1); DefaultMutableTreeTableNode b = new DefaultMutableTreeTableNode("b"); root.add(b); assertEquals(root.getChildCount(), 2); DefaultMutableTreeTableNode c = new DefaultMutableTreeTableNode("c"); root.add(c); assertEquals(root.getChildCount(), 3); DefaultMutableTreeTableNode d = new DefaultMutableTreeTableNode("d"); root.add(d); assertEquals(root.getChildCount(), 4); root.remove(a); assertEquals(root.getChildCount(), 3); root.remove(b); assertEquals(root.getChildCount(), 2); root.remove(c); assertEquals(root.getChildCount(), 1); root.remove(d); assertEquals(root.getChildCount(), 0); } @Test public void testGetIndex() { DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode("root"); assertEquals(root.getIndex(null), -1); assertEquals(root.getIndex(new DefaultMutableTreeNode()), -1); assertEquals(root.getIndex(new DefaultMutableTreeTableNode()), -1); DefaultMutableTreeTableNode a = new DefaultMutableTreeTableNode("a"); root.add(a); assertEquals(root.getIndex(a), 0); DefaultMutableTreeTableNode b = new DefaultMutableTreeTableNode("b"); root.add(b); assertEquals(root.getIndex(b), 1); DefaultMutableTreeTableNode c = new DefaultMutableTreeTableNode("c"); root.add(c); assertEquals(root.getIndex(c), 2); DefaultMutableTreeTableNode d = new DefaultMutableTreeTableNode("d"); root.add(d); assertEquals(root.getIndex(d), 3); } @Test public void testGetParent() { DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode("root"); assertNull(root.getParent()); DefaultMutableTreeTableNode a = new DefaultMutableTreeTableNode("a"); a.setParent(root); assertEquals(a.getParent(), root); assertEquals(root.getChildAt(0), a); DefaultMutableTreeTableNode b = new DefaultMutableTreeTableNode("b"); b.setParent(root); assertEquals(b.getParent(), root); assertEquals(root.getChildAt(1), b); DefaultMutableTreeTableNode c = new DefaultMutableTreeTableNode("c"); c.setParent(root); assertEquals(c.getParent(), root); assertEquals(root.getChildAt(2), c); DefaultMutableTreeTableNode d = new DefaultMutableTreeTableNode("d"); d.setParent(root); assertEquals(d.getParent(), root); assertEquals(root.getChildAt(3), d); a.setParent(d); assertEquals(root.getChildCount(), 3); assertEquals(a.getParent(), d); assertEquals(d.getChildAt(0), a); b.setAllowsChildren(false); try { c.setParent(b); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { //do nothing } assertEquals(c.getParent(), root); assertEquals(b.getChildCount(), 0); } @Test public void testSetParent() { DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode("root"); DefaultMutableTreeTableNode a = new DefaultMutableTreeTableNode("a"); root.add(a); assertEquals(root.getChildCount(), 1); a.setParent(null); assertEquals(root.getChildCount(), 0); a.setParent(root); assertEquals(root.getChildCount(), 1); a.setParent(null); assertEquals(root.getChildCount(), 0); root.setAllowsChildren(false); try { a.setParent(root); fail("should throw IllegalArgumentException"); } catch (IllegalArgumentException e) { //success } } @Test public void testUserObject() { DefaultMutableTreeTableNode empty = new DefaultMutableTreeTableNode(); assertNull(empty.getUserObject()); empty.setUserObject("root"); assertEquals(empty.getUserObject(), "root"); DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode("root"); assertEquals(root.getUserObject(), "root"); // root.setAllowsChildren(!root.getAllowsChildren()); // assertFalse(root.getAllowsChildren()); // root.setAllowsChildren(!root.getAllowsChildren()); // assertTrue(root.getAllowsChildren()); // // DefaultMutableTreeTableNode a = new DefaultMutableTreeTableNode("a", true); // assertTrue(a.getAllowsChildren()); // a.setAllowsChildren(!a.getAllowsChildren()); // assertFalse(a.getAllowsChildren()); // a.setAllowsChildren(!a.getAllowsChildren()); // assertTrue(a.getAllowsChildren()); // // DefaultMutableTreeTableNode b = new DefaultMutableTreeTableNode("b", false); // assertFalse(b.getAllowsChildren()); // b.setAllowsChildren(!b.getAllowsChildren()); // assertTrue(b.getAllowsChildren()); // b.setAllowsChildren(!b.getAllowsChildren()); // assertFalse(b.getAllowsChildren()); } } swingx-1.0-src/src/test/org/jdesktop/swingx/event/0000755000175000017500000000000011210401734021033 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/event/CompoundFocusListenerIssues.java0000644000175000017500000000463111210401722027365 0ustar tonytony/* * Created on 23.04.2009 * */ package org.jdesktop.swingx.event; import java.awt.Component; import java.awt.DefaultKeyboardFocusManager; import java.awt.GraphicsEnvironment; import java.awt.KeyboardFocusManager; import java.lang.reflect.InvocationTargetException; import java.util.logging.Logger; import javax.swing.SwingUtilities; import org.jdesktop.swingx.JXDatePicker; import org.jdesktop.swingx.SwingXUtilities; import org.jdesktop.test.PropertyChangeReport; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class CompoundFocusListenerIssues extends CompoundFocusListenerTest { @SuppressWarnings("unused") private static final Logger LOG = Logger .getLogger(CompoundFocusListenerIssues.class.getName()); /** * Test that listener copes with change of keyboardFocusManager. * * Not yet implemented. * * @throws InterruptedException * @throws InvocationTargetException */ @Test public void testKeyboardFocusManager() throws InterruptedException, InvocationTargetException { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } JXDatePicker picker = getRealizedDatePicker(); final KeyboardFocusManager oldManager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); Component focusOwner = oldManager.getPermanentFocusOwner(); assertFalse("sanity: initial focus must not be in picker", SwingXUtilities.isDescendingFrom(focusOwner, picker)); CompoundFocusListener l = new CompoundFocusListener(picker); final PropertyChangeReport report = new PropertyChangeReport(); l.addPropertyChangeListener(report); KeyboardFocusManager customManager = new DefaultKeyboardFocusManager(); KeyboardFocusManager.setCurrentKeyboardFocusManager(customManager); LOG.info("after custom? "); picker.requestFocusInWindow(); SwingUtilities.invokeAndWait(new Runnable() { public void run() { try { assertEquals(1, report.getEventCount("focused")); } finally { KeyboardFocusManager.setCurrentKeyboardFocusManager(oldManager); } } }); } } swingx-1.0-src/src/test/org/jdesktop/swingx/event/WeakEventListenerListTest.java0000644000175000017500000001150711210401722026772 0ustar tonytony/* * $Id: WeakEventListenerListTest.java,v 1.2 2008/10/11 20:42:31 rah003 Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.event; import javax.swing.event.ChangeListener; import junit.framework.TestCase; import org.jdesktop.test.ChangeReport; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * Unit tests for SwingX' EventListenerList. Testing the * mechanics of mutations and returned listener arrays.

* * PENDING: any way to unit test memory leaks? * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class WeakEventListenerListTest extends TestCase { /** * Test intial getListenerList * */ @Test public void testGetListenerListInitial() { WeakEventListenerList list = new WeakEventListenerList(); // must return empty array assertNotNull("array must be not null", list.getListenerList()); assertEquals("array must be empty", 0, list.getListenerList().length); } /** * test sequence in array. * */ @Test public void testGetListenerListAddRemove() { WeakEventListenerList list = new WeakEventListenerList(); // add one changeListener ChangeReport changeReport = new ChangeReport(); list.add(ChangeListener.class, changeReport); Object[] array = list.getListenerList(); assertEquals("array must have 2 elements", 2, array.length); assertSame("listener class must be at 0", ChangeListener.class, array[0]); assertSame("added listener must be at 1", changeReport, array[1]); // add a second ChangeReport otherReport = new ChangeReport(); list.add(ChangeListener.class, otherReport); Object[] otherArray = list.getListenerList(); assertEquals("array must have 4 elements", 4, otherArray.length); assertSame(ChangeListener.class, otherArray[0]); assertSame(changeReport, otherArray[1]); assertSame(ChangeListener.class, otherArray[2]); assertSame(otherReport, otherArray[3]); list.remove(ChangeListener.class, changeReport); Object[] removedArray = list.getListenerList(); assertEquals("array must have 2 elements", 2, removedArray.length); assertSame("listener class must be at 0", ChangeListener.class, removedArray[0]); assertSame("added listener must be at 1", otherReport, removedArray[1]); } @Test public void testGetListenersInitial() { WeakEventListenerList list = new WeakEventListenerList(); // must return empty array assertNotNull("array must be not null", list.getListeners(ChangeListener.class)); assertEquals("array must be empty", 0, list.getListeners(ChangeListener.class).length); } /** * test sequence in array. * */ @Test public void testGetListenersAddRemove() { WeakEventListenerList list = new WeakEventListenerList(); // add one changeListener ChangeReport changeReport = new ChangeReport(); list.add(ChangeListener.class, changeReport); ChangeListener[] array = list.getListeners(ChangeListener.class); assertEquals("array must have 2 elements", 1, array.length); assertSame("added listener must be at 0", changeReport, array[0]); // add a second ChangeReport otherReport = new ChangeReport(); list.add(ChangeListener.class, otherReport); ChangeListener[] otherArray = list.getListeners(ChangeListener.class); assertEquals("array must have 2 elements", 2, otherArray.length); assertSame(changeReport, otherArray[0]); assertSame(otherReport, otherArray[1]); list.remove(ChangeListener.class, changeReport); ChangeListener[] removedArray = list.getListeners(ChangeListener.class); assertEquals("array length", 1, removedArray.length); assertSame("last added listener must be at 0", otherReport, removedArray[0]); } } swingx-1.0-src/src/test/org/jdesktop/swingx/event/CompoundFocusListenerTest.java0000644000175000017500000001720611210401722027033 0ustar tonytony/* * Created on 23.04.2009 * */ package org.jdesktop.swingx.event; import java.awt.Component; import java.awt.GraphicsEnvironment; import java.awt.KeyboardFocusManager; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.reflect.InvocationTargetException; import java.util.Date; import java.util.logging.Logger; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.border.TitledBorder; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXDatePicker; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXPanel; import org.jdesktop.swingx.SwingXUtilities; import org.jdesktop.test.PropertyChangeReport; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class CompoundFocusListenerTest extends InteractiveTestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger .getLogger(CompoundFocusListenerTest.class.getName()); public static void main(String[] args) { CompoundFocusListenerTest test = new CompoundFocusListenerTest(); // KEEP this is global state - uncomment for debug painting completely // UIManager.put(CalendarHeaderHandler.uiControllerID, "org.jdesktop.swingx.plaf.basic.SpinningCalendarHeaderHandler"); // UIManager.put(SpinningCalendarHeaderHandler.FOCUSABLE_SPINNER_TEXT, Boolean.TRUE); // UIManager.put("JXDatePicker.forceZoomable", Boolean.TRUE); try { test.runInteractiveTests(); } catch (Exception e) { e.printStackTrace(); } } public void interactiveCompoundFocusedProperty() { JXPanel panel = new JXPanel(); panel.setName("plain-panel"); // add some components inside panel.add(new JTextField("something to .... focus")); JXDatePicker picker = new JXDatePicker(new Date()); picker.setName("picker"); panel.add(picker); JComboBox combo = new JComboBox(new Object[] {"dooooooooo", 1, 2, 3, 4 }); combo.setEditable(true); panel.add(new JButton("something else to ... focus")); panel.add(combo); panel.setBorder(new TitledBorder("has focus dispatcher")); // register the compound dispatcher CompoundFocusListener focusDispatcher = new CompoundFocusListener(picker); PropertyChangeListener l = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { LOG.info("focused on picker " + evt.getNewValue()); }}; focusDispatcher.addPropertyChangeListener(l); JComponent box = Box.createVerticalBox(); box.add(panel); showInFrame(box, "CompoundFocusListener (on datePicker)"); } @Test(expected = NullPointerException.class) public void testNullRoot() { new CompoundFocusListener(null); } @Test public void testFocusedInitialFalse() { JComboBox field = new JComboBox(); field.setEditable(true); assertFalse("sanity: combo not focused", field.hasFocus()); CompoundFocusListener l = new CompoundFocusListener(field); assertEquals(field.hasFocus(), l.isFocused()); } @Test public void testFocusedInitialTrue() throws InterruptedException, InvocationTargetException { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } final JXDatePicker picker = getRealizedDatePicker(); picker.requestFocusInWindow(); SwingUtilities.invokeAndWait(new Runnable() { public void run() { Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner(); assertTrue("sanity: focus transfered into picker hierarchy", SwingXUtilities.isDescendingFrom(focusOwner, picker)); CompoundFocusListener l = new CompoundFocusListener(picker); assertTrue("listener must take initial focused state ", l.isFocused()); } }); } @Test public void testReleaseRemovesListeners() { CompoundFocusListener l = new CompoundFocusListener(new JXDatePicker()); final PropertyChangeReport report = new PropertyChangeReport(); l.addPropertyChangeListener(report); l.release(); assertRemoved(report, l.getPropertyChangeListeners()); } private void assertRemoved(PropertyChangeReport report, PropertyChangeListener[] propertyChangeListeners) { for (PropertyChangeListener l : propertyChangeListeners) { assertNotSame("property change listener must have been removed", report, l); } } /** * Test no property change fired after release. * * @throws InterruptedException * @throws InvocationTargetException */ @Test public void testRelease() throws InterruptedException, InvocationTargetException { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } JXDatePicker picker = getRealizedDatePicker(); Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner(); assertFalse("sanity: initial focus must not be in picker", SwingXUtilities.isDescendingFrom(focusOwner, picker)); CompoundFocusListener l = new CompoundFocusListener(picker); final PropertyChangeReport report = new PropertyChangeReport(); l.addPropertyChangeListener(report); l.release(); picker.requestFocusInWindow(); SwingUtilities.invokeAndWait(new Runnable() { public void run() { assertEquals(0, report.getEventCount("focused")); } }); } /** * Test property change fired on focusGained. * * @throws InterruptedException * @throws InvocationTargetException */ @Test public void testFireFocusedProperty() throws InterruptedException, InvocationTargetException { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } JXDatePicker picker = getRealizedDatePicker(); Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner(); assertFalse("sanity: initial focus must not be in picker", SwingXUtilities.isDescendingFrom(focusOwner, picker)); CompoundFocusListener l = new CompoundFocusListener(picker); final PropertyChangeReport report = new PropertyChangeReport(); l.addPropertyChangeListener(report); picker.requestFocusInWindow(); SwingUtilities.invokeAndWait(new Runnable() { public void run() { assertEquals(1, report.getEventCount("focused")); } }); } /** * @return */ protected JXDatePicker getRealizedDatePicker() { JXFrame frame = new JXFrame(); final JXDatePicker picker = new JXDatePicker(); frame.add(new JTextField(10)); frame.add(picker); frame.add(new JTextField(10)); frame.pack(); frame.setVisible(true); return picker; } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXTreeTableIssues.java0000644000175000017500000013557011210401722024072 0ustar tonytony/* * $Id: JXTreeTableIssues.java,v 1.80 2009/03/11 10:50:50 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.Color; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.InvocationTargetException; import java.util.Vector; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.event.TableModelEvent; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreePath; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.HighlighterFactory; import org.jdesktop.swingx.hyperlink.AbstractHyperlinkAction; import org.jdesktop.swingx.renderer.CellContext; import org.jdesktop.swingx.renderer.CheckBoxProvider; import org.jdesktop.swingx.renderer.ComponentProvider; import org.jdesktop.swingx.renderer.DefaultTableRenderer; import org.jdesktop.swingx.renderer.DefaultTreeRenderer; import org.jdesktop.swingx.renderer.HyperlinkProvider; import org.jdesktop.swingx.renderer.LabelProvider; import org.jdesktop.swingx.renderer.StringValue; import org.jdesktop.swingx.renderer.StringValues; import org.jdesktop.swingx.renderer.WrappingIconPanel; import org.jdesktop.swingx.renderer.WrappingProvider; import org.jdesktop.swingx.renderer.RendererVisualCheck.TextAreaProvider; import org.jdesktop.swingx.test.ActionMapTreeTableModel; import org.jdesktop.swingx.test.ComponentTreeTableModel; import org.jdesktop.swingx.test.TreeTableUtils; import org.jdesktop.swingx.treetable.AbstractMutableTreeTableNode; import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; import org.jdesktop.swingx.treetable.DefaultTreeTableModel; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.swingx.treetable.MutableTreeTableNode; import org.jdesktop.swingx.treetable.TreeTableModel; import org.jdesktop.swingx.treetable.TreeTableNode; import org.jdesktop.test.AncientSwingTeam; import org.jdesktop.test.TableModelReport; /** * Test to exposed known issues of JXTreeTable.

* * Ideally, there would be at least one failing test method per open * issue in the issue tracker. Plus additional failing test methods for * not fully specified or not yet decided upon features/behaviour.

* * Once the issues are fixed and the corresponding methods are passing, they * should be moved over to the XXTest. * * @author Jeanette Winzenburg */ public class JXTreeTableIssues extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(JXTreeTableIssues.class .getName()); public static void main(String[] args) { setSystemLF(true); JXTreeTableIssues test = new JXTreeTableIssues(); try { // test.runInteractiveTests(); // test.runInteractiveTests(".*ColumnSelection.*"); // test.runInteractiveTests(".*Text.*"); // test.runInteractiveTests(".*TreeExpand.*"); test.runInteractiveTests("interactive.*Cancel.*"); // test.runInteractiveTests("interactive.*CustomColor.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #875-swingx: cell selection incorrect in hierarchical column. * */ public void interactiveColumnSelection() { JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()); treeTable.setColumnSelectionAllowed(true); JXTable table = new JXTable(new AncientSwingTeam()); table.setColumnSelectionAllowed(true); JXFrame frame = wrapWithScrollingInFrame(treeTable, table, "columnSelection in treetable"); show(frame); } /** * Custom renderer colors of Swingx DefaultTreeRenderer not respected. * (same in J/X/Tree). * * A bit surprising - probably due to the half-hearted support (backward * compatibility) of per-provider colors: they are set by the glueing * renderer to the provider's default visuals. Which is useless if the * provider is a wrapping provider - the wrappee's default visuals are unchanged. * * PENDING JW: think about complete removal. Client code should move over * completely to highlighter/renderer separation anyway. * * */ public void interactiveXRendererCustomColor() { JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()); treeTable.addHighlighter(HighlighterFactory.createSimpleStriping()); DefaultTreeRenderer swingx = new DefaultTreeRenderer(); // in a treetable this has no effect: treetable.applyRenderer // internally resets them to the same colors as tree itself // (configured by the table's highlighters swingx.setBackground(Color.YELLOW); treeTable.setTreeCellRenderer(swingx); JTree tree = new JXTree(treeTable.getTreeTableModel()); DefaultTreeRenderer other = new DefaultTreeRenderer(); other.setBackground(Color.YELLOW); // other.setBackgroundSelectionColor(Color.RED); tree.setCellRenderer(other); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "swingx renderers - highlight complete cell"); frame.setVisible(true); } /** * Custom renderer colors of core DefaultTreeCellRenderer not respected. * This is intentional: treeTable's highlighters must rule, so the * renderer colors are used to force the treecellrenderer to use the * correct values. */ public void interactiveCoreRendererCustomColor() { JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()); treeTable.addHighlighter(HighlighterFactory.createSimpleStriping()); DefaultTreeCellRenderer legacy = createBackgroundTreeRenderer(); // in a treetable this has no effect: treetable.applyRenderer // internally resets them to the same colors as tree itself // (configured by the table's highlighters legacy.setBackgroundNonSelectionColor(Color.YELLOW); legacy.setBackgroundSelectionColor(Color.RED); treeTable.setTreeCellRenderer(legacy); JTree tree = new JXTree(treeTable.getTreeTableModel()); DefaultTreeCellRenderer other = createBackgroundTreeRenderer(); other.setBackgroundNonSelectionColor(Color.YELLOW); other.setBackgroundSelectionColor(Color.RED); tree.setCellRenderer(other); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "legacy renderers - highlight complete cell"); frame.setVisible(true); } private DefaultTreeCellRenderer createBackgroundTreeRenderer() { DefaultTreeCellRenderer legacy = new DefaultTreeCellRenderer() { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component comp = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); if (sel) { comp.setBackground(getBackgroundSelectionColor()); } else { comp.setBackground(getBackgroundNonSelectionColor()); } return comp; } }; return legacy; } /** * Issue #493-swingx: incorrect table events fired. * Issue #592-swingx: (no structureChanged table events) is a special * case of the former. * * Here: add support to prevent a structureChanged even when setting * the root. May be required if the columns are stable and the * model lazily loaded. Quick hack would be to add a clientProperty? * * @throws InvocationTargetException * @throws InterruptedException */ public void testTableEventOnSetRootNoStructureChange() throws InterruptedException, InvocationTargetException { TreeTableModel model = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(model); table.setRootVisible(true); table.expandAll(); final TableModelReport report = new TableModelReport(); table.getModel().addTableModelListener(report); ((DefaultTreeTableModel) model).setRoot(new DefaultMutableTreeTableNode("other")); SwingUtilities.invokeAndWait(new Runnable() { public void run() { assertEquals("tableModel must have fired", 1, report.getEventCount()); assertTrue("event type must be dataChanged " + TableModelReport.printEvent(report.getLastEvent()), report.isDataChanged(report.getLastEvent())); } }); } /** * Issue #576-swingx: sluggish scrolling (?). * Here - use default model */ public void interactiveScrollAlternateHighlightDefaultModel() { final JXTable table = new JXTable(0, 6); DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode("root"); for (int i = 0; i < 5000; i++) { root.insert(new DefaultMutableTreeTableNode(i), i); } final JXTreeTable treeTable = new JXTreeTable(new DefaultTreeTableModel(root)); treeTable.expandAll(); table.setModel(treeTable.getModel()); final Highlighter hl = HighlighterFactory.createAlternateStriping(UIManager.getColor("Panel.background"), Color.WHITE); treeTable.setHighlighters(hl); table.setHighlighters(hl); final JXFrame frame = wrapWithScrollingInFrame(treeTable, table, "sluggish scrolling"); Action toggleHighlighter = new AbstractActionExt("toggle highlighter") { public void actionPerformed(ActionEvent e) { if (treeTable.getHighlighters().length == 0) { treeTable.addHighlighter(hl); table.addHighlighter(hl); } else { treeTable.removeHighlighter(hl); table.removeHighlighter(hl); } } }; Action scroll = new AbstractActionExt("start scroll") { public void actionPerformed(ActionEvent e) { for (int i = 0; i < table.getRowCount(); i++) { table.scrollRowToVisible(i); treeTable.scrollRowToVisible(i); } } }; addAction(frame, toggleHighlighter); addAction(frame, scroll); frame.setVisible(true); } /** * Issue #576-swingx: sluggish scrolling (?) * * Here: use FileSystemModel */ public void interactiveScrollAlternateHighlight() { final JXTable table = new JXTable(0, 6); final JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()); final Highlighter hl = HighlighterFactory.createAlternateStriping(UIManager.getColor("Panel.background"), Color.WHITE); treeTable.setHighlighters(hl); table.setHighlighters(hl); final JXFrame frame = wrapWithScrollingInFrame(treeTable, table, "sluggish scrolling"); Action expand = new AbstractActionExt("start expand") { public void actionPerformed(ActionEvent e) { for (int i = 0; i < 5000; i++) { treeTable.expandRow(i); } table.setModel(treeTable.getModel()); } }; Action toggleHighlighter = new AbstractActionExt("toggle highlighter") { public void actionPerformed(ActionEvent e) { if (treeTable.getHighlighters().length == 0) { treeTable.addHighlighter(hl); table.addHighlighter(hl); } else { treeTable.removeHighlighter(hl); table.removeHighlighter(hl); } } }; Action scroll = new AbstractActionExt("start scroll") { public void actionPerformed(ActionEvent e) { for (int i = 0; i < table.getRowCount(); i++) { table.scrollRowToVisible(i); treeTable.scrollRowToVisible(i); } } }; addAction(frame, expand); addAction(frame, toggleHighlighter); addAction(frame, scroll); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing update. * * Test update events after updating table. * * from tiberiu@dev.java.net * * @throws InvocationTargetException * @throws InterruptedException */ public void testTableEventUpdateOnTreeTableSetValueForRoot() throws InterruptedException, InvocationTargetException { TreeTableModel model = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(model); table.setRootVisible(true); table.expandAll(); final int row = 0; // sanity assertEquals("JTree", table.getValueAt(row, 0).toString()); assertTrue("root must be editable", table.getModel().isCellEditable(0, 0)); final TableModelReport report = new TableModelReport(); table.getModel().addTableModelListener(report); // doesn't fire or isn't detectable? // Problem was: model was not-editable. table.setValueAt("games", row, 0); SwingUtilities.invokeAndWait(new Runnable() { public void run() { assertEquals("tableModel must have fired", 1, report.getEventCount()); assertEquals("the event type must be update " + TableModelReport.printEvent(report.getLastEvent()) , 1, report.getUpdateEventCount()); TableModelEvent event = report.getLastUpdateEvent(); assertEquals("the updated row ", row, event.getFirstRow()); } }); } // -------------- interactive tests /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing update on a recursive delete on a parent node. * * By recursive delete on a parent node it is understood that first we * remove its children and then the parent node. After each child removed * we are making an update over the parent. During this update the problem * occurs: the index row for the parent is -1 and hence it is made an update * over the row -1 (the header) and as it can be seen the preffered widths * of column header are not respected anymore and are restored to the default * preferences (all equal). * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterDeleteUpdate() { final DefaultTreeTableModel customTreeTableModel = (DefaultTreeTableModel) createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); table.getColumn("A").setPreferredWidth(100); table.getColumn("A").setMinWidth(100); table.getColumn("A").setMaxWidth(100); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing update on recursive delete"); final MutableTreeTableNode deletedNode = (MutableTreeTableNode) table.getPathForRow(6).getLastPathComponent(); MutableTreeTableNode child1 = (MutableTreeTableNode) table.getPathForRow(6+1).getLastPathComponent(); MutableTreeTableNode child2 = (MutableTreeTableNode) table.getPathForRow(6+2).getLastPathComponent(); MutableTreeTableNode child3 = (MutableTreeTableNode) table.getPathForRow(6+3).getLastPathComponent(); MutableTreeTableNode child4 = (MutableTreeTableNode) table.getPathForRow(6+4).getLastPathComponent(); final MutableTreeTableNode[] children = {child1, child2, child3, child4 }; final String[] values = {"v1", "v2", "v3", "v4"}; final ActionListener l = new ActionListener() { int count = 0; public void actionPerformed(ActionEvent e) { if (count > values.length) return; if (count == values.length) { customTreeTableModel.removeNodeFromParent(deletedNode); count++; } else { // one in each run removeChild(customTreeTableModel, deletedNode, children, values); count++; // all in one // for (int i = 0; i < values.length; i++) { // removeChild(customTreeTableModel, deletedNode, children, values); // count++; // } } } /** * @param customTreeTableModel * @param deletedNode * @param children * @param values */ private void removeChild(final DefaultTreeTableModel customTreeTableModel, final MutableTreeTableNode deletedNode, final MutableTreeTableNode[] children, final String[] values) { customTreeTableModel.removeNodeFromParent(children[count]); customTreeTableModel.setValueAt(values[count], deletedNode, 0); } }; Action changeValue = new AbstractAction("delete node sports recursively") { Timer timer; public void actionPerformed(ActionEvent e) { if (timer == null) { timer = new Timer(10, l); timer.start(); } else { timer.stop(); setEnabled(false); } } }; addAction(frame, changeValue); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing update. Use the second child of root - first is accidentally okay. * * from tiberiu@dev.java.net * * TODO DefaultMutableTreeTableNodes do not allow value changes, so this * test will never work */ public void interactiveTreeTableModelAdapterUpdate() { TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); table.setLargeModel(true); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing update"); Action changeValue = new AbstractAction("change sports to games") { public void actionPerformed(ActionEvent e) { String newValue = "games"; table.getTreeTableModel().setValueAt(newValue, table.getPathForRow(6).getLastPathComponent(), 0); } }; addAction(frame, changeValue); Action changeRoot = new AbstractAction("change root") { public void actionPerformed(ActionEvent e) { DefaultMutableTreeTableNode newRoot = new DefaultMutableTreeTableNode("new Root"); ((DefaultTreeTableModel) table.getTreeTableModel()).setRoot(newRoot); } }; addAction(frame, changeRoot); frame.pack(); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing delete. * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterDelete() { final TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing update"); Action changeValue = new AbstractAction("delete first child of sports") { public void actionPerformed(ActionEvent e) { MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(6 +1).getLastPathComponent(); ((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(firstChild); } }; addAction(frame, changeValue); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing delete. * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterMutateSelected() { final TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing delete expanded folder"); Action changeValue = new AbstractAction("delete selected node") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent(); ((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(firstChild); } }; addAction(frame, changeValue); Action changeValue1 = new AbstractAction("insert as first child of selected node") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent(); MutableTreeTableNode newChild = new DefaultMutableTreeTableNode("inserted"); ((DefaultTreeTableModel) customTreeTableModel) .insertNodeInto(newChild, firstChild, 0); } }; addAction(frame, changeValue1); frame.pack(); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing delete. * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterMutateSelectedDiscontinous() { final TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing delete expanded folder"); Action changeValue = new AbstractAction("delete selected node + sibling") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent(); MutableTreeTableNode parent = (MutableTreeTableNode) firstChild.getParent(); MutableTreeTableNode secondNextSibling = null; int firstIndex = parent.getIndex(firstChild); if (firstIndex + 2 < parent.getChildCount()) { secondNextSibling = (MutableTreeTableNode) parent.getChildAt(firstIndex + 2); } if (secondNextSibling != null) { ((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(secondNextSibling); } ((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(firstChild); } }; addAction(frame, changeValue); Action changeValue1 = new AbstractAction("insert as first child of selected node") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent(); MutableTreeTableNode newChild = new DefaultMutableTreeTableNode("inserted"); ((DefaultTreeTableModel) customTreeTableModel) .insertNodeInto(newChild, firstChild, 0); } }; addAction(frame, changeValue1); frame.pack(); frame.setVisible(true); } /** * Creates and returns a custom model from JXTree default model. The model * is of type DefaultTreeModel, allowing for easy insert/remove. * * @return */ private TreeTableModel createCustomTreeTableModelFromDefault() { JXTree tree = new JXTree(); DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel(); TreeTableModel customTreeTableModel = TreeTableUtils .convertDefaultTreeModel(treeModel); return customTreeTableModel; } /** * A TreeTableModel inheriting from DefaultTreeModel (to ease * insert/delete). */ public static class CustomTreeTableModel extends DefaultTreeTableModel { /** * @param root */ public CustomTreeTableModel(TreeTableNode root) { super(root); } @Override public int getColumnCount() { return 1; } @Override public String getColumnName(int column) { return "User Object"; } @Override public Object getValueAt(Object node, int column) { return ((DefaultMutableTreeNode) node).getUserObject(); } @Override public boolean isCellEditable(Object node, int column) { return true; } @Override public void setValueAt(Object value, Object node, int column) { ((MutableTreeTableNode) node).setUserObject(value); modelSupport.firePathChanged(new TreePath(getPathToRoot((TreeTableNode) node))); } } /** * Issue #??-swingx: hyperlink in JXTreeTable hierarchical column not * active. * */ public void interactiveTreeTableLinkRendererSimpleText() { AbstractHyperlinkAction simpleAction = new AbstractHyperlinkAction(null) { public void actionPerformed(ActionEvent e) { LOG.info("hit: " + getTarget()); } }; JXTreeTable tree = new JXTreeTable(new FileSystemModel()); HyperlinkProvider provider = new HyperlinkProvider(simpleAction); tree.getColumn(2).setCellRenderer(new DefaultTableRenderer(provider)); tree.setTreeCellRenderer(new DefaultTreeRenderer( //provider)); new WrappingProvider(provider))); // tree.setCellRenderer(new LinkRenderer(simpleAction)); tree.setHighlighters(HighlighterFactory.createSimpleStriping()); JFrame frame = wrapWithScrollingInFrame(tree, "table and simple links"); frame.setVisible(true); } /** * Issue ??-swingx: hyperlink/rollover in hierarchical column. * */ public void testTreeRendererInitialRollover() { JXTreeTable tree = new JXTreeTable(new FileSystemModel()); assertEquals(tree.isRolloverEnabled(), ((JXTree) tree.getCellRenderer(0, 0)).isRolloverEnabled()); } /** * Issue ??-swingx: hyperlink/rollover in hierarchical column. * */ public void testTreeRendererModifiedRollover() { JXTreeTable tree = new JXTreeTable(new FileSystemModel()); tree.setRolloverEnabled(!tree.isRolloverEnabled()); assertEquals(tree.isRolloverEnabled(), ((JXTree) tree.getCellRenderer(0, 0)).isRolloverEnabled()); } /** * example how to use a custom component as * renderer in tree column of TreeTable. * */ public void interactiveTreeTableCustomRenderer() { JXTreeTable tree = new JXTreeTable(new FileSystemModel()); StringValue sv = new StringValue( ){ public String getString(Object value) { return "..." + StringValues.TO_STRING.getString(value); } }; ComponentProvider provider = new CheckBoxProvider(sv); // /** // * custom tooltip: show row. Note: the context is that // * of the rendering tree. No way to get at table state? // */ // @Override // protected void configureState(CellContext context) { // super.configureState(context); // rendererComponent.setToolTipText("Row: " + context.getRow()); // } // // }; tree.setTreeCellRenderer(new DefaultTreeRenderer(provider)); tree.setHighlighters(HighlighterFactory.createSimpleStriping()); JFrame frame = wrapWithScrollingInFrame(tree, "treetable and custom renderer"); frame.setVisible(true); } /** * Quick example to use a TextArea in the hierarchical column * of a treeTable. Not really working .. the wrap is not reliable?. * */ public void interactiveTextAreaTreeTable() { TreeTableModel model = createTreeTableModelWithLongNode(); JXTreeTable treeTable = new JXTreeTable(model); treeTable.setVisibleRowCount(5); treeTable.setRowHeight(50); treeTable.getColumnExt(0).setPreferredWidth(200); TreeCellRenderer renderer = new DefaultTreeRenderer( new WrappingProvider(new TextAreaProvider())); treeTable.setTreeCellRenderer(renderer); showWithScrollingInFrame(treeTable, "TreeTable with text wrapping"); } /** * @return */ private TreeTableModel createTreeTableModelWithLongNode() { MutableTreeTableNode root = createLongNode("some really, maybe really really long text - " + "wrappit .... where needed "); root.insert(createLongNode("another really, maybe really really long text - " + "with nothing but junk. wrappit .... where needed"), 0); root.insert(createLongNode("another really, maybe really really long text - " + "with nothing but junk. wrappit .... where needed"), 0); MutableTreeTableNode node = createLongNode("some really, maybe really really long text - " + "wrappit .... where needed "); node.insert(createLongNode("another really, maybe really really long text - " + "with nothing but junk. wrappit .... where needed"), 0); root.insert(node, 0); root.insert(createLongNode("another really, maybe really really long text - " + "with nothing but junk. wrappit .... where needed"), 0); Vector ids = new Vector(); ids.add("long text"); ids.add("dummy"); return new DefaultTreeTableModel(root, ids); } /** * @param string * @return */ private MutableTreeTableNode createLongNode(final String string) { AbstractMutableTreeTableNode node = new AbstractMutableTreeTableNode() { Object rnd = Math.random(); public int getColumnCount() { return 2; } public Object getValueAt(int column) { if (column == 0) { return string; } return rnd; } }; node.setUserObject(string); return node; } /** * Experiments to try and understand clipping issues: occasionally, the text * in the tree column is clipped even if there is enough space available. * * To visualize the rendering component's size we use a WrappingIconProvider * which sets a red border. * * Calling packxx might pose a problem: for non-large models the node size * is cached. In this case, packing before replacing the renderer will lead * to incorrect sizes which are hard to invalidate (no way except faking a * structural tree event? temporaryly set large model and back, plus repaint * works). * */ public void interactiveTreeTableClipIssueWrappingProvider() { final JXTreeTable treeTable = new JXTreeTable(createActionTreeModel()); treeTable.setHorizontalScrollEnabled(true); treeTable.setColumnControlVisible(true); // BEWARE: do not pack before setting the renderer treeTable.packColumn(0, -1); StringValue format = new StringValue() { public String getString(Object value) { if (value instanceof Action) { return ((Action) value).getValue(Action.NAME) + "xx"; } return StringValues.TO_STRING.getString(value); } }; ComponentProvider tableProvider = new LabelProvider(format); WrappingProvider wrappingProvider = new WrappingProvider(tableProvider) { Border redBorder = BorderFactory.createLineBorder(Color.RED); @Override public WrappingIconPanel getRendererComponent(CellContext context) { super.getRendererComponent(context); rendererComponent.setBorder(redBorder); return rendererComponent; } }; DefaultTreeRenderer treeCellRenderer = new DefaultTreeRenderer( wrappingProvider); treeTable.setTreeCellRenderer(treeCellRenderer); treeTable.setHighlighters(HighlighterFactory.createSimpleStriping()); // at this point a pack is okay, caching will get the correct values // treeTable.packColumn(0, -1); final JXTree tree = new JXTree(treeTable.getTreeTableModel()); tree.setCellRenderer(treeCellRenderer); tree.setScrollsOnExpand(false); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "treetable and tree with wrapping provider"); // revalidate doesn't help Action revalidate = new AbstractActionExt("revalidate") { public void actionPerformed(ActionEvent e) { treeTable.revalidate(); tree.revalidate(); treeTable.repaint(); } }; // hack around incorrect cached node sizes Action large = new AbstractActionExt("large-circle") { public void actionPerformed(ActionEvent e) { treeTable.setLargeModel(true); treeTable.setLargeModel(false); treeTable.repaint(); } }; addAction(frame, revalidate); addAction(frame, large); show(frame); } /** * Experiments to try and understand clipping issues: occasionally, the text * in the tree column is clipped even if there is enough space available. * * Here we don't change any renderers. */ public void interactiveTreeTableClipIssueDefaultRenderer() { final JXTreeTable treeTable = new JXTreeTable(createActionTreeModel()); treeTable.setHorizontalScrollEnabled(true); treeTable.setRootVisible(true); treeTable.collapseAll(); treeTable.packColumn(0, -1); final JTree tree = new JTree(treeTable.getTreeTableModel()); tree.collapseRow(0); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "JXTreeTable vs. JTree: default renderer"); Action revalidate = new AbstractActionExt("revalidate") { public void actionPerformed(ActionEvent e) { treeTable.revalidate(); tree.revalidate(); } }; addAction(frame, revalidate); frame.setVisible(true); } /** * Experiments to try and understand clipping issues: occasionally, the text * in the tree column is clipped even if there is enough space available. * Here we set a custom (unchanged default) treeCellRenderer which * removes ellipses altogether. * */ public void interactiveTreeTableClipIssueCustomDefaultRenderer() { TreeCellRenderer renderer = new DefaultTreeCellRenderer() { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { return super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); } }; final JXTreeTable treeTable = new JXTreeTable(createActionTreeModel()); treeTable.setTreeCellRenderer(renderer); treeTable.setHorizontalScrollEnabled(true); treeTable.setRootVisible(true); treeTable.collapseAll(); treeTable.packColumn(0, -1); final JTree tree = new JTree(treeTable.getTreeTableModel()); tree.setCellRenderer(renderer); tree.collapseRow(0); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "JXTreeTable vs. JTree: custom default renderer"); Action revalidate = new AbstractActionExt("revalidate") { public void actionPerformed(ActionEvent e) { treeTable.revalidate(); tree.revalidate(); } }; addAction(frame, revalidate); frame.setVisible(true); } /** * Dirty example how to configure a custom renderer to use * treeTableModel.getValueAt(...) for showing. * */ public void interactiveTreeTableGetValueRenderer() { JXTreeTable tree = new JXTreeTable(new ComponentTreeTableModel(new JXFrame())); ComponentProvider provider = new CheckBoxProvider(StringValues.TO_STRING) { @Override protected String getValueAsString(CellContext context) { // this is dirty because the design idea was to keep the renderer // unaware of the context type TreeTableModel model = (TreeTableModel) ((JXTree) context.getComponent()).getModel(); // beware: currently works only if the node is not a DefaultMutableTreeNode // otherwise the WrappingProvider tries to be smart and replaces the node // by the userObject before passing on to the wrappee! Object nodeValue = model.getValueAt(context.getValue(), 0); return formatter.getString(nodeValue); } }; tree.setTreeCellRenderer(new DefaultTreeRenderer(provider)); tree.expandAll(); tree.setHighlighters(HighlighterFactory.createSimpleStriping()); JFrame frame = wrapWithScrollingInFrame(tree, "treeTable and getValueAt renderer"); frame.setVisible(true); } //------------- unit tests /** * Issue #399-swingx: editing terminated by selecting editing row. * */ public void testSelectionKeepsEditingWithExpandsTrue() { JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()) { @Override public boolean isCellEditable(int row, int column) { return true; } }; // sanity: default value of expandsSelectedPath assertTrue(treeTable.getExpandsSelectedPaths()); boolean canEdit = treeTable.editCellAt(1, 2); // sanity: editing started assertTrue(canEdit); // sanity: nothing selected assertTrue(treeTable.getSelectionModel().isSelectionEmpty()); int editingRow = treeTable.getEditingRow(); treeTable.setRowSelectionInterval(editingRow, editingRow); assertEquals("after selection treeTable editing state must be unchanged", canEdit, treeTable.isEditing()); } /** * Issue #212-jdnc: reuse editor, install only once. * */ public void testReuseEditor() { //TODO rework this test, since we no longer use TreeTableModel.class // JXTreeTable treeTable = new JXTreeTable(treeTableModel); // CellEditor editor = treeTable.getDefaultEditor(TreeTableModel.class); // assertTrue(editor instanceof TreeTableCellEditor); // treeTable.setTreeTableModel(simpleTreeTableModel); // assertSame("hierarchical editor must be unchanged", editor, // treeTable.getDefaultEditor(TreeTableModel.class)); fail("#212-jdnc - must be revisited after treeTableModel overhaul"); } /** * sanity: toggling select/unselect via mouse the lead is * always painted, doing unselect via model (clear/remove path) * seems to clear the lead? * */ public void testBasicTreeLeadSelection() { JXTree tree = new JXTree(); TreePath path = tree.getPathForRow(0); tree.setSelectionPath(path); assertEquals(0, tree.getSelectionModel().getLeadSelectionRow()); assertEquals(path, tree.getLeadSelectionPath()); tree.removeSelectionPath(path); assertNotNull(tree.getLeadSelectionPath()); assertEquals(0, tree.getSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after setting selection via table. * * PENDING: this passes locally, fails on server */ public void testLeadSelectionFromTable() { JXTreeTable treeTable = prepareTreeTable(false); assertEquals(-1, treeTable.getSelectionModel().getLeadSelectionIndex()); assertEquals(-1, treeTable.getTreeSelectionModel().getLeadSelectionRow()); treeTable.setRowSelectionInterval(0, 0); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); fail("lead selection synch passes locally, fails on server"); } /** * Issue #341-swingx: missing synch of lead. * test lead after setting selection via treeSelection. * PENDING: this passes locally, fails on server * */ public void testLeadSelectionFromTree() { JXTreeTable treeTable = prepareTreeTable(false); assertEquals(-1, treeTable.getSelectionModel().getLeadSelectionIndex()); assertEquals(-1, treeTable.getTreeSelectionModel().getLeadSelectionRow()); treeTable.getTreeSelectionModel().setSelectionPath(treeTable.getPathForRow(0)); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); assertEquals(0, treeTable.getTreeSelectionModel().getLeadSelectionRow()); fail("lead selection synch passes locally, fails on server"); } /** * Issue #341-swingx: missing synch of lead. * test lead after remove selection via tree. * */ public void testLeadAfterRemoveSelectionFromTree() { JXTreeTable treeTable = prepareTreeTable(true); treeTable.getTreeSelectionModel().removeSelectionPath( treeTable.getTreeSelectionModel().getLeadSelectionPath()); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after clear selection via table. * */ public void testLeadAfterClearSelectionFromTable() { JXTreeTable treeTable = prepareTreeTable(true); treeTable.clearSelection(); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after clear selection via table. * */ public void testLeadAfterClearSelectionFromTree() { JXTreeTable treeTable = prepareTreeTable(true); treeTable.getTreeSelectionModel().clearSelection(); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * creates and configures a treetable for usage in selection tests. * * @param selectFirstRow boolean to indicate if the first row should * be selected. * @return */ protected JXTreeTable prepareTreeTable(boolean selectFirstRow) { JXTreeTable treeTable = new JXTreeTable(new ComponentTreeTableModel(new JXFrame())); treeTable.setRootVisible(true); // sanity: assert that we have at least two rows to change selection assertTrue(treeTable.getRowCount() > 1); if (selectFirstRow) { treeTable.setRowSelectionInterval(0, 0); } return treeTable; } public void testDummy() { } /** * @return */ private TreeTableModel createActionTreeModel() { JXTable table = new JXTable(10, 10); table.setHorizontalScrollEnabled(true); return new ActionMapTreeTableModel(table); } } swingx-1.0-src/src/test/org/jdesktop/swingx/XLocalizeIssues.java0000644000175000017500000002365711210401722023655 0ustar tonytony/* * $Id: XLocalizeIssues.java,v 1.9 2008/02/18 11:35:02 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx; import java.awt.event.ActionEvent; import java.util.Locale; import java.util.logging.Logger; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.UIManager; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.error.ErrorInfo; import org.jdesktop.swingx.plaf.LookAndFeelAddons; /** * Test to expose known issues around Locale setting. * * Ideally, there would be at least one failing test method per open * Issue in the issue tracker. Plus additional failing test methods for * not fully specified or not yet decided upon features/behaviour. * * @author Jeanette Winzenburg */ public class XLocalizeIssues extends InteractiveTestCase { @SuppressWarnings("all") private static final Logger LOG = Logger.getLogger(XLocalizeIssues.class .getName()); private static final Locale A_LOCALE = Locale.FRENCH; private static final Locale OTHER_LOCALE = Locale.GERMAN; private Locale originalLocale; // test scope is static anyway... static { // force the addon to load LookAndFeelAddons.getAddon(); } public static void main(String[] args) { // setSystemLF(true); XLocalizeIssues test = new XLocalizeIssues(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*TwoTable.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } @Override protected void setUp() throws Exception { originalLocale = Locale.getDefault(); super.setUp(); } @Override protected void tearDown() throws Exception { Locale.setDefault(originalLocale); super.tearDown(); } /** * similar to Issue #459-swingx: errorPane properties not updated on setLocale.

* * Seem to have some unrelated open issues ... * */ public void interactiveErrorPane() { final JXTable table = new JXTable(10, 3); table.getColumnExt(0).setTitle(Locale.getDefault().getLanguage()); final JXFrame frame = wrapWithScrollingInFrame(table, "ErrorPane and default locale?"); Action toggleLocale = new AbstractActionExt("toggleLocale") { public void actionPerformed(ActionEvent e) { Locale old = Locale.getDefault(); Locale.setDefault(old == A_LOCALE ? OTHER_LOCALE : A_LOCALE); // make sure newly created comps get the new locale by default // Note: this does not effect components which are already // created JComponent.setDefaultLocale(Locale.getDefault()); table.getColumnExt(0).setTitle( Locale.getDefault().getLanguage()); } }; final JXErrorPane errorPane = new JXErrorPane(); // work around issue #??-swingx: errorPane must cope with null errorInfo. errorPane.setErrorInfo(new ErrorInfo("title", "xxxx-yyy", null, null, null, null, null)); Action open = new AbstractActionExt("open error") { public void actionPerformed(ActionEvent e) { // we are fine if the chooser is re-created in each call // _and_ the JComponent.defaultLocale is kept in synch with // with Locale.getDefault() // JFileChooser chooser = new JFileChooser(); // otherwise we have to update the chooser's locale manually if (!Locale.getDefault().equals(errorPane.getLocale())) { errorPane.setLocale(Locale.getDefault()); // need to explicitly trigger re-install to pick up the new // locale-dependent state // this throws java error - UIDefaults.getUI() failed ... ?? errorPane.updateUI(); } JXErrorPane.showDialog(frame, errorPane); } }; addAction(frame, toggleLocale); addAction(frame, open); frame.setVisible(true); } //------------------ core components for comparison. /** * Trying to understand how core Swing handles Locale * in JFileChooser. *

* * Not very intuitive: the default locale for all J** is controlled by the * static JComponent.getDefaultLocale() which is automatically set the very * first time any component is instantiated to the Locale.getDefault(). * Changing the Locale-defined default later on has no effect, must do so * explicitly *

* * Changing a component's Locale after instantiating is not trivial as well: * need to explicitly call updateUI to trigger the ui-delegate into action. *

* * * Core bug JFileChooser * */ public void interactiveFileChooser() { final JXTable table = new JXTable(10, 3); table.getColumnExt(0).setTitle(Locale.getDefault().getLanguage()); final JXFrame frame = wrapWithScrollingInFrame(table, "FileChooser and default locale?"); Action toggleLocale = new AbstractActionExt("toggleLocale") { public void actionPerformed(ActionEvent e) { Locale old = Locale.getDefault(); Locale.setDefault(old == A_LOCALE ? OTHER_LOCALE : A_LOCALE); // make sure newly created comps get the new locale by default // Note: this does not effect components which are already // created JComponent.setDefaultLocale(Locale.getDefault()); UIManager.getDefaults().setDefaultLocale(Locale.getDefault()); table.getColumnExt(0).setTitle( Locale.getDefault().getLanguage()); } }; final JFileChooser chooser = new JFileChooser(); Action open = new AbstractActionExt("open") { public void actionPerformed(ActionEvent e) { // we are fine if the chooser is re-created in each call // _and_ the JComponent.defaultLocale is kept in synch with // with Locale.getDefault() // JFileChooser chooser = new JFileChooser(); // otherwise we have to update the chooser's locale manually if (!Locale.getDefault().equals(chooser.getLocale())) { chooser.setLocale(Locale.getDefault()); // need to explicitly trigger re-install to pick up the new // locale-dependent state chooser.updateUI(); } chooser.showOpenDialog(frame); } }; addAction(frame, toggleLocale); addAction(frame, open); frame.setVisible(true); } /** * Trying to understand how core Swing handles Locale * switching in JOptionPane. *

* * Not very intuitive: the default locale for all J** is controlled by the * static JComponent.getDefaultLocale() which is automatically set the very * first time any component is instantiated to the Locale.getDefault(). * Changing the Locale-defined default later on has no effect. *

* * * Core bug JOptionPane * */ public void interactiveOptionPane() { final JXTable table = new JXTable(10, 3); table.getColumnExt(0).setTitle(Locale.getDefault().getLanguage()); final JXFrame frame = wrapWithScrollingInFrame(table, "JOptionPane and default locale?"); Action toggleLocale = new AbstractActionExt("toggleLocale") { public void actionPerformed(ActionEvent e) { Locale old = Locale.getDefault(); Locale.setDefault(old == A_LOCALE ? OTHER_LOCALE : A_LOCALE); // make sure newly created comps get the new locale by default // Note: this does not effect components which are already // created JComponent.setDefaultLocale(Locale.getDefault()); table.getColumnExt(0).setTitle( Locale.getDefault().getLanguage()); } }; Action open = new AbstractActionExt("open") { public void actionPerformed(ActionEvent e) { // title not localized ... JOptionPane.showConfirmDialog(frame, "abcdefghijklmnopqrstxyz - 123456789"); } }; addAction(frame, toggleLocale); addAction(frame, open); frame.setVisible(true); } /** * do nothing except make the testrunner happy. */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXTaskPaneContainerVisualCheck.java0000644000175000017500000001667711210401722026530 0ustar tonytony/* * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.util.Locale; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JPanel; import javax.swing.JSplitPane; import org.jdesktop.swingx.action.AbstractActionExt; /** * Simple tests to ensure that the {@code JXTaskPane} can be instantiated and * displayed. * * @author rah003 */ public class JXTaskPaneContainerVisualCheck extends InteractiveTestCase { public JXTaskPaneContainerVisualCheck() { super("JXLoginPane Test"); } public static void main(String[] args) throws Exception { // setSystemLF(true); JXTaskPaneContainerVisualCheck test = new JXTaskPaneContainerVisualCheck(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } public void interactiveGap() { JXTaskPaneContainer container = new JXTaskPaneContainer(); // ((VerticalLayout) container.getLayout()).setGap(0); JXTaskPane first = new JXTaskPane(); fillTaskPane(first); container.add(first); JXTaskPane second = new JXTaskPane(); fillTaskPane(second); container.add(second); showWithScrollingInFrame(container, "custom gap"); } public void interactiveGetUINPE() { showWithScrollingInFrame(new AbstractLBContentPanel("hi") {}, "custom gap"); } private void fillTaskPane(JXTaskPane first) { first.add(new AbstractActionExt("some") { public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } }); first.add(new AbstractActionExt("other") { public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } }); } /** * Ensure that removing a task pane properly repaints the container. *

* SwingX issue #719 */ public void interactiveRemovalTest() { final JXTaskPaneContainer container = new JXTaskPaneContainer(); final JXTaskPane pane1 = new JXTaskPane(); pane1.setTitle("First"); container.add(pane1); final JXTaskPane pane2 = new JXTaskPane(); pane2.setTitle("Second"); container.add(pane2); JXFrame frame = wrapInFrame(container, "removal test"); frame.add(new JButton(new AbstractAction("Remove Second") { public void actionPerformed(ActionEvent e) { container.remove(pane2); } }), BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); } /** * Ensure correct painting when in JSplitPane. *

* SwingX issue #434 */ public void interactiveSplitPaneTest() { final JXTaskPaneContainer container = new JXTaskPaneContainer(); final JXTaskPane pane1 = new JXTaskPane(); pane1.setTitle("First"); pane1.add(new JLabel("1")); pane1.add(new JLabel("2")); pane1.add(new JLabel("3")); container.add(pane1); final JXTaskPane pane2 = new JXTaskPane(); class DummyAction extends AbstractAction { DummyAction(String name, boolean enabled) { super(name); setEnabled(enabled); } /** * {@inheritDoc} */ public void actionPerformed(ActionEvent e) { //does nothing } } pane2.setTitle("Second"); pane2.add(new DummyAction("MMMM", true)); pane2.add(new DummyAction("MMMM", false)); pane2.add(new DummyAction("MMMM", false)); pane2.add(new DummyAction("MMMM", true)); container.add(pane2); final JXTaskPane pane3 = new JXTaskPane(); pane3.setTitle("Third"); pane3.add(new JLabel("1")); pane3.add(new JLabel("2")); pane3.add(new JLabel("3")); container.add(pane3); JSplitPane splitter = new JSplitPane(); splitter.setLeftComponent(container); splitter.setContinuousLayout(true); JXFrame frame = wrapInFrame(splitter, "split pane test"); frame.pack(); frame.setVisible(true); } @Override protected void createAndAddMenus(JMenuBar menuBar, final JComponent component) { super.createAndAddMenus(menuBar, component); JMenu menu = new JMenu("Locales"); menu.add(new AbstractAction("Change Locale") { public void actionPerformed(ActionEvent e) { if (component.getLocale() == Locale.FRANCE) { component.setLocale(Locale.ENGLISH); } else { component.setLocale(Locale.FRANCE); } }}); menuBar.add(menu); } /** * Do nothing, make the test runner happy * (would output a warning without a test fixture). * */ public void testDummy() { } public abstract class AbstractLBContentPanel extends JPanel { private JXTaskPaneContainer taskPane; private JXTaskPaneContainer jxTaskPaneContainer; public AbstractLBContentPanel(T content) { taskPane = getJXTaskPaneContainer(content); this.add(taskPane); } /** * This method initializes JXTaskPaneContainer * * @return org.jdesktop.swingx.JXTaskPaneContainer */ private JXTaskPaneContainer getJXTaskPaneContainer(T content) { if (jxTaskPaneContainer == null) { try { JXTaskPane first = new JXTaskPane(); fillTaskPane(first); JXTaskPane second = new JXTaskPane(); fillTaskPane(second); jxTaskPaneContainer = new JXTaskPaneContainer(); jxTaskPaneContainer.setSize(new Dimension(200, 220)); // Generated jxTaskPaneContainer.setOpaque(false); jxTaskPaneContainer.add(first); jxTaskPaneContainer.add(second); } catch (java.lang.Throwable e) { e.printStackTrace(); } } return jxTaskPaneContainer; } } } swingx-1.0-src/src/test/org/jdesktop/swingx/package.html0000644000175000017500000000063011210401722022167 0ustar tonytony Contains Unit tests for JDNC's Swing Extensions.

Package Specification

Related Documentation

swingx-1.0-src/src/test/org/jdesktop/swingx/JXTaskPaneVisualCheck.java0000644000175000017500000001107111210401724024646 0ustar tonytony/* * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.Locale; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JScrollPane; /** * Simple tests to ensure that the {@code JXTaskPane} can be instantiated and * displayed. * * @author rah003 */ public class JXTaskPaneVisualCheck extends InteractiveTestCase { public JXTaskPaneVisualCheck() { super("JXLoginPane Test"); } public static void main(String[] args) throws Exception { // setSystemLF(true); JXTaskPaneVisualCheck test = new JXTaskPaneVisualCheck(); try { // test.runInteractiveTests(); // test.runInteractiveTests("interactiveDisplay"); test.runInteractiveTests("interactiveMnemonic"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } public void interactiveMnemonic() { JXTaskPane pane = new JXTaskPane(); pane.setTitle("Use Me"); pane.setMnemonic(KeyEvent.VK_U); pane.setForeground(Color.RED); pane.setBackground(Color.YELLOW); pane.add(new JLabel("another")); pane.add(new JButton("wow!!")); JXTaskPaneContainer container = new JXTaskPaneContainer(); container.add(pane); showInFrame(container, "Mnemonic Test", true); } public void interactiveColors() { JXTaskPane pane = new JXTaskPane(); pane.setTitle("just something...."); pane.setForeground(Color.RED); pane.setBackground(Color.YELLOW); pane.add(new JLabel("another")); pane.add(new JButton("wow!!")); JXTaskPaneContainer container = new JXTaskPaneContainer(); container.add(pane); showInFrame(container, "background", true); } /** * Issue #249-swingx JXTaskPane looks ugly under different default LaFs * */ public void interactiveDisplay() { sun.awt.AppContext.getAppContext().put("JComponent.defaultLocale", Locale.FRANCE); JXTaskPane panel = new JXTaskPane(); panel.setTitle("Hi there"); panel.setForeground(Color.RED); panel.setFont(new Font("tahoma",Font.BOLD, 72)); panel.add(new JLabel("Hi there again")); showInFrame(panel, "JXTaskPane interactive", true); } /** * Ensure that resizing scroll pane's properly enables/disables scrollbars. *

* SwingX issue #740 */ public void interactiveJScrollPaneTest() { JXTaskPane panel = new JXTaskPane(); JXTable table = new JXTable(10, 15); table.setHorizontalScrollEnabled(true); panel.add(new JScrollPane(table)); showInFrame(panel, "Ensure scrolling works"); } @Override protected void createAndAddMenus(JMenuBar menuBar, final JComponent component) { super.createAndAddMenus(menuBar, component); JMenu menu = new JMenu("Locales"); menu.add(new AbstractAction("Change Locale") { public void actionPerformed(ActionEvent e) { if (component.getLocale() == Locale.FRANCE) { component.setLocale(Locale.ENGLISH); } else { component.setLocale(Locale.FRANCE); } }}); menuBar.add(menu); } /** * Do nothing, make the test runner happy * (would output a warning without a test fixture). * */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/combobox/0000755000175000017500000000000011210401736021524 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/combobox/EnumComboBoxModelUnitTest.java0000644000175000017500000000560711210401724027412 0ustar tonytony/* * Created on 12.04.2006 * */ package org.jdesktop.swingx.combobox; import org.jdesktop.swingx.InteractiveTestCase; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; @RunWith(JUnit4.class) public class EnumComboBoxModelUnitTest extends InteractiveTestCase { enum MyEnum1 { GoodStuff, BadStuff }; enum MyEnum2 { EasyStuff, HardStuff; public String toString() { switch (this) { case EasyStuff: return "Easy Stuff"; case HardStuff: return "Hard Stuff"; } return "ERROR"; } }; enum MyEnum3 { RightStuff, WrongStuff; public String toString() { switch (this) { case RightStuff: return "One Value"; case WrongStuff: return "One Value"; } return "ERROR"; } } /** * Issue #303-swingx: EnumComboBoxModel getSelectedItem throws * ClassCastException. Fixed. */ @Test public void testSetSelectedItem() { EnumComboBoxModel model1 = new EnumComboBoxModel( MyEnum1.class); // always starts by selecting the first value assertEquals(model1.getSelectedItem(), MyEnum1.GoodStuff); // should ignore the non-mapped string model1.setSelectedItem("something else"); assertEquals(model1.getSelectedItem(), MyEnum1.GoodStuff); model1.setSelectedItem(MyEnum1.BadStuff); assertEquals(model1.getSelectedItem(), MyEnum1.BadStuff); model1.setSelectedItem(null); assertNull(model1.getSelectedItem()); model1.setSelectedItem("GoodStuff"); assertEquals(model1.getSelectedItem(), MyEnum1.GoodStuff); // ensure that custom strings map correctly EnumComboBoxModel model2 = new EnumComboBoxModel( MyEnum2.class); // always starts by selecting the first value assertEquals(model2.getSelectedItem(), MyEnum2.EasyStuff); // should ignore the non-mapped string and set to null model2.setSelectedItem("something else"); assertEquals(model2.getSelectedItem(), MyEnum2.EasyStuff); model2.setSelectedItem(MyEnum2.HardStuff); assertEquals(model2.getSelectedItem(), MyEnum2.HardStuff); model2.setSelectedItem(null); assertNull(model2.getSelectedItem()); model2.setSelectedItem("Easy Stuff"); assertEquals(model2.getSelectedItem(), MyEnum2.EasyStuff); } @Test public void testNonUniqueToString() { try { new EnumComboBoxModel(MyEnum3.class); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // success } } } swingx-1.0-src/src/test/org/jdesktop/swingx/combobox/ListComboBoxModelVisualCheck.java0000644000175000017500000000526011210401722030034 0ustar tonytony/* * $Id: ListComboBoxModelVisualCheck.java,v 1.2 2008/01/11 14:01:33 kleopatra Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.combobox; import java.awt.event.ActionEvent; import java.util.Arrays; import javax.swing.AbstractAction; import javax.swing.ComboBoxModel; import javax.swing.JComboBox; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; public class ListComboBoxModelVisualCheck extends InteractiveTestCase { public static void main(String[] args) throws Exception { ListComboBoxModelVisualCheck test = new ListComboBoxModelVisualCheck(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Creates a {@code ListComboBoxModel} of {@code Integer}s for use in * visual checks. * * @return a list of integers from 1 to 10 */ protected ListComboBoxModel createComboBoxModel() { return new ListComboBoxModel(Arrays.asList(new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})); } /** * SwingX issue #670. Fixed. *

* Ensure that programatically selecting an item from the list correctly updates the display. */ public void interactiveSelectedItem() { final ComboBoxModel model = createComboBoxModel(); JXFrame frame = wrapInFrame(new JComboBox(model), "programatically select item"); addAction(frame, new AbstractAction("Select 9") { public void actionPerformed(ActionEvent e) { model.setSelectedItem(9); } }); frame.pack(); frame.setVisible(true); } /** * do nothing test - keep the testrunner happy. */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/combobox/EnumComboBoxModelVisualCheck.java0000644000175000017500000000314711210401722030027 0ustar tonytonypackage org.jdesktop.swingx.combobox; import javax.swing.JComboBox; import org.jdesktop.swingx.JXFrame; public class EnumComboBoxModelVisualCheck extends EnumComboBoxModelUnitTest { public static void main(String[] args) throws Exception { EnumComboBoxModelUnitTest test = new EnumComboBoxModelUnitTest(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #303-swingx: EnumComboBoxModel getSelectedItem throws * ClassCastException. Fixed. *

* A visual example using default {@code toString} implementation. */ public void interactiveSelectedItem() { EnumComboBoxModel enumModel = new EnumComboBoxModel( MyEnum1.class); JComboBox box = new JComboBox(enumModel); box.setEditable(true); JXFrame frame = wrapInFrame(box, "enum combo"); frame.setVisible(true); } /** * Issue #303-swingx: EnumComboBoxModel getSelectedItem throws * ClassCastException. Fixed. *

* A visual example using a custom {@code toString} implementation. */ public void interactiveSelectedItemWithCustomToString() { EnumComboBoxModel enumModel = new EnumComboBoxModel( MyEnum2.class); JComboBox box = new JComboBox(enumModel); box.setEditable(true); JXFrame frame = wrapInFrame(box, "enum with custom toString combo"); frame.setVisible(true); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXErrorPaneIssues.java0000644000175000017500000000412611210401722024110 0ustar tonytony/* * $Id: JXErrorPaneIssues.java,v 1.8 2008/10/06 13:54:58 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx; /** * Test to expose known issues around JXError*. * * Ideally, there would be at least one failing test method per open * Issue in the issue tracker. Plus additional failing test methods for * not fully specified or not yet decided upon features/behaviour. * * * @author Jeanette Winzenburg */ public class JXErrorPaneIssues extends InteractiveTestCase { public static void main(String[] args) { // setSystemLF(true); JXErrorPaneIssues test = new JXErrorPaneIssues(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * * reported in forum - details not visible, details close on focus change. * Worksforme on XP, maybe OS dependent? * */ public void interactiveNoDetails() { JXErrorPane.showDialog(new NullPointerException("something to show")); } /** * do-nothing method - suppress warning if there are no other * test fixtures to run. * */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXEditorPaneTest.java0000644000175000017500000001441011210401722023706 0ustar tonytony/* * $Id: JXEditorPaneTest.java,v 1.10 2009/01/27 22:53:24 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx; import java.awt.GraphicsEnvironment; import java.awt.event.ActionEvent; import java.io.IOException; import java.net.URL; import java.util.logging.Logger; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.JEditorPane; import javax.swing.text.html.HTMLDocument; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; /** * A unit test for the JXEditorPane * * @author Mark Davidson */ @RunWith(JUnit4.class) public class JXEditorPaneTest extends InteractiveTestCase { @SuppressWarnings("all") private static final Logger LOG = Logger.getLogger(JXEditorPaneTest.class .getName()); private static String testText = "This is an example of some text"; /** * Issue #289-swingx: JXEditorPane actions should be disabled if not * applicable. * undo is enabled if there is selected text and editor editable * disabled otherwise. * */ @Test public void testXDisabledUndoAction() { JXEditorPane editor = new JXEditorPane(); editor.setEditable(false); editor.setText(testText); assertEquals(testText, editor.getText()); Action action = editor.getActionMap().get("undo"); assertFalse("undo must not be enabled", action.isEnabled()); } /** * Issue #289-swingx: JXEditorPane actions should be disabled if not * applicable. * cut is enabled if there is selected text and editor editable * disabled otherwise. * */ @Test public void testXDisabledCutActionUnselected() { JXEditorPane editor = new JXEditorPane(); editor.setText("some"); editor.setEditable(true); Action action = editor.getActionMap().get("cut"); assertFalse("cut of unselected must not be enabled", action.isEnabled()); } /** * Issue #289-swingx: JXEditorPane actions should be disabled if not * applicable. * cut is enabled if there is selected text and editor editable * disabled otherwise. */ @Test public void testXDisabledCutActionOnNotEditable() { JXEditorPane editor = new JXEditorPane(); editor.setText("some"); editor.selectAll(); editor.setEditable(false); Action action = editor.getActionMap().get("cut"); assertFalse("cut of uneditable editor must not be enabled", action.isEnabled()); } /** * Issue #289-swingx: JXEditorPane actions should be disabled if not * applicable. * * paste is enabled if the editor is editable and the clipboard isn't empty, * disabled otherwise. * */ @Test public void testXDisabledPasteActionOnNotEditable() { JXEditorPane editor = new JXEditorPane(); editor.setEditable(false); Action action = editor.getActionMap().get("paste"); assertFalse("paste of uneditable editor must not be enabled", action.isEnabled()); } /** * Issue #289-swingx: JXEditorPane actions should be disabled if not * applicable. * * paste is enabled if the editor is editable the clipboard isn't empty. * can't really test ... don't want to clear the clipboard as a test side-effect. */ @Test public void testXDisabledPasteEmptyClipboard() { JXEditorPane editor = new JXEditorPane(); editor.setEditable(true); // can't really test - want to erase system clipboard? // Action action = editor.getActionMap().get("paste"); // assertFalse("paste with empty clipboard must not be enabled", action.isEnabled()); } @Test public void testInitialization() throws IOException { URL url = JXEditorPaneTest.class.getResource("resources/test.html"); JXEditorPane editor = new JXEditorPane(); editor.setContentType("text/html"); editor.setPage(url); assertTrue(editor.getDocument() instanceof HTMLDocument); assertNotNull(editor.getCaretListener()); assertNotNull(editor.getUndoableEditListener()); editor = new JXEditorPane("text/html", ""); editor.setPage(url); assertTrue(editor.getDocument() instanceof HTMLDocument); assertNotNull(editor.getCaretListener()); assertNotNull(editor.getUndoableEditListener()); editor = new JXEditorPane(); assertFalse(editor.getDocument() instanceof HTMLDocument); assertNull(editor.getCaretListener()); } @Test public void testRegistration() { } @Test public void testCutPastePlain() { JXEditorPane editor = new JXEditorPane("text/plain", testText); editorCutPaste(editor); } /** * XXX currently the html cut and paste is broken. A work around has been * implemented to use only plain text on the clip. This test will fail * if the text contains some markup like <b>foo</b> */ @Test public void testCutPasteHtml() { JXEditorPane editor = new JXEditorPane("text/html", testText); editorCutPaste(editor); } public void editorCutPaste(JEditorPane editor) { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { return; } // set selection markers editor.select(4, 15); // get cut and paste actions and execute them simultaniously ActionMap map = editor.getActionMap(); Action cut = map.get("cut-to-clipboard"); Action paste = map.get("paste-from-clipboard"); assertNotNull(cut); assertNotNull(paste); String before = editor.getText(); cut.actionPerformed(new ActionEvent(editor, 0, (String)cut.getValue(Action.ACTION_COMMAND_KEY))); // XXX caret position should be moved in the cut operation editor.setCaretPosition(4); paste.actionPerformed(new ActionEvent(editor, 0, (String)paste.getValue(Action.ACTION_COMMAND_KEY))); assertEquals(before, editor.getText()); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXDialogVisualCheck.java0000644000175000017500000000730511210401722024342 0ustar tonytony/* * $Id: JXDialogVisualCheck.java,v 1.2 2008/06/20 11:21:29 kleopatra Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx; import java.awt.Window; import java.awt.event.ActionEvent; import java.util.logging.Logger; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; import org.jdesktop.swingx.action.AbstractActionExt; /** * TODO add type doc * * @author Jeanette Winzenburg */ public class JXDialogVisualCheck extends InteractiveTestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger .getLogger(JXDialogVisualCheck.class.getName()); public static void main(String[] args) { // setSystemLF(true); JXDialogVisualCheck test = new JXDialogVisualCheck(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * * example of how to bind custom actions to a JXDialog. * * Requirement from forum: * - custom execute * - custom close (text should be "Cancel") * */ public void interactiveXDialogButtons() { final JComponent content = new JPanel(); content.add(new JLabel("A label:")); content.add(new JTextField("something to play with")); Action myExecuteAction = new AbstractActionExt("Execute") { public void actionPerformed(ActionEvent e) { LOG.info("got an execute"); } }; content.getActionMap().put(JXDialog.EXECUTE_ACTION_COMMAND, myExecuteAction); Action myCancelAction = new AbstractActionExt("Cancel") { public void actionPerformed(ActionEvent e) { LOG.info("got a close"); Window window = SwingUtilities.windowForComponent(content); if (window instanceof JXDialog) { ((JXDialog) window).doClose(); } } }; content.getActionMap().put(JXDialog.CLOSE_ACTION_COMMAND, myCancelAction); final JXDialog dialog = new JXDialog(content); dialog.pack(); JComponent comp = new JXPanel(); Action openDialog = new AbstractActionExt("open dialog") { public void actionPerformed(ActionEvent e) { dialog.setVisible(true); } }; JButton button = new JButton(openDialog); comp.add(button); showWithScrollingInFrame(comp, "JXDialog custom actions"); } /** * Do nothing, just to make the runner happy if there are no * issues. * */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXDatePickerVisualCheck.java0000644000175000017500000010530511210401722025155 0ustar tonytony/* * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.Component; import java.awt.Container; import java.awt.LayoutManager; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JSpinner; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.SpinnerDateModel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.JSpinner.DefaultEditor; import javax.swing.UIManager.LookAndFeelInfo; import javax.swing.text.DateFormatter; import javax.swing.text.DefaultFormatterFactory; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.calendar.DateSelectionModel; import org.jdesktop.swingx.calendar.DaySelectionModel; import org.jdesktop.swingx.calendar.SingleDaySelectionModel; import org.jdesktop.swingx.calendar.DateSelectionModel.SelectionMode; import org.jdesktop.test.VerticalLayoutPref; /** * Simple tests to ensure that the {@code JXDatePicker} can be instantiated and * displayed.

* * JW: being lazy - added visuals for JXMonthView as well. * * @author Karl Schaefer */ public class JXDatePickerVisualCheck extends InteractiveTestCase { @SuppressWarnings("all") private static final Logger LOG = Logger .getLogger(JXDatePickerVisualCheck.class.getName()); @SuppressWarnings("unused") private Calendar calendar; /** flag to decide if the menubar should be created */ private boolean showMenu; public JXDatePickerVisualCheck() { super("JXDatePicker Test"); } public static void main(String[] args) throws Exception { UIManager.put("JXDatePicker.forceZoomable", Boolean.TRUE); setSystemLF(true); JXDatePickerVisualCheck test = new JXDatePickerVisualCheck(); try { // test.runInteractiveTests(); // test.runInteractiveTests("interactive.*PrefSize.*"); // test.runInteractiveTests("interactive.*Keep.*"); // test.runInteractiveTests("interactive.*Multiple.*"); test.runInteractiveTests("interactive.*Event.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #940-swingx: support multiple selection in picker. * Nothing out-off-the-box, trying to implement custom * dateSelectionModel. */ public void interactiveMultipleSelection() { DateSelectionModel model = new AddingDaySelectionModel(); model.setSelectionMode(SelectionMode.MULTIPLE_INTERVAL_SELECTION); JXMonthView monthView = new JXMonthView(new Date(), model) { @Override public Date getSelectionDate() { if (getSelectionModel() instanceof AddingDaySelectionModel) { return ((AddingDaySelectionModel) getSelectionModel()).getLastAddedDate(); } return super.getSelectionDate(); } }; JXDatePicker picker = new JXDatePicker(); picker.setMonthView(monthView); JXFrame frame = showInFrame(picker, "multiple selection"); show(frame); } /** * Custom model which always adds selection dates. */ public static class AddingDaySelectionModel extends DaySelectionModel { Date lastAdded; @Override public void setSelectionInterval(Date startDate, Date endDate) { addSelectionInterval(startDate, endDate); } @Override public void addSelectionInterval(Date startDate, Date endDate) { if (endDate.before(startDate)) return; super.addSelectionInterval(startDate, endDate); // PENDING: need to do better to cope with unselectables if (isSelected(endDate)) { lastAdded = endDate; } else if (isSelected(startDate)) { lastAdded = startDate; } else { lastAdded = null; } } @Override public void clearSelection() { lastAdded = null; super.clearSelection(); } public Date getLastAddedDate() { return lastAdded; } } /** * Issue #910-swingx: commitToday must not be allowed if field not editable. * */ public void interactiveNotEditableCommitToday() { JXDatePicker picker = new JXDatePicker(); Calendar cal = picker.getMonthView().getCalendar(); cal.add(Calendar.MONTH, 5); picker.setDate(cal.getTime()); picker.setEditable(false); showInFrame(picker, "not editable "); } /** * Issue #910-swingx: commitToday must not be allowed if field not editable. * */ public void interactiveNotEditableCompareTextField() { final JXDatePicker picker = new JXDatePicker(new Date()); final JFormattedTextField field = new JFormattedTextField(picker.getDate()); field.setEditable(false); PropertyChangeListener l = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if ("date".equals(evt.getPropertyName())) { if (picker.getDate() != null) field.setValue(picker.getDate()); } } }; picker.addPropertyChangeListener(l); JXPanel panel = new JXPanel(); panel.add(picker); panel.add(field); showInFrame(panel, "not editable field "); } /** * From forum: have spinner with the same timezone. */ public void interactiveTimeZoneFormat() { final JSpinner spinner = new JSpinner(new SpinnerDateModel()); final JXDatePicker picker = new JXDatePicker(); picker.setTimeZone(TimeZone.getTimeZone("GMT-10")); picker.setDate(new Date()); spinner.setValue(picker.getDate()); SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss", picker.getLocale()); format.setTimeZone(picker.getTimeZone()); JFormattedTextField textField = ((DefaultEditor) spinner.getEditor()).getTextField(); textField.setFormatterFactory( new DefaultFormatterFactory(new DateFormatter(format))); PropertyChangeListener l = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if ("date".equals(evt.getPropertyName())) { if (picker.getDate() != null) spinner.setValue(picker.getDate()); } } }; picker.addPropertyChangeListener(l); JXPanel panel = new JXPanel(); panel.add(picker); panel.add(spinner); showInFrame(panel, "formats in picker and spinner"); } /** * Issue #565-swingx: popup not closed if open and * clicking into other focus-tricksing component (like * picker, combo). * * Issue #1011-swingx: popup of first picker opened on click on second * (mac only?) * * And: Compare picker and combo behaviour on toggle lf. * * Not really comparable: the combo has complete control over the popup, re-creates * both popup and content on install. * */ public void interactivePopupPickerCompareCombo() { // Trace14.keyboardFocusManager(true); final JXDatePicker picker = new JXDatePicker(); picker.getEditor().setName("first DateField"); JComboBox box = new JComboBox(new Object[] {"one", "twooooooo", "threeeeeeeeeeee", "GOOO!"}); box.setEditable(true); JComponent comp = new JPanel(); comp.add(picker); comp.add(new JXDatePicker(new Date())); comp.add(box); JXFrame frame = wrapInFrame(comp, "compare combo <-> picker, picker <-> picker", true); addMessage(frame, "open popup, click in other picker/combo - popup must close and other focused"); show(frame); } /** * Issue #1011-swingx: popup of first picker opened on click on second * (mac only?) * */ public void interactivePopupTwoPickers() { // Trace14.keyboardFocusManager(true); final JXDatePicker picker = new JXDatePicker(); picker.getEditor().setName("first DateField"); JComponent comp = new JPanel(); comp.add(picker); JXDatePicker other = new JXDatePicker(new Date()); comp.add(other); // other.setFocusable(false); // picker.setFocusable(false); JXFrame frame = wrapInFrame(comp, "popup: picker <-> picker", true); addMessage(frame, "click on second opens popup of first (mac only?)"); show(frame, 400, 400); } /** * Visually characterize focus behaviour. * * Issue #577-swingx: JXDatePicker focus cleanup. * After commit/cancel in popup: picker's editor should be focused. * * * Issue #757-swingx: JXDatePicker inconsistent focusLost firing. * * JXDatePicker must not fire focusLost, the picker's editor should. * * New (?) problem: after closing focused popup by clicking into * another the focus is in the picker's editor and can't be moved * with tab * - open popup, * - focus popup (by clicking next month, no keyboard, nor commit/cancel) * - click into textfield: popup closed, picker editor has focus * * Independent of forcing focus into picker itself or its editor on open. * Looks dependent on heavyweight popup: okay on resizing the frame so * that the popup fits in. * * */ public void interactiveFocusEventOnTogglePopup() { JXDatePicker picker = new JXDatePicker(); final Action togglePopup = picker.getActionMap().get("TOGGLE_POPUP"); JComboBox box = new JComboBox(new String[] {"one", "twos"}); box.setEditable(true); FocusListener l = new FocusListener() { public void focusGained(FocusEvent e) { if (e.isTemporary()) return; String source = e.getSource().getClass().getSimpleName(); LOG.info("focus gained from: " + source); } public void focusLost(FocusEvent e) { if (e.isTemporary()) return; String source = e.getSource().getClass().getSimpleName(); LOG.info("focus lost from: " + source); }}; picker.getEditor().addFocusListener(l); picker.addFocusListener(l); box.addFocusListener(l); box.getEditor().getEditorComponent().addFocusListener(l); JComponent panel = new JPanel(); panel.add(box); panel.add(picker); panel.add(new JTextField("something to focus")); JXFrame frame = showInFrame(panel, "E: FocusEvents on editor"); addAction(frame, togglePopup); frame.pack(); } /** * Issue #568-swingx: DatePicker must not reset time fields. * * Behaviour defined by selection model of monthView. While the default * (DaySelectionModel) normalizes the dates to the start of the day in the * model's calendar coordinates, a SingleDaySelectionModel keeps the date as-is. * For now, need to explicitly set. */ public void interactiveKeepTimeFields() { final JXDatePicker picker = new JXDatePicker(); SingleDaySelectionModel selectionModel = new SingleDaySelectionModel(); picker.getMonthView().setSelectionModel(selectionModel); picker.setDate(new Date()); DateFormat format = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL); picker.setFormats(format); final JFormattedTextField field = new JFormattedTextField(format); field.setValue(picker.getDate()); PropertyChangeListener l = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if ("date".equals(evt.getPropertyName())) { field.setValue(evt.getNewValue()); } } }; picker.addPropertyChangeListener(l); Action setDate = new AbstractActionExt("set date") { public void actionPerformed(ActionEvent e) { picker.setDate(new Date()); } }; JComponent box = Box.createHorizontalBox(); box.add(picker); box.add(field); JXFrame frame = wrapInFrame(box, "time fields"); addAction(frame, setDate); frame.pack(); frame.setVisible(true); } /** * Issue #706-swingx: picker doesn't update monthView. * */ public void interactiveUpdateUIPickerMonthView() { final JXDatePicker picker = new JXDatePicker(); JXFrame frame = showInFrame(picker, "picker update ui"); Action action = new AbstractActionExt("toggleUI") { public void actionPerformed(ActionEvent e) { String uiClass = (String) UIManager.get(JXMonthView.uiClassID); boolean custom = uiClass.indexOf("Custom") > 0; if (!custom) { UIManager.put(JXMonthView.uiClassID, "org.jdesktop.swingx.test.CustomMonthViewUI"); } else { UIManager.put(JXMonthView.uiClassID, null); } picker.updateUI(); custom = !custom; } }; addAction(frame, action); frame.pack(); }; /** * Issue #764-swingx: JXDatePicker sizing. * * Compare pref size with/-out date initially. * - null date is slightly narrower than not null * - formats using the day of week are cut a bit (for "long" day names like wed) * - a formatted text field is slightly off, by the width of the caret */ public void interactiveLocalePrefSize() { // wednesday - has width problems calendar.set(2008, Calendar.FEBRUARY, 20); Date date = calendar.getTime(); String formatString = "EEE MM/dd/yyyy"; LayoutManager layout = new VerticalLayoutPref(); JComponent fieldsNull = new JPanel(layout); addFormattedTextField(fieldsNull, Locale.US, null, formatString); addFormattedTextField(fieldsNull, Locale.UK, null, formatString); addFormattedTextField(fieldsNull, Locale.GERMAN, null, formatString); addFormattedTextField(fieldsNull, Locale.ITALIAN, null, formatString); JComponent fields = new JPanel(layout); addFormattedTextField(fields, Locale.US, date, formatString); addFormattedTextField(fields, Locale.UK, date, formatString); addFormattedTextField(fields, Locale.GERMAN, date, formatString); addFormattedTextField(fields, Locale.ITALIAN, date, formatString); JComponent other = new JPanel(layout); addDatePickerWithLocaleSet(other, Locale.US, date, formatString); addDatePickerWithLocaleSet(other, Locale.UK, date, formatString); addDatePickerWithLocaleSet(other, Locale.GERMAN, date, formatString); addDatePickerWithLocaleSet(other, Locale.ITALIAN, date, formatString); JComponent comp = new JPanel(layout); addDatePickerWithLocaleSet(comp, Locale.US, null, formatString); addDatePickerWithLocaleSet(comp, Locale.UK, null, formatString); addDatePickerWithLocaleSet(comp, Locale.GERMAN, null, formatString); addDatePickerWithLocaleSet(comp, Locale.ITALIAN, null, formatString); JComponent outer = Box.createHorizontalBox(); outer.add(other); outer.add(comp); outer.add(fields); outer.add(fieldsNull); JXFrame frame = wrapInFrame(outer, "Sizing DatePicker"); addMessage(frame, "rows: locales, columns: picker/formatted field"); frame.pack(); frame.setVisible(true); } /** * Issue #764-swingx: JXDatePicker sizing. * * Compare pref size with/-out date initially. * - null date is slightly narrower than not null * - formats using the day of week are cut a bit (for "long" day names like wed) * - a formatted text field is slightly off, by the width of the caret */ public void interactiveLocalePrefSize2() { // wednesday - has width problems calendar.set(2008, Calendar.FEBRUARY, 20); Date date = calendar.getTime(); String formatString = "EEE MM/dd/yyyy"; LayoutManager layout = new VerticalLayoutPref(); JComponent german = new JPanel(layout); addFormattedTextField(german, Locale.GERMAN, date, formatString); addDatePickerWithLocaleSet(german, Locale.GERMAN, date, formatString); addDatePickerWithLocaleSet(german, Locale.GERMAN, null, formatString); addFormattedTextField(german, Locale.GERMAN, null, formatString); JComponent italian = new JPanel(layout); addFormattedTextField(italian, Locale.ITALIAN, date, formatString); addDatePickerWithLocaleSet(italian, Locale.ITALIAN, date, formatString); addDatePickerWithLocaleSet(italian, Locale.ITALIAN, null, formatString); addFormattedTextField(italian, Locale.ITALIAN, null, formatString); JComponent uk = new JPanel(layout); addFormattedTextField(uk, Locale.UK, date, formatString); addDatePickerWithLocaleSet(uk, Locale.UK, date, formatString); addDatePickerWithLocaleSet(uk, Locale.UK, null, formatString); addFormattedTextField(uk, Locale.UK, null, formatString); JComponent us = new JPanel(layout); addFormattedTextField(us, Locale.US, date, formatString); addDatePickerWithLocaleSet(us, Locale.US, date, formatString); addDatePickerWithLocaleSet(us, Locale.US, null, formatString); addFormattedTextField(us, Locale.US, null, formatString); JComponent outer = Box.createHorizontalBox(); outer.add(us); outer.add(uk); outer.add(german); outer.add(italian); JXFrame frame = wrapInFrame(outer, "Sizing DatePicker"); addMessage(frame, "rows: picker/formatted field, columns: locales"); frame.pack(); frame.setVisible(true); } /** * Instantiates a datePicker using the default constructor, set * its locale to the given and adds it to the comp. * @param comp the container to add the picker to * @param uk the locale to use. */ private void addDatePickerWithLocaleSet(JComponent comp, Locale uk, Date date, String formatString) { JXDatePicker datePicker = new JXDatePicker(date); datePicker.setLocale(uk); if (formatString != null) { DateFormat format = new SimpleDateFormat(formatString, uk); datePicker.setFormats(format); } comp.add(datePicker); } /** * Instantiates a datePicker using the default constructor, set * its locale to the given and adds it to the comp. * @param comp the container to add the picker to * @param uk the locale to use. */ private void addFormattedTextField(JComponent comp, Locale uk, Date date, String formatString) { JFormattedTextField datePicker; if (formatString != null) { DateFormat format = new SimpleDateFormat(formatString, uk); datePicker = new JFormattedTextField(format); } else { datePicker = new JFormattedTextField(); } datePicker.setValue(date); comp.add(datePicker); } /** * Issue #665-swingx: make JXDatePicker Locale-aware. * * Here: instantiate the picker with a non-default locale. * Check that the dates in LinkPanel and editor * are formatted as appropriate for the Locale */ public void interactiveLocaleConstructor() { JComponent other = new JPanel(); // wednesday - has width problems calendar.set(2008, Calendar.FEBRUARY, 20); Date date = calendar.getTime(); addDatePickerWithLocaleConstructor(other, Locale.US, date); addDatePickerWithLocaleConstructor(other, Locale.UK, date); addDatePickerWithLocaleConstructor(other, Locale.GERMAN, date); addDatePickerWithLocaleConstructor(other, Locale.ITALIAN, date); JComponent comp = new JPanel(); addDatePickerWithLocaleConstructor(comp, Locale.US, null); addDatePickerWithLocaleConstructor(comp, Locale.UK, null); addDatePickerWithLocaleConstructor(comp, Locale.GERMAN, null); addDatePickerWithLocaleConstructor(comp, Locale.ITALIAN, null); JComponent outer = Box.createVerticalBox(); outer.add(other); outer.add(comp); showInFrame(outer, "Localized DatePicker: constructor"); } /** * Instantiates a datePicker using the constructor with the given locale and * adds it to the comp. * @param comp the container to add the picker to * @param uk the locale to use. */ private void addDatePickerWithLocaleConstructor(JComponent comp, Locale uk, Date date) { JXDatePicker datePicker = new JXDatePicker(uk); datePicker.setDate(date); comp.add(new JLabel(uk.getDisplayName())); comp.add(datePicker); } /** * Issue #665-swingx: make JXDatePicker Locale-aware. * * Tests reaction to default locales set via both JComponent.setDefault and * Locale.setDefault. Going that way, catches the locales fine. * * Also Issue #681-swingx - the first row of days in the monthview * overlaps with the day names for locales which have the monday as the * first day of week. */ public void interactiveLocaleDefault() { JComponent comp = new JPanel(); Locale old = addDatePickerWithLocale(comp, Locale.US); addDatePickerWithLocale(comp, Locale.UK); addDatePickerWithLocale(comp, Locale.GERMAN); addDatePickerWithLocale(comp, Locale.ITALIAN); showInFrame(comp, "DatePicker takes default Locale"); setLocale(old); } /** * Sets the default Locale to the given, instantiates a JXDatePicker with * default Locale and adds it to the given component. Returns the previous * default Locale. * * @param comp the container to add the picker to * @param uk the new default Locale * * @return the previous default Locale */ private Locale addDatePickerWithLocale(JComponent comp, Locale uk) { Locale old = setLocale(uk); JXDatePicker datePicker = new JXDatePicker(); comp.add(new JLabel(uk.getDisplayName())); comp.add(datePicker); return old; } /** * Sets default Locale (on Locale and JComponent) to the given Locale and * returns the previous default. * * @param locale the default Locale to set. * @return the previous default. */ private Locale setLocale(Locale locale) { Locale old = JComponent.getDefaultLocale(); JComponent.setDefaultLocale(locale); Locale.setDefault(locale); return old; } /** * Issue #566-swingx: JXRootPane eats picker's popup esc. * to reproduce: open the picker's popup the press esc - * not closed. Same with combo is working. * */ public void interactiveXRootPaneEatsEscape() { JXDatePicker picker = new JXDatePicker(); JComboBox box = new JComboBox(new String[] {"one", "twos"}); box.setEditable(true); JComponent panel = new JPanel(); panel.add(picker); panel.add(box); showInFrame(panel, "Escape key"); } /** * visual check that toggling the panel adds/removes it * and installs the keybindings. * */ public void interactiveLinkPanelSet() { final JXDatePicker picker = new JXDatePicker(); final JPanel panel = picker.getLinkPanel(); // initial null okay JXFrame frame = showInFrame(picker, "null panel"); Action toggleLinkPanel = new AbstractAction("toggleLinkPanel <-> null") { public void actionPerformed(ActionEvent e) { boolean hasLinkPanel = picker.getLinkPanel() != null; picker.setLinkPanel(hasLinkPanel ? null : panel); } }; addAction(frame, toggleLinkPanel); frame.pack(); } /** * Checking PropertyChangeEvent: report in forum that no event for date fired. * here not reproducible.. problem of WizardPage? */ public void interactivePCEvent() { JXDatePicker picker = new JXDatePicker(new Date()); JFormattedTextField textField = new JFormattedTextField(DateFormat.getDateInstance()); textField.setValue(new Date()); PropertyChangeListener l = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { LOG.info("got pce from: " + e.getSource().getClass().getSimpleName() + "\n" + e.getPropertyName() + e.getNewValue()); } }; textField.addPropertyChangeListener(l); picker.addPropertyChangeListener(l); // picker.getMonthView().addActionListener(l); JPanel panel = new JPanel(); panel.add(textField); panel.add(picker); JTabbedPane tab = new JTabbedPane(); tab.add("fields", panel); tab.add("dummy", new JTextField("dummy")); JXFrame frame = showInFrame(tab, "Compare propertChange events: keyboard/mouse"); frame.pack(); } /** * Issue #235-swingx: action events * * Compare textfield, formatted, picker, combo after keyboard. * * TextField * - simple field fires on enter always * - formatted fire on enter if value had been edited * * ComboBox * - fires on enter always * - fires on click in dropdown * * Calendar widgets after cleanup: * * Picker * - fires "datePickerCommit" on click (actually released) into monthView * - fires "datePickerCommit"/-"Cancel" on enter/escape, both in input field * and if popup is open * * MonthView * - fires "monthViewCommit" on click (actually released) * - fires "monthViewCommit"/-"Cancel" on enter/esc * * */ public void interactiveActionEventSetAction() { JXDatePicker picker = new JXDatePicker(); JTextField simpleField = new JTextField("simple field"); JFormattedTextField textField = new JFormattedTextField(DateFormat.getDateInstance()); textField.setValue(new Date()); JComboBox box = new JComboBox(new Object[] {"one", "two", "three"}); box.setEditable(true); JComboBox nonEditableBox = new JComboBox(new Object[] {"one", "two", "three"}); JSpinner spinner = new JSpinner(); final Action l = new AbstractActionExt("recived") { public void actionPerformed(ActionEvent e) { LOG.info("got action from: " + e.getSource().getClass().getName() + "\n" + e); } }; simpleField.setAction(l); textField.setAction(l); // picker doesn't have action-related api picker.addActionListener(l); // picker.getMonthView().addActionListener(l); box.setAction(l); nonEditableBox.setAction(l); JPanel panel = new JPanel(); panel.add(simpleField); panel.add(textField); panel.add(picker); panel.add(box); panel.add(new JCheckBox(l)); panel.add(nonEditableBox); JXFrame frame = wrapInFrame(panel, "SetAction - Compare action events: keyboard/mouse"); Action toggleEnabled = new AbstractActionExt("toggleEnabledAction") { public void actionPerformed(ActionEvent e) { l.setEnabled(!l.isEnabled()); } }; addAction(frame, toggleEnabled); show(frame); } /** * Issue #235-swingx: action events * * Compare textfield, formatted, picker and combo: programatic change. * - only combo fires * */ public void interactiveActionEventSetValue() { final JXDatePicker picker = new JXDatePicker(); final JTextField simpleField = new JTextField("simple field"); final JFormattedTextField textField = new JFormattedTextField(DateFormat.getDateInstance()); textField.setValue(new Date()); final JComboBox box = new JComboBox(new Object[] {"one", "two", "three"}); box.setEditable(true); ActionListener l = new ActionListener() { public void actionPerformed(ActionEvent e) { LOG.info("got action from: " + e.getSource().getClass().getName() + "\n" + e); } }; simpleField.addActionListener(l); textField.addActionListener(l); picker.addActionListener(l); picker.getMonthView().addActionListener(l); box.addActionListener(l); Action action = new AbstractAction("set new value") { int dayToAdd = 1; public void actionPerformed(ActionEvent e) { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, dayToAdd++); Date date = cal.getTime(); String text = DateFormat.getDateInstance().format(date); simpleField.setText(text); textField.setValue(date); picker.setDate(date); box.setSelectedItem(text); } }; JPanel panel = new JPanel(); panel.add(simpleField); panel.add(textField); panel.add(picker); panel.add(box); JXFrame frame = showInFrame(panel, "Compare action events: programmatic change"); addAction(frame, action); frame.pack(); } /** * Issue #99-swingx: null date and opening popup forces selection. * Status? Looks fixed.. * * Sizing issue if init with null date */ public void interactiveNullDate() { JXDatePicker picker = new JXDatePicker(); showInFrame(picker, "null date in picker"); } /** * something weird's going on: the picker's date must be null * after setting a monthView with null selection. It is, until * shown? * Looks fixed during synch control cleanup in datePicker. */ public void interactiveShowPickerSetMonthNull() { JXDatePicker picker = new JXDatePicker(); JXMonthView intervalForPicker = new JXMonthView(); intervalForPicker.setSelectionMode(SelectionMode.SINGLE_INTERVAL_SELECTION); picker.setMonthView(intervalForPicker); assertNull(picker.getDate()); showInFrame(picker, "empty selection in monthView"); assertNull(picker.getDate()); } public void interactiveDatePickerDisplay() { JXDatePicker datePicker = new JXDatePicker(); showInFrame(datePicker, "show date picker"); } @Override protected void setUp() throws Exception { calendar = Calendar.getInstance(); } private static class SetPlafAction extends AbstractAction { private String plaf; public SetPlafAction(String name, String plaf) { super(name); this.plaf = plaf; } /** * {@inheritDoc} */ public void actionPerformed(ActionEvent e) { try { Component c = (Component) e.getSource(); Window w = null; for (Container p = c.getParent(); p != null; p = p instanceof JPopupMenu ? (Container) ((JPopupMenu) p) .getInvoker() : p.getParent()) { if (p instanceof Window) { w = (Window) p; } } UIManager.setLookAndFeel(plaf); SwingUtilities.updateComponentTreeUI(w); w.pack(); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } catch (InstantiationException e1) { e1.printStackTrace(); } catch (IllegalAccessException e1) { e1.printStackTrace(); } catch (UnsupportedLookAndFeelException e1) { e1.printStackTrace(); } } } private JMenuBar createMenuBar() { LookAndFeelInfo[] plafs = UIManager.getInstalledLookAndFeels(); JMenuBar bar = new JMenuBar(); JMenu menu = new JMenu("Set L&F"); for (LookAndFeelInfo info : plafs) { menu.add(new SetPlafAction(info.getName(), info.getClassName())); } bar.add(menu); return bar; } @Override public JXFrame wrapInFrame(JComponent component, String title) { JXFrame frame = super.wrapInFrame(component, title); if (showMenu) { frame.setJMenuBar(createMenuBar()); } return frame; } /** * Do nothing, make the test runner happy * (would output a warning without a test fixture). * */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/UIDefaultsResourceBundleCheck.java0000644000175000017500000000275711210401722026372 0ustar tonytony/* * Created on 23.02.2007 * */ package org.jdesktop.swingx; import java.util.Locale; import org.jdesktop.swingx.plaf.UIManagerExt; import org.jdesktop.swingx.resources.swingx; /** * Standalone example for problems with application resourceBundle.

* * Run in jdk5: the found resource value is always in the system's default * locale.

* * Run in jdk6: the found resource value is correctly localized. * * @author Karl Schaefer */ public class UIDefaultsResourceBundleCheck { /** * @param args * unused */ public static void main(String[] args) { UIManagerExt.addResourceBundle( swingx.class.getName()); System.out.println(UIManagerExt.getString("LoginPane.1")); System.out.println(UIManagerExt.getString("LoginPane.1", Locale.US)); System.out.println(UIManagerExt.getString("LoginPane.1", Locale.GERMAN)); System.out.println(UIManagerExt.getString("LoginPane.1", Locale.GERMANY)); System.out.println(UIManagerExt.getString("LoginPane.1", Locale.FRENCH)); System.out.println(UIManagerExt.getString("LoginPane.1", Locale.FRANCE)); System.out.println(UIManagerExt.getString("LoginPane.1", Locale.CANADA_FRENCH)); System.out.println(UIManagerExt.getString("LoginPane.1", new Locale("pt"))); System.out.println(UIManagerExt.getString("LoginPane.1", new Locale("pt", "BR"))); System.out.println(UIManagerExt.getString("LoginPane.1", Locale.KOREAN)); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXButtonVisualCheck.java0000644000175000017500000000602311210401722024412 0ustar tonytony/* * $Id: JXButtonVisualCheck.java,v 1.2 2008/06/08 13:22:34 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.List; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; import org.jdesktop.swingx.JXHeader; /** * Visual tests of JXButton issues. * @author rah003 * */ public class JXButtonVisualCheck extends InteractiveTestCase { /** * Test for issue #761. */ public void interactiveButton() { final JFrame f = new JFrame(); JPanel control = new JPanel(); JButton b = new JButton("Start"); control.add(b); f.add(control, BorderLayout.SOUTH); f.setPreferredSize(new Dimension(400, 400)); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.pack(); f.setVisible(true); } /** * Test for issue 849 */ public void interactiveActionButton() { AbstractAction action = new AbstractAction() { public void actionPerformed(ActionEvent e) { //do nothing } }; action.putValue(action.NAME, "My Action"); action.setEnabled(true); final JFrame f = new JFrame(); f.setSize(300, 200); JPanel jContentPane = new JPanel(); jContentPane.setLayout(new BorderLayout()); jContentPane.add(new JButton(action), BorderLayout.WEST); // Generated jContentPane.add(new JXButton(action), BorderLayout.EAST); f.setContentPane(jContentPane); f.setTitle("JFrame"); f.setVisible(true); } /** * @param args */ public static void main(String[] args) { JXButtonVisualCheck test = new JXButtonVisualCheck(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * do nothing test - keep the testrunner happy. */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/table/0000755000175000017500000000000011210401734021001 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/table/ColumnFactoryTest.java0000644000175000017500000002326311210401722025274 0ustar tonytony/* * Created on 02.06.2006 * */ package org.jdesktop.swingx.table; import java.awt.Component; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXTable; import org.jdesktop.test.AncientSwingTeam; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * Contains unit tests for ColumnFactory. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class ColumnFactoryTest extends InteractiveTestCase { /** * Issue #564-swingx: allow custom factories to return null column. * Here: test that table can cope with null columns on create. */ @Test public void testTableCopeWithCreateNullColumn() { // factory returns null on create ColumnFactory factory = new ColumnFactory() { @Override public TableColumnExt createTableColumn(int modelIndex) { return modelIndex > 0 ? super.createTableColumn(modelIndex) : null; } }; JXTable table = new JXTable(); table.setColumnFactory(factory); TableModel model = new DefaultTableModel(0, 10); table.setModel(model); assertEquals("factory must have created one less than model columns", model.getColumnCount() - 1, table.getColumnCount()); } /** * Issue #564-swingx: allow custom factories to return null column. * Here: test that ColumnFactory can handle null creation. */ @Test public void testCreateNullColumn() { // factory returns null on create ColumnFactory factory = new ColumnFactory() { @Override public TableColumnExt createTableColumn(int modelIndex) { return null; } }; TableModel model = new DefaultTableModel(0, 10); factory.createAndConfigureTableColumn(model, 0); } /** * Issue #564-swingx: allow custom factories to return null column. * Here: check how to implement model-based decision. * * PENDING: need additional api? Left to subclasses for now. */ @Test public void testCreateNullColumnFromModelProperty() { // factory returns null on create ColumnFactory factory = new ColumnFactory() { @Override public TableColumnExt createAndConfigureTableColumn( TableModel model, int modelIndex) { if ("A".equals(model.getColumnName(modelIndex))) return null; return super.createAndConfigureTableColumn(model, modelIndex); } }; TableModel model = new DefaultTableModel(0, 10); TableColumnExt column = factory.createAndConfigureTableColumn(model, 0); assertNull("", column); } /** * Issue ??: NPE in pack for null table header. * */ @Test public void testPackColumnNullHeader() { JXTable table = new JXTable(new AncientSwingTeam()); table.setTableHeader(null); table.packAll(); } /** * test if max parameter is respected. * */ @Test public void testPackColumnWithMax() { JXTable table = new JXTable(new AncientSwingTeam()); TableColumnExt columnExt = table.getColumnExt(0); table.getColumnFactory().packColumn(table, columnExt, -1, -1); int prefWidth = columnExt.getPreferredWidth(); assertTrue("sanity: ", prefWidth > 10); int max = prefWidth - 5; table.getColumnFactory().packColumn(table, columnExt, -1, max); assertEquals("pref width must be bounded by max", max, columnExt.getPreferredWidth()); } /** * packColumn can't handle hidden columns. * */ @Test public void testPackHiddenColumn() { JXTable table = new JXTable(10, 4); TableColumnExt columnExt = table.getColumnExt(0); columnExt.setVisible(false); try { table.getColumnFactory().packColumn(table, columnExt, -1, -1); fail("packColumn is doc'ed to not handle hidden columns"); } catch (IllegalStateException e) { // expected } } /** * test that configure throws exceptions as doc'ed. * Here: model index == negative * */ @Test public void testConfigureTableColumnDoc() { TableModel model = new DefaultTableModel(0, 4); TableColumnExt columnExt = new TableColumnExt(-1); try { ColumnFactory.getInstance().configureTableColumn(model, columnExt); fail("factory must throw on illegal column model index " + columnExt.getModelIndex()); } catch (IllegalStateException e) { // nothing to do - that's the doc'ed behaviour } } /** * test that configure throws exceptions as doc'ed. * Here: model index == getColumnCount * */ @Test public void testConfigureTableColumnExcessModelIndex() { TableModel model = new DefaultTableModel(0, 4); TableColumnExt columnExt = new TableColumnExt(model.getColumnCount()); try { ColumnFactory.getInstance().configureTableColumn(model, columnExt); fail("factory must throw on illegal column model index " + columnExt.getModelIndex()); } catch (IllegalStateException e) { // nothing to do - that's the doc'ed behaviour } } /** * For completeness: formally test that app-wide factory * is used by JXTable. * */ @Test public void testSetColumnFactory() { ColumnFactory myFactory = new ColumnFactory(); ColumnFactory.setInstance(myFactory); JXTable table = new JXTable(); assertSame(myFactory, table.getColumnFactory()); } /** * Issue #470-swingx: added getRowCount(table) * */ @Test public void testEncapsulateRowCount() { final int cutOffRowCount = 10; ColumnFactory factory = new ColumnFactory() { @Override protected int getRowCount(JXTable table) { return cutOffRowCount; } }; DefaultTableModel model = new DefaultTableModel(cutOffRowCount * 2, 2) { @Override public Object getValueAt(int row, int column) { if (row >= cutOffRowCount) { throw new IllegalArgumentException("Illegal access to cutoff rows"); } return super.getValueAt(row, column); } }; JXTable table = new JXTable(); table.setColumnFactory(factory); table.setModel(model); factory.packColumn(table, table.getColumnExt(0), -1, -1); } /** * Issue #315-swingx: pack doesn't pass column index to headerRenderer. * This bug shows only if the renderer relies on the column index (default doesn't). */ @Test public void testPackColumnIndexToHeaderRenderer() { final int special = 1; TableCellRenderer renderer = new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (column == special) { value = "exxxxttteeeed" + value; } super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); return this; } }; JXTable table = new JXTable(1, 2); table.getTableHeader().setDefaultRenderer(renderer); TableColumnExt columnExt = table.getColumnExt(special); table.packAll(); int realPrefWidth = 2 * 4 // magic value - JXTable's default margin, // needs to be made configurable, see Issue ?? + renderer.getTableCellRendererComponent(table, columnExt.getHeaderValue(), false, false, -1, special).getPreferredSize().width; assertEquals(realPrefWidth, columnExt.getPreferredWidth()); } /** * Issue #266-swingx: support customization of pack margin. * * added property to ColumnFactory. * */ @Test public void testPackMargin() { final int special = 1; JXTable table = new JXTable(1, 2); ColumnFactory factory = new ColumnFactory(); table.setColumnFactory(factory); table.setValueAt("something that's wider than 75", 0, special); TableColumnExt columnExt = table.getColumnExt(special); table.packAll(); TableCellRenderer renderer = table.getCellRenderer(0, special); Component comp = table.prepareRenderer(renderer, 0, special); int realPrefWidth = 2 * factory.getDefaultPackMargin() // magic value - JXTable's default margin, // needs to be made configurable, see Issue 266 + comp.getPreferredSize().width; // sanity - default margin kicks in assertEquals(realPrefWidth, columnExt.getPreferredWidth()); int margin = 10; factory.setDefaultPackMargin(margin); table.packAll(); table.prepareRenderer(renderer, 0, special); int otherPrefWidth = 2 * margin + comp.getPreferredSize().width; assertEquals(otherPrefWidth, columnExt.getPreferredWidth()); } } swingx-1.0-src/src/test/org/jdesktop/swingx/table/TableColumnExtIssues.java0000644000175000017500000001410011210401722025717 0ustar tonytony/* * $Id: TableColumnExtIssues.java,v 1.13 2008/08/01 13:31:33 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.table; import java.beans.PropertyChangeListener; import java.io.IOException; import javax.swing.table.TableColumn; import junit.framework.TestCase; import org.jdesktop.test.PropertyChangeReport; import org.jdesktop.test.SerializableSupport; /** * Test to exposed known issues of TableColumnExt. * * Ideally, there would be at least one failing test method per open * Issue in the issue tracker. Plus additional failing test methods for * not fully specified or not yet decided upon features/behaviour. * * @author Jeanette Winzenburg */ public class TableColumnExtIssues extends TestCase { /** * Issue #815-swingx: Listeners must not be cloned. * Test that a listener registered with the clone is not registered * with the original. */ public void testListenersOriginalNotRegistered() { TableColumnCloneable column = new TableColumnCloneable(); column.setPreferredWidth(column.getMinWidth()); int old = column.getPropertyChangeListeners().length; assertEquals("sanity, no listener", 0, old); TableColumnCloneable clone = (TableColumnCloneable) column.clone(); PropertyChangeReport report = new PropertyChangeReport(); clone.addPropertyChangeListener(report); assertEquals(old, column.getPropertyChangeListeners().length); } /** * Issue #815-swingx: Listeners must not be cloned. * test that listeners registered with the original are not notified * when changing the clone. */ public void testListenerNotificationCloneChanged() { TableColumnCloneable column = new TableColumnCloneable(); column.setPreferredWidth(column.getMinWidth()); PropertyChangeReport report = new PropertyChangeReport(); column.addPropertyChangeListener(report); TableColumnCloneable clone = (TableColumnCloneable) column.clone(); clone.setPreferredWidth(column.getPreferredWidth() + 10); assertEquals(0, report.getEventCount()); } /** * Issue #815-swingx: Listeners must not be cloned. * Test that the listeners are still registered to the old. */ public void testListenersOriginalRegistered() { TableColumnCloneable column = new TableColumnCloneable(); PropertyChangeReport report = new PropertyChangeReport(); column.addPropertyChangeListener(report); int old = column.getPropertyChangeListeners().length; column.clone(); assertEquals(old, column.getPropertyChangeListeners().length); } /** * Try a TableColumn sub with a better-behaved clone - removes the cloned listeners. * * Doesn't help: the listeners are removed from the original as well. The problem * is in core - it doesn't provide a well-behaved clone implementation (in fact, it * doesn't provide any implementation). With the private listener registering there * is nothing subclasses can do. Except not implement cloneable (which is the best * to do anyway, see Bloch) */ public static class TableColumnCloneable extends TableColumn implements Cloneable { @Override public Object clone() { try { TableColumn column = (TableColumn) super.clone(); PropertyChangeListener[] listeners = getPropertyChangeListeners(); for (PropertyChangeListener listener : listeners) { column.removePropertyChangeListener(listener); } return column; } catch (CloneNotSupportedException e) { // don't expect } return null; } } /** * Issue #??-swingx: tableColumnExt does not fire propertyChange on resizable. * * Happens, if property is changed indirectly by changing min/max value * to be the same. * */ public void testResizableBoundProperty() { TableColumnExt columnExt = new TableColumnExt(); // sanity: assert expected defaults of resizable, minWidth assertTrue(columnExt.getResizable()); assertTrue(columnExt.getMinWidth() > 0); PropertyChangeReport report = new PropertyChangeReport(); columnExt.addPropertyChangeListener(report); columnExt.setMaxWidth(columnExt.getMinWidth()); if (!columnExt.getResizable()) { assertEquals("fixing column widths must fire resizable ", 1, report.getEventCount("resizable")); } else { fail("resizable must respect fixed column width"); } } /** * Sanity test Serializable: Listeners? Report not serializable? * * @throws ClassNotFoundException * @throws IOException * */ public void testSerializable() throws IOException, ClassNotFoundException { TableColumnExt columnExt = new TableColumnExt(); PropertyChangeReport report = new PropertyChangeReport(); columnExt.addPropertyChangeListener(report); TableColumnExt serialized = SerializableSupport.serialize(columnExt); PropertyChangeListener[] listeners = serialized .getPropertyChangeListeners(); assertTrue(listeners.length > 0); } /** * Issue #??-swingx: must handle non-serializable client properties * gracefully. * * @throws ClassNotFoundException * @throws IOException * * */ public void testNonSerializableClientProperties() throws IOException, ClassNotFoundException { TableColumnExt columnExt = new TableColumnExt(); Object value = new Object(); columnExt.putClientProperty("date", value ); SerializableSupport.serialize(columnExt); } /** * Dummy stand-in test method, does nothing. * without, the test would fail if there are no open issues. * */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/table/ColumnHeaderRendererTest.java0000644000175000017500000000640511210401722026543 0ustar tonytony/* * $Id: ColumnHeaderRendererTest.java,v 1.5 2008/10/11 20:42:33 rah003 Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.table; import java.awt.BorderLayout; import java.util.logging.Logger; import javax.swing.JTable; import javax.swing.JTextField; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXTable; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * Test ColumnHeaderRenderer. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class ColumnHeaderRendererTest extends InteractiveTestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger .getLogger(ColumnHeaderRendererTest.class.getName()); public static void main(String args[]) { ColumnHeaderRendererTest test = new ColumnHeaderRendererTest(); setSystemLF(true); try { test.runInteractiveTests(); // test.runInteractiveTests(".*Create.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * hack around big vista border. * */ public void interactiveVistaTableHeader() { final JTextField field = new JTextField(); // sanity: custom borders untouched // Border customBorder = BorderFactory.createEmptyBorder(20, 20, 20, 20); // UIManager.put(ColumnHeaderRenderer.VISTA_BORDER_HACK, customBorder); JXTable xTable = new JXTable(10, 3); JTable table = new JTable(xTable.getModel()); JXFrame frame = wrapWithScrollingInFrame(xTable, table, "JXTable <-> JTable: compare header height"); frame.add(field, BorderLayout.SOUTH); show(frame); } /** * Issue #540-swingx: sort icon in custom header renderer * not updated to ui. Reason was that the empty constructor * didn't load the ui-specific ion. * */ public void interactiveHeaderRendererCreate() { JXTable table = new JXTable(10, 2); ColumnHeaderRenderer renderer = new ColumnHeaderRenderer(); table.getColumnExt(1).setHeaderRenderer(renderer); showWithScrollingInFrame(table, "sortIcon in second column wrong"); } @Test public void testDummy() { // keep the test framework happy } } swingx-1.0-src/src/test/org/jdesktop/swingx/table/TableColumnModelExtIssues.java0000644000175000017500000001057411210401722026713 0ustar tonytony/* * Created on 24.08.2006 * */ package org.jdesktop.swingx.table; import java.awt.event.ActionEvent; import java.util.Collection; import java.util.List; import javax.swing.Action; import javax.swing.table.TableColumn; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.action.AbstractActionExt; /** * Test to exposed known issues of TableColumnModelExt * implementations. * * Ideally, there would be at least one failing test method per open * Issue in the issue tracker. Plus additional failing test methods for * not fully specified or not yet decided upon features/behaviour. * * @author Jeanette Winzenburg */ public class TableColumnModelExtIssues extends TableColumnModelTest { public static void main(String args[]) { setSystemLF(false); TableColumnModelExtIssues test = new TableColumnModelExtIssues(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Column.*"); // test.runInteractiveTests("interactive.*TableHeader.*"); // test.runInteractiveTests("interactive.*SorterP.*"); // test.runInteractiveTests("interactive.*Column.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #624-swingx: support use-case to store/restore column sequence. */ public void interactiveRestoreColumnOrder() { final JXTable source = new JXTable(20, 5); source.setColumnControlVisible(true); final JXTable target = new JXTable(source.getModel()); target.setColumnControlVisible(true); JXFrame frame = wrapWithScrollingInFrame(source, target, "source --> target: copy column sequence"); Action resetOrder = new AbstractActionExt("reset to initial") { public void actionPerformed(ActionEvent e) { source.tableChanged(null); target.tableChanged(null); } }; Action copyOrder = new AbstractActionExt("copy source order to target") { public void actionPerformed(ActionEvent e) { // source ... // hidden columns, don't care about sequence Collection hiddenSourceColumns = source.getColumns(true); hiddenSourceColumns.removeAll(source.getColumns()); // temporary set visible so we can get hold of their "virtual" // view index for (TableColumn tableColumn : hiddenSourceColumns) { ((TableColumnExt) tableColumn).setVisible(true); } // target Collection hiddenTargetColumns = target.getColumns(true); hiddenTargetColumns.removeAll(target.getColumns()); for (TableColumn tableColumn : hiddenTargetColumns) { ((TableColumnExt) tableColumn).setVisible(true); } // visible sequence if all were visible List sourceColumns = source.getColumns(); for (int i = 0; i < sourceColumns.size(); i++) { int sourceID = sourceColumns.get(i).getModelIndex(); List targetColumns = target.getColumns(); for (int j = 0; j < targetColumns.size(); j++) { if (targetColumns.get(j).getModelIndex() == sourceID) { target.getColumnModel().moveColumn(j, i); break; } } } // cleanup: hide originally hidden columns for (TableColumn tableColumn : hiddenSourceColumns) { ((TableColumnExt) tableColumn).setVisible(false); } for (TableColumn tableColumn : hiddenTargetColumns) { ((TableColumnExt) tableColumn).setVisible(false); } } }; addAction(frame, resetOrder); addAction(frame, copyOrder); frame.pack(); frame.setVisible(true); } /** * Do nothing, just to make the runner happy if there are no * issues. * */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/table/ColumnHeaderRendererIssues.java0000644000175000017500000003665511210401722027111 0ustar tonytony/* * $Id: ColumnHeaderRendererIssues.java,v 1.14 2008/12/16 09:54:51 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.table; import java.awt.event.ActionEvent; import java.util.logging.Logger; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.LookAndFeel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.plaf.UIResource; import javax.swing.plaf.metal.MetalBorders; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTableHeader; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.test.XTestUtils; import org.jdesktop.swingx.util.JVM; import org.jdesktop.swingx.util.OS; /** * Test for known issues with ColumnHeaderRenderer. * * @author Jeanette Winzenburg */ public class ColumnHeaderRendererIssues extends InteractiveTestCase { private static final Logger LOG = Logger .getLogger(ColumnHeaderRendererIssues.class.getName()); public static void main(String args[]) { ColumnHeaderRendererIssues test = new ColumnHeaderRendererIssues(); setSystemLF(true); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*LF.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #337-swingx: test hack around Metals tableHeaderBorder not respecting * insets. * * ColumnHeaderRendererAddon should install a custom border. * * Here: test that the addon installs/uninstalls a border as uiresource. * * */ public void testMetalHeaderBorderDefault() throws Exception { LookAndFeel old = UIManager.getLookAndFeel(); // force addon loading @SuppressWarnings("unused") ColumnHeaderRenderer renderer = new ColumnHeaderRenderer(); // be sure to install cross-platform LF try { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); if (hasMetalBordersTableHeaderBorder()) { Border border = UIManager.getBorder(ColumnHeaderRenderer.METAL_BORDER_HACK); assertNotNull("metal hack border must be installed", border); assertTrue("metal hack border must be UIResource", border instanceof UIResource); // be sure to install crossplatform LF // not really safe - blows if system == cross-platform // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // Border noborder = UIManager.getBorder(ColumnHeaderRenderer.METAL_BORDER_HACK); // assertNull("metal hack border must be un-installed", noborder); } else { LOG.info("metalHaderBorderHack not run: cross-platform does not default the MetalBorders"); } } finally { // revert to default LF UIManager.setLookAndFeel(old); } } /** * @return */ private boolean hasMetalBordersTableHeaderBorder() { return UIManager.getBorder("TableHeader.cellBorder") instanceof MetalBorders.TableHeaderBorder; } /** * Test hack around Vista's tableHeader too big. * ColumnHeaderRendererAddon should install a smaller custom border on * Vista and jdk5. Core issue is fixed in jdk6 (u10, but as that's final now ...) * * Here: test that the addon installs/uninstalls a border as uiresource. * * Hmm ... how to test against different windows versions? Classic/(XP?) under * the hood of Vista? * */ public void testVistaHeaderBorderDefault() throws Exception { if (!OS.isWindowsVista() || !UIManager.getSystemLookAndFeelClassName().contains("Windows")) { LOG.info("cannot run VistaHeaderBorder - no Vista system"); return; } if (!JVM.current().isOneDotFive()) { LOG.info("cannot run VistaHeaderBorder - no jvm1.5"); return; } LookAndFeel old = UIManager.getLookAndFeel(); // force addon loading @SuppressWarnings("unused") ColumnHeaderRenderer renderer = new ColumnHeaderRenderer(); // be sure to install system LF try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); Border border = UIManager.getBorder(ColumnHeaderRenderer.VISTA_BORDER_HACK); assertNotNull("vista hack border must be installed", border); assertTrue("vista hack border must be UIResource", border instanceof UIResource); // be sure to install crossplatform LF UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); Border noborder = UIManager.getBorder(ColumnHeaderRenderer.VISTA_BORDER_HACK); assertNull("vista hack border must be un-installed", noborder); } finally { // revert to default LF UIManager.setLookAndFeel(old); } } /** * test hack around Vista's tableHeader too big. * ColumnHeaderRendererAddon should install a smaller custom border. * * Here: test that addon doesn't touch a custom border. * * Hmm ... how to test against different windows versions? Classic/(XP?) under * the hood of Vista? * */ public void testVistaHeaderBorderCustom() throws Exception { if (!OS.isWindowsVista() || !UIManager.getSystemLookAndFeelClassName().contains("Windows")) { LOG.info("cannot run VistaHeaderBorder - no Vista system"); return; } if (!JVM.current().isOneDotFive()) { LOG.info("cannot run VistaHeaderBorder - no jvm1.5"); return; } LookAndFeel old = UIManager.getLookAndFeel(); // force addon loading @SuppressWarnings("unused") ColumnHeaderRenderer renderer = new ColumnHeaderRenderer(); // be sure to install system LF try { Border customBorder = BorderFactory.createEmptyBorder(20, 20, 20, 20); UIManager.put(ColumnHeaderRenderer.VISTA_BORDER_HACK, customBorder); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); assertEquals("custom border must be untouched", customBorder, UIManager.getBorder(ColumnHeaderRenderer.VISTA_BORDER_HACK)); // be sure to install crossplatform LF UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); assertSame("custom border must be untouched", UIManager.getBorder(ColumnHeaderRenderer.VISTA_BORDER_HACK), customBorder); } finally { // revert to default LF UIManager.put(ColumnHeaderRenderer.VISTA_BORDER_HACK, null); UIManager.setLookAndFeel(old); } } /** * Vista border is kept when switching (on OS level) between vista * and classic mode. * * TODO check on XP for core bug: * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6429812 * here no problem, JXTableHeader tries hard to update LF-provided * renderer. */ public void interactiveLFHeaderRenderer() { final JXTable table = new JXTable(20, 5); JTable core = new JTable(20, 5); final JXFrame frame = wrapWithScrollingInFrame(table, core, "LF provided renderer"); Action toggleLF = new AbstractActionExt("toggleLF") { public void actionPerformed(ActionEvent e) { try { toggleLAF(); SwingUtilities.updateComponentTreeUI(frame); } catch (Exception e1) { LOG.info("error when toggling LF - ignore"); } finally { LOG.info("current LF: " + UIManager.getLookAndFeel()); } } }; Action reloadLF = new AbstractActionExt("reloadLF") { public void actionPerformed(ActionEvent e) { SwingUtilities.updateComponentTreeUI(frame); } }; addAction(frame, toggleLF); addAction(frame, reloadLF); frame.pack(); frame.setVisible(true); } private void toggleLAF() throws Exception { LookAndFeel laf = UIManager.getLookAndFeel(); if (laf == null || laf.isNativeLookAndFeel()) { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } else { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } } /** * Issue #??-jdnc: configure header/column to show icon. * * Icon as header value not used. (Showing resource location) */ public void interactiveHeaderIcon() { final JXTable table = new JXTable(); // table.setAutoCreateRowSorter(false); ColumnFactory factory = new ColumnFactory() { @Override public void configureTableColumn(TableModel model, TableColumnExt columnExt) { super.configureTableColumn(model, columnExt); if (columnExt.getModelIndex() == 1) { // default can't cope columnExt.setHeaderValue(XTestUtils.loadDefaultIcon()); } } }; table.setColumnFactory(factory); table.setModel(new DefaultTableModel(new String[]{"first", "second", "third"}, 10)); JScrollPane pane = new JScrollPane(table); table.setColumnControlVisible(true); final JXFrame frame = wrapInFrame(pane, "Icon as column header value (not mapped)"); frame.setVisible(true); } /** * Issue #??-jdnc: configure header/column to show icon. * * We try to set an icon on second column only. We see the icon on * all columns. * * All: * don't handle header values of icon type by default * label properties not reset on each call (which produces * problems with the shared ui-provided renderer) * * Mustang: * duplicate sort icon (when using swingx sorting) * custom icon overpaints sort icon (when using 1.6 sorting) * * Note: this method makes sense only if * compiled, run under 1.6 (and the Mustang api uncommented) */ public void interactiveHeaderIconMustang() { final JXTable table = new JXTable(); // un-comment to see Mustang effect // table.setSortable(false); // table.setAutoCreateRowSorter(true); ColumnFactory factory = new ColumnFactory() { @Override public void configureTableColumn(TableModel model, TableColumnExt columnExt) { super.configureTableColumn(model, columnExt); if (columnExt.getModelIndex() == 1) { // default can't cope // columnExt.setHeaderValue(XTestUtils.loadDefaultIcon()); // columnExt.setHeaderValue(null); // not working - column renderer doesn't reset shared renderers state! ColumnHeaderRenderer renderer = new ColumnHeaderRenderer(table.getTableHeader()); renderer.setIcon(XTestUtils.loadDefaultIcon()); columnExt.setHeaderRenderer(renderer); } } }; table.setColumnFactory(factory); table.setModel(new DefaultTableModel(new String[]{"first", "second", "third"}, 10)); JScrollPane pane = new JScrollPane(table); table.setColumnControlVisible(true); showInFrame(pane, "Icon on second header - Mustang sort icon"); } /** * Issue #79-jdnc: leading/trailing (?) doesn't work. * */ public void interactiveHeaderAlignment() { final String[] alignText = {"default", "center", "leading", "left", "trailing", "right"}; final int[] align = {-1, JLabel.CENTER, JLabel.LEADING, JLabel.LEFT, JLabel.TRAILING, JLabel.RIGHT}; ColumnFactory factory = new ColumnFactory() { @Override public void configureTableColumn(TableModel model, TableColumnExt columnExt) { super.configureTableColumn(model, columnExt); int columnIndex = columnExt.getModelIndex(); columnExt.setHeaderValue(alignText[columnIndex]); ColumnHeaderRenderer renderer = ColumnHeaderRenderer.createColumnHeaderRenderer(); if (align[columnIndex] >= 0) { renderer.setHorizontalAlignment(align[columnIndex]); } columnExt.setHeaderRenderer(renderer); } }; final JXTable table = new JXTable(); table.setColumnFactory(factory); table.setModel(new DefaultTableModel(10, alignText.length)); JScrollPane pane = new JScrollPane(table); table.setColumnControlVisible(true); final JXFrame frame = wrapInFrame(pane, "RToL and column text alignment, trailing/leading"); addComponentOrientationToggle(frame); show(frame); } /** * Hook into the UI-provided renderer to set the * alignment of all columns. Note: this is not * bidi compliant, as of Issue #79-jdnc: leading/trailing * don't get updated on orientation toggle. * */ public void interactiveHeaderAlignmentAllRight() { final JXTable table = new JXTable(); JXTableHeader header = (JXTableHeader) table.getTableHeader(); TableCellRenderer renderer = header.getDefaultRenderer(); if (renderer instanceof ColumnHeaderRenderer) { ColumnHeaderRenderer columnRenderer = (ColumnHeaderRenderer) renderer; columnRenderer.setHorizontalAlignment(JLabel.RIGHT); } table.setModel(new DefaultTableModel(10, 6)); JScrollPane pane = new JScrollPane(table); table.setColumnControlVisible(true); final JXFrame frame = wrapInFrame(pane, "RToL and column text alignment RIGHT"); addComponentOrientationToggle(frame); show(frame); } /** * Do nothing, make the test runner happy * (would output a warning without a test fixture). * */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/table/DatePickerCellEditorVisualCheck.java0000644000175000017500000002250411210401722027750 0ustar tonytony/* * $Id: DatePickerCellEditorVisualCheck.java,v 1.10 2008/07/29 12:52:44 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.table; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.text.DateFormat; import java.text.ParseException; import java.util.Date; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.DefaultCellEditor; import javax.swing.JComboBox; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.table.DefaultTableModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellEditor; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeModel; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXDatePicker; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTree; import org.jdesktop.swingx.tree.DefaultXTreeCellEditor; public class DatePickerCellEditorVisualCheck extends InteractiveTestCase { public static void main(String[] args) { // setSystemLF(true); DatePickerCellEditorVisualCheck test = new DatePickerCellEditorVisualCheck(); try { test.runInteractiveTests(); // test.runInteractiveTests(".*Text.*"); // test.runInteractiveTests(".*XTree.*"); // test.runInteractiveTests(".*Table.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * visualize datepicker editing of the hierarchical column, both * in a tree and a xTree switching CO. * * standard editor */ public void interactiveTreeEditingRToLDatePicker() { TreeModel model = createTreeModelWithDates(); JTree tree = new JTree(model); tree.setEditable(true); tree.setCellEditor(new DefaultTreeCellEditor(tree, null, new DatePickerCellEditor())); JXTree xTree = new JXTree(model); xTree.setEditable(true); xTree.setCellEditor(new DefaultTreeCellEditor(tree, null, new DatePickerCellEditor())); final JXFrame frame = wrapWithScrollingInFrame(tree, xTree, "standard Editing (DatePicker): compare tree and xtree"); addComponentOrientationToggle(frame); show(frame); } /** * @return */ private TreeModel createTreeModelWithDates() { DefaultMutableTreeNode root = new DefaultMutableTreeNode(new Date()); root.add(new DefaultMutableTreeNode(new Date())); TreeModel model = new DefaultTreeModel(root); return model; } /** * visualize date picker editing of the hierarchical column, both * in a tree and a xTree switching CO. * using DefaultXTreeCellEditor. */ public void interactiveXTreeEditingRToLDatePicker() { TreeModel model = createTreeModelWithDates(); JTree tree = new JTree(model); tree.setEditable(true); tree.setCellEditor(new DefaultXTreeCellEditor(tree, null, new DatePickerCellEditor())); JXTree xTree = new JXTree(model); xTree.setEditable(true); xTree.setCellEditor(new DefaultXTreeCellEditor(xTree, null, new DatePickerCellEditor())); final JXFrame frame = wrapWithScrollingInFrame(tree, xTree, "XEditing(DatePicker): compare tree and xtree"); addComponentOrientationToggle(frame); show(frame); } /** * Issue ??-swingx: picker cell editor popup commit/cancel * transfers focus out-off the table (1.5) * * Looks like a core issue - editable combo misbehaves as well. * Here we use a JXTable. */ public void interactiveDatePickerCellEditorXTable() { final JXTable table = new JXTable(createTableModel(2)); table.setVisibleColumnCount(6); // table.setSurrendersFocusOnKeystroke(true); installEditors(table); Action action = new AbstractAction("toggle terminate") { public void actionPerformed(ActionEvent e) { table.setTerminateEditOnFocusLost(!table.isTerminateEditOnFocusLost()); } }; JXFrame frame = wrapWithScrollingInFrame(table, "JXTable - date picker cell editor"); addAction(frame, action); frame.add(new JXDatePicker(), BorderLayout.SOUTH); show(frame); } /** * Issue ??-swingx: picker cell editor popup commit/cancel * transfers focus out-off the tree (1.5) * * * a) commit by keyboard - commit okay but focus moved where? * b) click into popup to commit - did not commit. * Now fixed (CellEditorRemover copes with popup) okay committed, * but focus where (as in a)? * c) click on month navigation - editing canceled fixed. * d) click in month navigation, then cancel by keyboard - * focus where? * * focus handling is done in BasicTreeUI.completeEditing - and * does not cope with popup. All termination is done in uidelegate, * no central method in the tree called. * * independent on stopCellEditing flag - semantic in tree is * different from semantic in table (first is "how" to terminate, * second is "if" to terminate) * */ public void interactiveDatePickerCellEditorXTree() { final JXTree tree = new JXTree(createTreeModelWithDates()); tree.setEditable(true); tree.setCellEditor(new DefaultXTreeCellEditor(tree, null, new DatePickerCellEditor())); Action action = new AbstractAction("toggle terminate") { public void actionPerformed(ActionEvent e) { tree.setInvokesStopCellEditing(!tree.getInvokesStopCellEditing()); } }; JXFrame frame = wrapWithScrollingInFrame(tree, "JXTree - date picker cell editor"); addAction(frame, action); frame.add(new JTextField("yet another thing to focus"), BorderLayout.SOUTH); show(frame); } /** * Issue ??-swingx: picker cell editor popup commit/cancel * transfers focus out-off the table (1.5) * * Looks like a core issue - editable combo misbehaves as well. * Here we use a core table. */ public void interactiveDatePickerCellEditorTable() { JTable table = new JTable(createTableModel(2)); table.putClientProperty("terminateEditOnFocusLost", true); installEditors(table); JXFrame frame = wrapWithScrollingInFrame(table, "JTable - date picker cell editor"); frame.add(new JTextField("yet another thing to focus"), BorderLayout.SOUTH); show(frame); } /** * @param table */ private void installEditors(JTable table) { table.setDefaultEditor(Date.class, new DatePickerCellEditor(DateFormat.getDateInstance())); JComboBox box = new JComboBox(new String[] {"item1", "item2", "item3"}); box.setEditable(true); table.getColumnModel().getColumn(1).setCellEditor( new DefaultCellEditor(box)); } /** * @return */ private DefaultTableModel createTableModel(int rows) { Object[] columns = new Object[]{"Date", "editable combo", "simple field"}; DefaultTableModel model = new DefaultTableModel(rows, columns.length) { @Override public Class getColumnClass(int columnIndex) { if (getRowCount() > 0) { Object value = getValueAt(0, columnIndex); if (value != null) { return value.getClass(); } } return super.getColumnClass(columnIndex); } }; model.setColumnIdentifiers(columns); Date date = new Date(); model.setValueAt(date, 0, 0); model.setValueAt("selectedItem", 0, 1); return model; } /** * Test Picker's value --> date mapping strategy. * @throws ParseException * failing on server due to parseException (format issue?) * */ public void testDateEditorValueAsDate() throws ParseException { DatePickerCellEditor editor = new DatePickerCellEditor(); Date input = new Date(); String dateString = editor.getFormats()[0].format(input); Date fullCycle = editor.getFormats()[0].parse(dateString); assertEquals("the formatted input date string must be same", fullCycle, editor.getValueAsDate(dateString)); } } swingx-1.0-src/src/test/org/jdesktop/swingx/table/TableColumnModelTest.java0000644000175000017500000005030111210401724025670 0ustar tonytony/* * $Id: TableColumnModelTest.java,v 1.20 2008/10/11 20:42:33 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.table; import java.beans.PropertyChangeEvent; import java.util.logging.Logger; import javax.swing.event.ChangeEvent; import javax.swing.event.ListSelectionEvent; import javax.swing.event.TableColumnModelEvent; import javax.swing.event.TableColumnModelListener; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.event.TableColumnModelExtListener; import org.jdesktop.swingx.test.ColumnModelReport; import org.jdesktop.test.TestUtils; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * Skeleton to unit test DefaultTableColumnExt. * * Incomplete list of issues to test: * fired added after setVisible(true) * behaviour when adding/removing invisible columns * selection state * * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class TableColumnModelTest extends InteractiveTestCase { @SuppressWarnings("all") private static final Logger LOG = Logger .getLogger(TableColumnModelTest.class.getName()); protected static final int COLUMN_COUNT = 3; /** * added api to get array of ext listeners */ @Test public void testGetTableColumnModelExtListener() { // any tableColumnModelExtListener will do JXTable table = new JXTable(); DefaultTableColumnModelExt columnModel = (DefaultTableColumnModelExt) createColumnModel(COLUMN_COUNT); columnModel.addColumnModelListener(table); TableColumnModelExtListener[] listeners = columnModel.getTableColumnModelExtListeners(); assertEquals(1, listeners.length); assertEquals(table, listeners[0]); } /** * Issue #867-swingx: internal book-keeping must not be routed via columnModel * column propertyChange

* test the change from visible to hidden. */ @Test public void testTableColumnIgnoreNoPropertyNotificationHide() { TableColumnModelExt columnModel = createColumnModel(COLUMN_COUNT); ColumnModelReport report = new ColumnModelReport(); columnModel.addColumnModelListener(report); columnModel.getColumnExt(0).setVisible(false); assertEquals("ignore events must not be routed", 0, report.getColumnPropertyEventCount( "TableColumnModelExt.ignoreEvent")); } /** * Issue #867-swingx: internal book-keeping must not be routed via columnModel * column propertyChange

* test the change from hidden to visible. */ @Test public void testTableColumnIgnoreNoPropertyNotificationShow() { TableColumnModelExt columnModel = createColumnModel(COLUMN_COUNT); columnModel.getColumnExt(0).setVisible(false); ColumnModelReport report = new ColumnModelReport(); columnModel.addColumnModelListener(report); columnModel.getColumnExt(0).setVisible(true); assertEquals("ignore events must not be routed", 0, report.getColumnPropertyEventCount( "TableColumnModelExt.ignoreEvent")); } /** * Issue #369-swingx: properties of hidden columns are not fired.

* test the change from visible to hidden. */ @Test public void testHideTableColumnPropertyNotification() { TableColumnModelExt columnModel = createColumnModel(COLUMN_COUNT); ColumnModelReport report = new ColumnModelReport(); columnModel.addColumnModelListener(report); columnModel.getColumnExt(0).setVisible(false); TestUtils.assertPropertyChangeEvent(report.getPropertyChangeReport(), "visible", true, false); } /** * Issue #846-swingx */ @Test public void testIsAddedFromInvisibleTrue() { final DefaultTableColumnModelExt columnModel = (DefaultTableColumnModelExt) createColumnModel(3); TableColumnExt columnB = columnModel.getColumnExt(1); columnB.setVisible(false); // can't use report: the isRemovedToInvisible is valid during notification only TableColumnModelListener report = new TableColumnModelListener() { public void columnAdded(TableColumnModelEvent e) { int fromIndex = e.getToIndex(); assertEquals("old column really removed", true, columnModel.isAddedFromInvisibleEvent(fromIndex)); // note: the toIndex here is always the last // following are moves to position before hiding } public void columnRemoved(TableColumnModelEvent e) {} public void columnMarginChanged(ChangeEvent e) { } public void columnMoved(TableColumnModelEvent e) {} public void columnSelectionChanged(ListSelectionEvent e) {} }; columnModel.addColumnModelListener(report); columnB.setVisible(true); // sanity testing internals: marker client property removed assertEquals("ignoreEvents marker must be null", null, columnB.getClientProperty("TableColumnModelExt.ignoreEvent")); } /** * Issue #846-swingx */ @Test public void testIsRemovedToInvisibleFalse() { final DefaultTableColumnModelExt columnModel = (DefaultTableColumnModelExt) createColumnModel(3); TableColumnExt columnB = columnModel.getColumnExt(1); columnModel.getColumnExt(0).setVisible(false); // can't use report: the isRemovedToInvisible is valid during notification only TableColumnModelListener report = new TableColumnModelListener() { public void columnRemoved(TableColumnModelEvent e) { int fromIndex = e.getFromIndex(); assertEquals("old visible index of removed", 0, fromIndex); assertEquals("old column really removed", false, columnModel.isRemovedToInvisibleEvent(fromIndex)); } public void columnAdded(TableColumnModelEvent e) {} public void columnMarginChanged(ChangeEvent e) { } public void columnMoved(TableColumnModelEvent e) {} public void columnSelectionChanged(ListSelectionEvent e) {} }; columnModel.addColumnModelListener(report); columnModel.removeColumn(columnB); // sanity testing internals: marker client property removed assertEquals("ignoreEvents marker must be null", null, columnB.getClientProperty("TableColumnModelExt.ignoreEvent")); } /** * Issue #846-swingx */ @Test public void testIsRemovedToInvisibleTrue() { final DefaultTableColumnModelExt columnModel = (DefaultTableColumnModelExt) createColumnModel(3); final int index = 2; TableColumnExt columnB = columnModel.getColumnExt(index); // can't use report: the isRemovedToInvisible is valid during notification only TableColumnModelListener report = new TableColumnModelListener() { public void columnRemoved(TableColumnModelEvent e) { int fromIndex = e.getFromIndex(); assertEquals("old visible index of removed", index, fromIndex); assertEquals("moved to invisible", true, columnModel.isRemovedToInvisibleEvent(fromIndex)); } public void columnAdded(TableColumnModelEvent e) {} public void columnMarginChanged(ChangeEvent e) { } public void columnMoved(TableColumnModelEvent e) {} public void columnSelectionChanged(ListSelectionEvent e) {} }; columnModel.addColumnModelListener(report); columnB.setVisible(false); // sanity testing internals: marker client property removed assertEquals("ignoreEvents marker must be null", null, columnB.getClientProperty("TableColumnModelExt.ignoreEvent")); } /** * Issue #369-swingx: properties of hidden columns are not fired.

* test the change from hidden to visible. */ @Test public void testShowTableColumnPropertyNotification() { TableColumnModelExt columnModel = createColumnModel(COLUMN_COUNT); Object identifier = "0"; // sanity... assertNotNull(columnModel.getColumnExt(identifier)); columnModel.getColumnExt(identifier).setVisible(false); ColumnModelReport report = new ColumnModelReport(); columnModel.addColumnModelListener(report); columnModel.getColumnExt(identifier).setVisible(true); // can't use the report because of the ignore_event hack in // moveToVisible of DTCMExt - revisit: maybe no longer // needed now that the column property events are correctly // routed? TestUtils.assertPropertyChangeEvent(report.getLastColumnPropertyEvent(), "visible", false, true); } /** * Issue #369-swingx: properties of hidden columns are not fired.

* test property changes while hidden * */ @Test public void testHiddenTableColumnPropertyNotification() { TableColumnModelExt columnModel = createColumnModel(COLUMN_COUNT); String identifier = "0"; TableColumnExt columnExt = columnModel.getColumnExt(identifier); columnExt.setVisible(false); // sanity... assertNotNull(columnExt); String title = columnExt.getTitle() + "changed"; ColumnModelReport report = new ColumnModelReport(); columnModel.addColumnModelListener(report); columnExt.setIdentifier(title); TestUtils.assertPropertyChangeEvent(report.getPropertyChangeReport(), "identifier", identifier, title); } /** * Issue #253-swingx: hiding/showing columns changes column sequence. * * The test is modelled after the example code as * http://forums.java.net/jive/thread.jspa?threadID=7344. * */ @Test public void testHideShowColumns() { DefaultTableColumnModelExt model = (DefaultTableColumnModelExt) createColumnModel(10); int[] columnsToHide = new int[] { 4, 7, 6, 8, }; for (int i = 0; i < columnsToHide.length; i++) { model.getColumnExt(String.valueOf(columnsToHide[i])).setVisible(false); } // sanity: actually hidden assertEquals(model.getColumnCount(true) - columnsToHide.length, model.getColumnCount()); for (int i = 0; i < columnsToHide.length; i++) { model.getColumnExt(String.valueOf(columnsToHide[i])).setVisible(true); } // sanity: all visible again assertEquals(10, model.getColumnCount()); for (int i = 0; i < model.getColumnCount(); i++) { // the original sequence assertEquals(i, model.getColumn(i).getModelIndex()); } } /** * test sequence of visible columns after hide/move/show. * * Expected behaviour should be like in Thunderbird. * */ @Test public void testMoveColumns() { DefaultTableColumnModelExt model = (DefaultTableColumnModelExt) createColumnModel(COLUMN_COUNT); TableColumnExt columnExt = model.getColumnExt(1); columnExt.setVisible(false); model.moveColumn(1, 0); columnExt.setVisible(true); assertEquals(columnExt.getModelIndex(), model.getColumnExt(2).getModelIndex()); } /** * test the columnPropertyChangeEvent is fired as expected. * */ @Test public void testColumnPropertyChangeNotification() { DefaultTableColumnModelExt model = (DefaultTableColumnModelExt) createColumnModel(COLUMN_COUNT); ColumnModelReport report = new ColumnModelReport(); model.addColumnModelListener(report); TableColumn column = model.getColumn(0); column.setHeaderValue("somevalue"); assertEquals(1, report.getColumnPropertyEventCount()); PropertyChangeEvent event = report.getLastColumnPropertyEvent(); assertEquals(column, event.getSource()); assertEquals("headerValue", event.getPropertyName()); assertEquals("somevalue", event.getNewValue()); } /** * added TableColumnModelExtListener: test for add/remove extended listeners. * */ @Test public void testAddExtListener() { DefaultTableColumnModelExt model = (DefaultTableColumnModelExt) createColumnModel(COLUMN_COUNT); ColumnModelReport extListener = new ColumnModelReport(); model.addColumnModelListener(extListener); // JW: getListeners returns the count of exactly the given class? // assertEquals(1, model.getListeners(TableColumnModelExtListener.class).length); // assertEquals(2, model.getListeners(EventListener.class).length); // model.removeColumnModelListener(extListener); // assertEquals(0, model.getListeners(TableColumnModelExtListener.class).length); // assertEquals(0, model.getListeners(EventListener.class).length); assertEquals(1, model.getEventListenerList().getListenerCount(TableColumnModelExtListener.class)); assertEquals(2, model.getEventListenerList().getListenerCount()); model.removeColumnModelListener(extListener); assertEquals(0, model.getEventListenerList().getListenerCount(TableColumnModelExtListener.class)); assertEquals(0, model.getEventListenerList().getListenerCount()); } /** * Issue #??-swingx: incorrect isRemovedToInvisible after * removing an invisible column. * */ @Test public void testRemoveInvisibleColumn() { DefaultTableColumnModelExt model = (DefaultTableColumnModelExt) createColumnModel(COLUMN_COUNT); TableColumnExt tableColumnExt = ((TableColumnExt) model.getColumn(0)); tableColumnExt.setVisible(false); model.removeColumn(tableColumnExt); assertEquals("visible column count must be reduced", COLUMN_COUNT - 1, model.getColumns(false).size()); assertEquals("all columns count must be unchanged", COLUMN_COUNT - 1, model.getColumns(true).size()); assertFalse("removing invisible must update event cache", model.isRemovedToInvisibleEvent(0)); } @Test public void testGetColumns() { TableColumnModelExt model = createColumnModel(COLUMN_COUNT); ((TableColumnExt) model.getColumn(0)).setVisible(false); assertEquals("visible column count must be reduced", COLUMN_COUNT - 1, model.getColumns(false).size()); assertEquals("all columns count must be unchanged", COLUMN_COUNT, model.getColumns(true).size()); } /** * column count must be changed on changing * column visibility. * */ @Test public void testColumnCountOnSetInvisible() { TableColumnModel model = createColumnModel(COLUMN_COUNT); int columnCount = model.getColumnCount(); TableColumnExt column = (TableColumnExt) model.getColumn(columnCount - 1); assertTrue(column.isVisible()); column.setVisible(false); assertEquals("columnCount must be decremented", columnCount - 1, model.getColumnCount()); } /** * Issue #156: must update internal state after setting invisible. * Here: the cached totalWidth. Expect similar inconsistency * with selection. * */ @Test public void testTotalColumnWidth() { TableColumnModel model = createColumnModel(COLUMN_COUNT); int totalWidth = model.getTotalColumnWidth(); TableColumnExt column = (TableColumnExt) model.getColumn(0); int columnWidth = column.getWidth(); column.setVisible(false); assertEquals("new total width must be old minus invisible column width " + columnWidth, totalWidth - columnWidth, model.getTotalColumnWidth()); } /** * Issue #157: must fire columnRemoved after setting to invisible. * */ @Test public void testRemovedFired() { TableColumnModel model = createColumnModel(COLUMN_COUNT); ColumnModelReport l = new ColumnModelReport(); model.addColumnModelListener(l); TableColumnExt column = (TableColumnExt) model.getColumn(0); column.setVisible(false); assertTrue("must have fired columnRemoved", l.hasRemovedEvent()); } /** * Issue #157: must fire columnAdded after setting to invisible. * */ @Test public void testAddedFired() { TableColumnModel model = createColumnModel(COLUMN_COUNT); ColumnModelReport l = new ColumnModelReport(); TableColumnExt column = (TableColumnExt) model.getColumn(0); column.setVisible(false); model.addColumnModelListener(l); column.setVisible(true); assertTrue("must have fired columnRemoved", l.hasAddedEvent()); } /** * columnAdded: event.getToIndex must be valid columnIndex. * * */ @Test public void testAddInvisibleColumn() { TableColumnModel model = createColumnModel(COLUMN_COUNT); TableColumnModelListener l = new TableColumnModelListener() { public void columnAdded(TableColumnModelEvent e) { assertTrue("toIndex must be positive", e.getToIndex() >= 0); ((TableColumnModel) e.getSource()).getColumn(e.getToIndex()); } public void columnRemoved(TableColumnModelEvent e) { // TODO Auto-generated method stub } public void columnMoved(TableColumnModelEvent e) { // TODO Auto-generated method stub } public void columnMarginChanged(ChangeEvent e) { // TODO Auto-generated method stub } public void columnSelectionChanged(ListSelectionEvent e) { // TODO Auto-generated method stub } }; model.addColumnModelListener(l); // add invisible column TableColumnExt invisibleColumn = new TableColumnExt(0); invisibleColumn.setVisible(false); model.addColumn(invisibleColumn); // sanity check: add visible column model.addColumn(createTableColumnExt(0)); } /** * columnAt must work on visible columns. * */ @Test public void testColumnAt() { TableColumnModel model = createColumnModel(COLUMN_COUNT); int totalWidth = model.getTotalColumnWidth(); int lastColumn = model.getColumnIndexAtX(totalWidth - 10); assertEquals("lastColumn detected", model.getColumnCount() - 1, lastColumn); TableColumnExt column = (TableColumnExt) model.getColumn(lastColumn); column.setVisible(false); assertEquals("out of range", -1, model.getColumnIndexAtX(totalWidth - 10)); } //------------------ factory methods /** * creates and returns a TableColumnModelExt with the given number * of configured columns of type TableColumnExt. * * @param columns the number of columns to create and add to the model * @return a TableColumnModelExt filled with columns. * * @see createTableColumnExt */ protected TableColumnModelExt createColumnModel(int columns) { TableColumnModelExt model = new DefaultTableColumnModelExt(); for (int i = 0; i < columns; i++) { model.addColumn(createTableColumnExt(i)); } return model; } /** * Creates and returns a TableColumnExt with simple standard configuration. * *


     * column.getModelIndex() == modelIndex
     * column.getIdentifier() == String.valueOf(modelIndex);
     * 
* * @param modelIndex the model column index to use for config * @return a TableColumnExt with standard configuration */ protected TableColumnExt createTableColumnExt(int modelIndex) { TableColumnExt column = new TableColumnExt(modelIndex); column.setIdentifier(String.valueOf(modelIndex)); return column; } } swingx-1.0-src/src/test/org/jdesktop/swingx/table/TableColumnExtTest.java0000644000175000017500000003653011210401722025376 0ustar tonytony/* * $Id: TableColumnExtTest.java,v 1.20 2008/10/11 20:42:33 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.table; import java.io.IOException; import java.text.Collator; import java.util.Comparator; import java.util.Date; import javax.swing.DefaultCellEditor; import javax.swing.JTextField; import junit.framework.TestCase; import org.jdesktop.swingx.decorator.ColorHighlighter; import org.jdesktop.swingx.decorator.CompoundHighlighter; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.UIDependent; import org.jdesktop.swingx.renderer.DefaultTableRenderer; import org.jdesktop.test.PropertyChangeReport; import org.jdesktop.test.SerializableSupport; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * Unit test of enhanced TableColumnExt. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class TableColumnExtTest extends TestCase { /** * api change: let TableColumnExt implement UIDependent. */ @Test public void testUIDependent() { TableColumnExt columnExt = new TableColumnExt(); assertTrue(columnExt instanceof UIDependent); } /** * Issue #822-swingx: replace cloneable by copy constructor. * Here: test base properties copied. */ @Test public void testCopyConstructor() { TableColumnExt columnExt = new TableColumnExt(10, 200, new DefaultTableRenderer(), new DefaultCellEditor(new JTextField(20))); TableColumnExt copy = new TableColumnExt(columnExt); assertEquals(columnExt.getModelIndex(), copy.getModelIndex()); assertEquals(columnExt.getWidth(), copy.getWidth()); assertEquals(columnExt.getCellRenderer(), copy.getCellRenderer()); assertEquals(columnExt.getCellEditor(), copy.getCellEditor()); } /** * test remove * */ @Test public void testPutClientPropertyNullValue() { TableColumnExt columnExt = new TableColumnExt(); Object value = new Object(); String key = "some"; columnExt.putClientProperty(key, value); // sanity: got it assertSame(value, columnExt.getClientProperty(key)); columnExt.putClientProperty(key, null); assertNull(columnExt.getClientProperty(key)); // again - for going into the last untested line // but what to test? columnExt.putClientProperty(key, null); assertNull(columnExt.getClientProperty(key)); } /** * test doc'ed exceptions in putClientProperty. * */ @Test public void testPutClientPropertyExc() { TableColumnExt columnExt = new TableColumnExt(); try { columnExt.putClientProperty(null, "somevalue"); fail("put client property with null key must throw"); } catch (IllegalArgumentException e) { // expected behaviour } } /** * Sanity test Serializable. * * @throws ClassNotFoundException * @throws IOException * */ @Test public void testSerializable() throws IOException, ClassNotFoundException { TableColumnExt columnExt = new TableColumnExt(); Object value = new Date(); columnExt.putClientProperty("date", value); TableColumnExt serialized = SerializableSupport.serialize(columnExt); assertTrue(serialized.isVisible()); assertEquals(value, serialized.getClientProperty("date")); assertEquals(15, serialized.getMinWidth()); assertTrue(serialized.getResizable()); } /** * Issue #154-swingx. * * added property headerTooltip. Test initial value, propertyChange * notification, cloned correctly. * */ @Test public void testHeaderTooltip() { TableColumnExt columnExt = new TableColumnExt(); columnExt.setTitle("mytitle"); assertNull("tooltip is null initially", columnExt.getToolTipText()); String toolTip = "some column text"; PropertyChangeReport report = new PropertyChangeReport(); columnExt.addPropertyChangeListener(report); columnExt.setToolTipText(toolTip); assertEquals(toolTip, columnExt.getToolTipText()); assertEquals("must have fired one propertyChangeEvent for toolTipText ", 1, report.getEventCount("toolTipText")); TableColumnExt copy = new TableColumnExt(columnExt); assertEquals("tooltip property must be cloned", columnExt.getToolTipText(), copy.getToolTipText()); } /** * Test the sortable property: must fire propertyChange and * be cloned properly * */ @Test public void testSortable() { TableColumnExt columnExt = new TableColumnExt(); boolean sortable = columnExt.isSortable(); assertTrue("columnExt isSortable by default", sortable); PropertyChangeReport report = new PropertyChangeReport(); columnExt.addPropertyChangeListener(report); columnExt.setSortable(!sortable); // sanity assert: the change was taken assertEquals(sortable, !columnExt.isSortable()); assertEquals("must have fired one propertyChangeEvent for sortable ", 1, report.getEventCount("sortable")); TableColumnExt copy = new TableColumnExt(columnExt); assertEquals("sortable property must be cloned", columnExt.isSortable(), copy.isSortable()); } /** * Issue #273-swingx: make Comparator a bound property of TableColumnExt. * (instead of client property) * * test if setting comparator fires propertyChange. */ @Test public void testComparatorBoundProperty() { TableColumnExt tableColumn = new TableColumnExt(); PropertyChangeReport report = new PropertyChangeReport(); tableColumn.addPropertyChangeListener(report); Comparator comparator = Collator.getInstance(); tableColumn.setComparator(comparator); assertTrue(report.hasEvents()); assertEquals(1, report.getEventCount("comparator")); } /** * Issue #273-swingx: make Comparator a bound property of TableColumnExt. * (instead of client property) * * test if comparator is cloned. */ @Test public void testCopyComparator() { TableColumnExt tableColumn = new TableColumnExt(); Comparator comparator = Collator.getInstance(); tableColumn.setComparator(comparator); TableColumnExt clone = new TableColumnExt(tableColumn); assertEquals(comparator, clone.getComparator()); } /** * Issue #280-swingx: tableColumnExt doesn't fire propertyChange on * putClientProperty. * */ @Test public void testClientPropertyNotification() { TableColumnExt tableColumn = new TableColumnExt(); PropertyChangeReport report = new PropertyChangeReport(); tableColumn.addPropertyChangeListener(report); Object value = new Integer(3); tableColumn.putClientProperty("somevalue", value); assertTrue(report.hasEvents()); assertEquals(1, report.getEventCount("somevalue")); } /** * Issue #279-swingx: getTitle throws NPE. * */ @Test public void testTitle() { TableColumnExt tableColumn = new TableColumnExt(); tableColumn.getTitle(); } /** * user friendly resizable flag. * */ @Test public void testResizable() { TableColumnExt column = new TableColumnExt(0); //sanity assert assertTrue("min < max", column.getMinWidth() < column.getMaxWidth()); // sanity assert assertTrue("resizable default", column.getResizable()); column.setMinWidth(column.getMaxWidth()); assertFalse("must not be resizable with equal min-max", column.getResizable()); TableColumnExt copy = new TableColumnExt(column); // sanity assertEquals("min-max of clone", copy.getMinWidth(), copy.getMaxWidth()); assertFalse("must not be resizable with equal min-max", copy.getResizable()); copy.setMinWidth(0); //sanity assert assertTrue("min < max", copy.getMinWidth() < copy.getMaxWidth()); assertTrue("cloned base resizable", copy.getResizable()); } /** * Issue #39-swingx: * Client properties not preserved when cloning. * */ @Test public void testCopyClientProperty() { TableColumnExt column = new TableColumnExt(0); String key = "property"; Object value = new Object(); column.putClientProperty(key, value); TableColumnExt copy = new TableColumnExt(column); assertEquals("client property must be in cloned", value, copy.getClientProperty(key)); key = "single"; column.putClientProperty(key, value); //sanity check assertSame(value, column.getClientProperty(key)); assertNull("cloned client properties must be in independant", copy.getClientProperty(key)); } //begin SwingX Issue #770 checks // PENDING JW: consider to remove the "HighlighterClient" // related testing here - that part is done in TableColumnExtAsHighlighterClient in package // swingx. /** * Check for setHighlighters portion of #770. */ @Test public void testSetHighlighters() { TableColumnExt column = new TableColumnExt(0); PropertyChangeReport hcl = new PropertyChangeReport(); column.addPropertyChangeListener(hcl); Highlighter h1 = new ColorHighlighter(); Highlighter h2 = new ColorHighlighter(); //sanity check assertEquals(0, hcl.getEventCount()); //base case no highlighters assertSame(CompoundHighlighter.EMPTY_HIGHLIGHTERS, column.getHighlighters()); column.setHighlighters(h1); assertEquals(1, hcl.getEventCount()); assertEquals("highlighters", hcl.getLastProperty()); assertEquals(1, column.getHighlighters().length); assertSame(h1, column.getHighlighters()[0]); //reset state hcl.clear(); column.removeHighlighter(h1); assertEquals(1, hcl.getEventCount()); assertEquals("highlighters", hcl.getLastProperty()); //we have a compound, but empty highlighter assertEquals(0, column.getHighlighters().length); // JW: changed CompoundHighlighter to return its EMPTY_HIGHLIGHTERS if empty assertSame(CompoundHighlighter.EMPTY_HIGHLIGHTERS, column.getHighlighters()); //reset state hcl.clear(); column.setHighlighters(h1, h2); assertEquals(1, hcl.getEventCount()); assertEquals("highlighters", hcl.getLastProperty()); assertEquals(2, column.getHighlighters().length); assertSame(h1, column.getHighlighters()[0]); assertSame(h2, column.getHighlighters()[1]); } /** * Check for addHighlighter portion of #770. */ @Test public void testAddHighlighter() { TableColumnExt column = new TableColumnExt(0); PropertyChangeReport hcl = new PropertyChangeReport(); column.addPropertyChangeListener(hcl); Highlighter h1 = new ColorHighlighter(); Highlighter h2 = new ColorHighlighter(); //sanity check assertEquals(0, hcl.getEventCount()); //base case no highlighters assertSame(CompoundHighlighter.EMPTY_HIGHLIGHTERS, column.getHighlighters()); column.addHighlighter(h1); assertEquals(1, hcl.getEventCount()); assertEquals("highlighters", hcl.getLastProperty()); assertEquals(1, column.getHighlighters().length); assertSame(h1, column.getHighlighters()[0]); //reset state hcl.clear(); column.removeHighlighter(h1); assertEquals(1, hcl.getEventCount()); assertEquals("highlighters", hcl.getLastProperty()); //we have a compound, but empty highlighter assertEquals(0, column.getHighlighters().length); // JW: changed CompoundHighlighter to return its EMPTY_HIGHLIGHTERS if empty assertSame(CompoundHighlighter.EMPTY_HIGHLIGHTERS, column.getHighlighters()); column.setHighlighters(h1); //reset state hcl.clear(); column.addHighlighter(h2); assertEquals(1, hcl.getEventCount()); assertEquals("highlighters", hcl.getLastProperty()); assertEquals(2, column.getHighlighters().length); assertSame(h1, column.getHighlighters()[0]); assertSame(h2, column.getHighlighters()[1]); } /** * Check for removeHighlighter portion of #770. */ @Test public void testRemoveHighlighter() { TableColumnExt column = new TableColumnExt(0); PropertyChangeReport hcl = new PropertyChangeReport(); column.addPropertyChangeListener(hcl); Highlighter h1 = new ColorHighlighter(); Highlighter h2 = new ColorHighlighter(); Highlighter h3 = new ColorHighlighter(); //sanity check assertEquals(0, hcl.getEventCount()); //ensure that nothing goes awry column.removeHighlighter(h1); assertEquals(0, hcl.getEventCount()); column.setHighlighters(h1, h2, h3); //reset state hcl.clear(); column.removeHighlighter(h2); assertEquals(1, hcl.getEventCount()); assertEquals("highlighters", hcl.getLastProperty()); assertEquals(2, column.getHighlighters().length); assertSame(h1, column.getHighlighters()[0]); assertSame(h3, column.getHighlighters()[1]); } /** * Check to ensure that the clone returns the highlighters correctly. Part of #770. */ @Test public void testCopyHighlighters() { TableColumnExt column = new TableColumnExt(0); Highlighter h1 = new ColorHighlighter(); Highlighter h2 = new ColorHighlighter(); Highlighter h3 = new ColorHighlighter(); column.setHighlighters(h1, h2); TableColumnExt clone = new TableColumnExt(column); Highlighter[] columnHighlighters = column.getHighlighters(); Highlighter[] cloneHighlighters = clone.getHighlighters(); assertEquals(2, columnHighlighters.length); assertEquals(columnHighlighters.length, cloneHighlighters.length); assertSame(h1, columnHighlighters[0]); assertSame(columnHighlighters[0], cloneHighlighters[0]); assertSame(h2, columnHighlighters[1]); assertSame(columnHighlighters[1], cloneHighlighters[1]); column.addHighlighter(h3); columnHighlighters = column.getHighlighters(); cloneHighlighters = clone.getHighlighters(); assertEquals(3, columnHighlighters.length); assertEquals(columnHighlighters.length, cloneHighlighters.length + 1); assertSame(h1, columnHighlighters[0]); assertSame(columnHighlighters[0], cloneHighlighters[0]); assertSame(h2, columnHighlighters[1]); assertSame(columnHighlighters[1], cloneHighlighters[1]); assertSame(h3, columnHighlighters[2]); } } swingx-1.0-src/src/test/org/jdesktop/swingx/table/ColumnControlButtonTest.java0000644000175000017500000006302711210401724026505 0ustar tonytony/* * $Id: ColumnControlButtonTest.java,v 1.25 2008/10/11 20:42:33 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.table; import java.awt.Component; import java.awt.GraphicsEnvironment; import java.awt.event.ActionEvent; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.Icon; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JToggleButton; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.action.ActionContainerFactory; import org.jdesktop.swingx.icon.EmptyIcon; import org.jdesktop.swingx.plaf.ColumnControlButtonAddon; import org.jdesktop.swingx.plaf.LookAndFeelAddons; import org.jdesktop.swingx.table.ColumnControlButton.ColumnVisibilityAction; import org.jdesktop.swingx.table.ColumnControlButton.DefaultColumnControlPopup; import org.jdesktop.test.AncientSwingTeam; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class ColumnControlButtonTest extends InteractiveTestCase { private static final Logger LOG = Logger .getLogger(ColumnControlButtonTest.class.getName()); protected TableModel sortableTableModel; @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } /** * Issue #404-swingx: load column control margin from ui. * Test that column control configures itself with the icon from the ui. */ @Test public void testColumnControlInitialUpdateInsetsUIResource() { ColumnControlButton control = new ColumnControlButton(new JXTable()); // PENDING JW: why not same? insets can be shared - or not? // probably setMargin interferes - is doing some things ... assertEquals("columnControl must have margin from ui", UIManager.getInsets(ColumnControlButton.COLUMN_CONTROL_BUTTON_MARGIN_KEY), control.getMargin()); } /** * Issue #404-swingx: load column control margin from ui. * Test that column control loads the margin. */ @SuppressWarnings("unused") @Test public void testColumnControlLoadsMargin() { // force loading by instantiating a column control ColumnControlButton control = new ColumnControlButton(new JXTable()); assertNotNull("columnControl must load lf-specific icon", UIManager.getInsets(ColumnControlButton.COLUMN_CONTROL_BUTTON_MARGIN_KEY)); } /** * Issue #404-swingx: load column control margin from ui. * Test that addon loads the margin. */ @Test public void testColumnControlAddonLoadsMargin() { // direct loading of addon LookAndFeelAddons.contribute(new ColumnControlButtonAddon()); assertNotNull("addon must load lf-specific icon", UIManager.getInsets(ColumnControlButton.COLUMN_CONTROL_BUTTON_MARGIN_KEY)); } /** * Issue #404-swingx: load column control icon from ui. * Test that table instantiates the column control with ui icon. */ @Test public void testColumnControlInXTable() { JXTable table = new JXTable(); ColumnControlButton control = (ColumnControlButton) table.getColumnControl(); assertSame("columnControl must have icon from ui", UIManager.getIcon(ColumnControlButton.COLUMN_CONTROL_BUTTON_ICON_KEY), control.getIcon()); } /** * Issue #404-swingx: load column control icon from ui. * Test that icon is not updated on updateUI if not uiResource */ @Test public void testColumnControlIconNotUpdateNonActionUIResource() { ColumnControlButton control = new ColumnControlButton(new JXTable(), new EmptyIcon()); Icon icon = control.getIcon(); String lf = UIManager.getLookAndFeel().getName(); setSystemLF(!defaultToSystemLF); if (lf.equals(UIManager.getLookAndFeel().getName())) { LOG.info("cannot run layoutOnLFChange - equal LF" + lf); return; } SwingUtilities.updateComponentTreeUI(control); assertSame("icon must not be updated on LF change if not UIResource: ", icon, control.getIcon()); } /** * Issue #404-swingx: load column control icon from ui. * Test that is updated on updateUI */ @Test public void testColumnControlIconUpdateActionUIResource() { ColumnControlButton control = new ColumnControlButton(new JXTable()); Icon icon = control.getIcon(); String lf = UIManager.getLookAndFeel().getName(); setSystemLF(!defaultToSystemLF); if (lf.equals(UIManager.getLookAndFeel().getName())) { LOG.info("cannot run layoutOnLFChange - equal LF" + lf); return; } SwingUtilities.updateComponentTreeUI(control); assertNotSame("sanity: ui did reload icon: ", icon, UIManager.getIcon(ColumnControlButton.COLUMN_CONTROL_BUTTON_ICON_KEY)); assertNotSame("icon must be updated on LF change: ", icon, control.getIcon()); } /** * Issue #404-swingx: load column control icon from ui. * Test that column control configures itself with the icon from the ui. */ @Test public void testColumnControlInitialUpdateActionUIResource() { ColumnControlButton control = new ColumnControlButton(new JXTable()); assertSame("columnControl must have icon from ui", UIManager.getIcon(ColumnControlButton.COLUMN_CONTROL_BUTTON_ICON_KEY), control.getIcon()); } /** * Issue #404-swingx: load column control icon from ui. * Test that column control loads the icon. */ @SuppressWarnings("unused") @Test public void testColumnControlLoadsIcon() { // force loading by instantiating a column control ColumnControlButton control = new ColumnControlButton(new JXTable()); assertNotNull("columnControl must load lf-specific icon", UIManager.getIcon(ColumnControlButton.COLUMN_CONTROL_BUTTON_ICON_KEY)); } /** * Issue #404-swingx: load column control icon from ui. * Test that addon loads the icon. */ @Test public void testColumnControlAddonLoadsIcon() { // direct loading of addon LookAndFeelAddons.contribute(new ColumnControlButtonAddon()); assertNotNull("addon must load lf-specific icon", UIManager.getIcon(ColumnControlButton.COLUMN_CONTROL_BUTTON_ICON_KEY)); } /** * Issue #429-swingx: ClassCastException if column identifiers are not * String type. * */ @Test public void testNonStringIdentifier() { JXTable table = new JXTable(0, 2); table.getColumn(0).setIdentifier(new Object()); table.setColumnControlVisible(true); table.getColumnControl(); } @Test public void testNotNullColumnModelListener() { JXTable table = new JXTable(0, 2); table.setColumnControlVisible(true); assertNotNull(((ColumnControlButton)table.getColumnControl()).columnModelListener); } /** * Tests if subclasses are allowed to not create a visibility action. * This might happen if they want to exempt certain columns from * user interaction. * */ @Test public void testNullVisibilityAction() { JXTable table = new JXTable(); ColumnControlButton columnControl = new ColumnControlButton(table) { @Override protected ColumnVisibilityAction createColumnVisibilityAction(TableColumn column) { if (column.getModelIndex() == 0) return null; return super.createColumnVisibilityAction(column); } }; table.setColumnControl(columnControl); table.setColumnControlVisible(true); table.setModel(sortableTableModel); } /** * test that the actions synch's its own selected property with * the column's visible property.

* * Looks as if the non-synch of action.setSelected only shows * if the ColumnControlPopup doesn't create a menuitem via ActionFactory: the * listeners internally installed via ActionFactory probably take care? *

* * An analogous test in the incubator (in kleopatra/.../table) did fail * for a dialog based custom ColumnControlPopup. For now, changed the visibility * action to explicitly update the tableColumn. All tests are passing, * but need to further evaluate. * */ @Test public void testColumnVisibilityAction() { JXTable table = new JXTable(10, 3); table.setColumnControlVisible(true); ColumnControlButton columnControl = (ColumnControlButton) table.getColumnControl(); ColumnVisibilityAction action = columnControl.getColumnVisibilityActions().get(0); TableColumnExt columnExt = table.getColumnExt(0); boolean visible = columnExt.isVisible(); // sanity assertTrue(visible); assertEquals(columnExt.isVisible(), action.isSelected()); action.setSelected(!visible); // hmmm... here it's working? unexpected // synch might be done by the listener's installed by ActionFactor.createMenuItem()? assertEquals(!visible, columnExt.isVisible()); } /** * Tests that enabled property of table and column control is synched dynamically. */ @Test public void testDynamicDisabled() { JXTable table = new JXTable(10, 3); table.setColumnControlVisible(true); assertEquals(table.isEnabled(), table.getColumnControl().isEnabled()); table.setEnabled(!table.isEnabled()); assertEquals(table.isEnabled(), table.getColumnControl().isEnabled()); } /** * suspected: enabled not synched on init. * But is (done in ccb.installTable()). * */ @Test public void testInitialDisabled() { JXTable table = new JXTable(10, 3); table.setEnabled(false); table.setColumnControlVisible(true); assertEquals(table.isEnabled(), table.getColumnControl().isEnabled()); } /** * guarantee that at least one column is always visible. * */ @Test public void testMinimumColumnCountOne() { JXTable table = new JXTable(10, 2); table.setColumnControlVisible(true); table.getColumnExt(0).setVisible(false); assertEquals(1, table.getColumnCount()); } /** * Issue #229-swingx: increasing listener list in column actions. * */ @Test public void testActionListenerCount() { JXTable table = new JXTable(10, 1); Action action = table.getActionMap().get(JXTable.HORIZONTALSCROLL_ACTION_COMMAND); if (!(action instanceof AbstractActionExt)) { LOG.info("cannot run testColumnActionListenerCount - action not of type AbstractAction"); return; } AbstractActionExt extAction = (AbstractActionExt) action; assertTrue(extAction.isStateAction()); assertEquals(0, extAction.getPropertyChangeListeners().length); AbstractButton menuItem = new JCheckBoxMenuItem(); ActionContainerFactory factory = new ActionContainerFactory(null); factory.configureSelectableButton(menuItem, extAction, null); // sanity: here the action is bound to a menu item in the columnControl // should have one ad int initialPCLCount = extAction.getPropertyChangeListeners().length; // sanity: expect it to be 2 - one is the menuitem itself, another // the TogglePCL registered by the ActionContainerFacory assertEquals(2, initialPCLCount); menuItem = new JToggleButton(); factory.configureSelectableButton(menuItem, extAction, null); // 2 menuitems are listening assertEquals(2* initialPCLCount, extAction.getPropertyChangeListeners().length); } /** * Issue #153-swingx: ClassCastException if actionMap key is not a string. * */ @Test public void testNonStringActionKeys() { JXTable table = new JXTable(); Action l = new AbstractAction("dummy") { public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } }; table.registerKeyboardAction(l , KeyStroke.getKeyStroke("ESCAPE"), JComponent.WHEN_FOCUSED); table.setColumnControlVisible(true); table.getColumnControl(); } @Test public void testColumnControlReleaseAction() { final JXTable table = new JXTable(sortableTableModel); final TableColumnExt priorityColumn = table.getColumnExt("First Name"); int listenerCount = priorityColumn.getPropertyChangeListeners().length; table.setColumnControlVisible(true); // JW: the columnControlButton is created lazily, so we // have to access to test if listeners are registered. table.getColumnControl(); assertEquals("numbers of listeners must be increased", listenerCount + 1, priorityColumn.getPropertyChangeListeners().length); int totalColumnCount = table.getColumnCount(); table.removeColumn(priorityColumn); assertEquals("number of columns reduced", totalColumnCount - 1, table.getColumnCount()); assertEquals("all listeners must be removed", 0, priorityColumn.getPropertyChangeListeners().length); } /** * Issue #212-swingx: * * Behaviour change: *

    *
  • before - guarantee that exactly one column is always visible, * independent of source of visibiblity change *
  • now - this is true for user gesture induced invisible (through * columnControl, but not for programmatic hiding. It's up to * developers to not hide all. To alleviate the effects if they * hide all, the JXTableHeader and ColumnControl is always visible. *
* This is testing the old behaviour (guarding against regression) * Here we directly set the second last visible column to invisible. This * failed if a) column visibility is set after adding the table to a frame * and b) model.count = 2. * */ @Test public void testSetAllColumnsToInvisible() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { return; } final JXTable table = new JXTable(10, 2); table.setColumnControlVisible(true); wrapWithScrollingInFrame(table, ""); table.getColumnExt(0).setVisible(false); assertEquals(1, table.getColumnCount()); table.getColumnExt(0).setVisible(false); assertEquals(0, table.getColumnCount()); } /** * Issue #212-swingx: * * guarantee that exactly one column is always visible if * visibility is toggled via the ColumnControl. * * Here we deselect the menuitem. * */ @Test public void testSetLastColumnMenuItemToUnselected() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { return; } final JXTable table = new JXTable(10, 1); table.setColumnControlVisible(true); wrapWithScrollingInFrame(table, ""); ColumnControlButton columnControl = (ColumnControlButton) table.getColumnControl(); Component[] items = ((DefaultColumnControlPopup) columnControl.getColumnControlPopup()).getPopupMenu().getComponents(); ((JMenuItem) items[0]).setSelected(false); assertEquals(1, table.getColumnCount()); } /** * Issue #192: initially invisibility columns are hidden * but marked as visible in control. * * Issue #38 (swingx): initially invisble columns don't show up * in the column control list. * * */ @Test public void testColumnControlInvisibleColumns() { final JXTable table = new JXTable(sortableTableModel); // columns set to invisible before setting the columnControl // will not be inserted into the column control's list // table.getColumnExt("Last Name").setVisible(false); table.setColumnControlVisible(true); int totalColumnCount = table.getColumnCount(); final TableColumnExt priorityColumn = table.getColumnExt("First Name"); priorityColumn.setVisible(false); ColumnControlButton columnControl = (ColumnControlButton) table.getColumnControl(); assertNotNull("popup menu not null", columnControl.popup); int columnMenuItems = 0; Component[] items = ((DefaultColumnControlPopup) columnControl.getColumnControlPopup()).getPopupMenu().getComponents(); for (int i = 0; i < items.length; i++) { if (!(items[i] instanceof JMenuItem)) { break; } columnMenuItems++; } // wrong assumption - has separator and actions! assertEquals("menu items must be equal to columns", totalColumnCount, columnMenuItems); JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem) ((DefaultColumnControlPopup) columnControl.getColumnControlPopup()).getPopupMenu() .getComponent(0); // sanit assert assertEquals(priorityColumn.getHeaderValue(), menuItem.getText()); assertEquals("selection of menu must be equal to column visibility", priorityColumn.isVisible(), menuItem.isSelected()); } /** * test if subclasses are allowed to not create a visibility action. * This might happen, if they want to exempt certain columns from * user interaction. * */ public void interactiveNullVisibilityAction() { JXTable table = new JXTable(); ColumnControlButton columnControl = new ColumnControlButton(table) { @Override protected ColumnVisibilityAction createColumnVisibilityAction(TableColumn column) { if (column.getModelIndex() == 0) return null; return super.createColumnVisibilityAction(column); } }; table.setColumnControl(columnControl); table.setColumnControlVisible(true); table.setModel(sortableTableModel); JXFrame frame = wrapWithScrollingInFrame(table, "first model column not togglable"); frame.setVisible(true); } /** * Issue ??: Column control update on changing table model. * */ public void interactiveTestToggleTableModel() { final DefaultTableModel tableModel = new DefaultTableModel(0, 20); final JXTable table = new JXTable(tableModel); table.setColumnControlVisible(true); Action toggleAction = new AbstractAction("Toggle TableModel") { public void actionPerformed(ActionEvent e) { TableModel model = table.getModel(); table.setModel(model.equals(tableModel) ? sortableTableModel : tableModel); } }; JXFrame frame = wrapWithScrollingInFrame(table, "ColumnControl: set tableModel update columns"); addAction(frame, toggleAction); frame.setVisible(true); } /** * Issue ??: Column control on changing column model. * */ public void interactiveTestColumnControlColumnModel() { final JXTable table = new JXTable(10, 5); table.setColumnControlVisible(true); Action toggleAction = new AbstractAction("Set ColumnModel") { public void actionPerformed(ActionEvent e) { table.setColumnModel(new DefaultTableColumnModel()); table.setModel(sortableTableModel); setEnabled(false); } }; JXFrame frame = wrapWithScrollingInFrame(table, "ColumnControl: set columnModel ext -> core default"); addAction(frame, toggleAction); frame.setVisible(true); } /** * Issue ??: Column control cancontrol update on changing column model. * */ public void interactiveTestColumnControlColumnModelExt() { final JXTable table = new JXTable(); table.setColumnModel( new DefaultTableColumnModel()); table.setModel(new DefaultTableModel(10, 5)); table.setColumnControlVisible(true); Action toggleAction = new AbstractAction("Set ColumnModelExt") { public void actionPerformed(ActionEvent e) { table.setColumnModel(new DefaultTableColumnModelExt()); table.setModel(sortableTableModel); table.getColumnExt(0).setVisible(false); setEnabled(false); } }; JXFrame frame = wrapWithScrollingInFrame(table, "ColumnControl: set ColumnModel core -> modelExt"); addAction(frame, toggleAction); frame.setVisible(true); } /** * Issue #192: initially invisibility columns are hidden * but marked as visible in control. * * Issue #38 (swingx): initially invisble columns don't show up * in the column control list. * * Visual check: first enable column control then set column invisible. * */ public void interactiveTestColumnControlInvisibleColumns() { final JXTable table = new JXTable(sortableTableModel); table.setColumnControlVisible(true); final TableColumnExt firstNameColumn = table.getColumnExt("First Name"); firstNameColumn.setVisible(false); JFrame frame = wrapWithScrollingInFrame(table, "ColumnControl (#192, #38-swingx) first enable ColumnControl then column invisible"); frame.setVisible(true); } /** * Issue #192: initially invisibility columns are hidden * but marked as visible in control. * * Issue #38 (swingx): initially invisble columns don't show up * in the column control list. * * Visual check: first set column invisible then enable column control. * */ public void interactiveTestColumnControlEarlyInvisibleColumns() { final JXTable table = new JXTable(sortableTableModel); table.getColumnExt("First Name").setVisible(false); table.setColumnControlVisible(true); JFrame frame = wrapWithScrollingInFrame(table, "ColumnControl (#192, #38-swingx) first column invisible, the enable columnControl"); frame.setVisible(true); } /** * Issue #212: programmatically toggle column vis does not work. * * Visual check: compare toggle column visibility both via the columnControl * and programmatically by button. While the columnControl prevents to hide * the very last visible column, developers have full control to do so * programatically. * * */ public void interactiveTestColumnControlSetModelToggleInvisibleColumns() { final JXTable table = new JXTable(); table.setColumnControlVisible(true); JXFrame frame = wrapWithScrollingInFrame(table, "ColumnControl (#212-swingx) setModel and toggle first column invisible"); frame.setVisible(true); table.setModel(new DefaultTableModel(10, 2)); final TableColumnExt firstNameColumn = table.getColumnExt(1); Action action = new AbstractAction("Toggle first name visibility") { public void actionPerformed(ActionEvent e) { firstNameColumn.setVisible(!firstNameColumn.isVisible()); } }; addAction(frame, action); } /** * * */ public void interactiveTestLastVisibleColumn() { final JXTable table = new JXTable(); table.setModel(new DefaultTableModel(10, 2)); table.setColumnControlVisible(true); JFrame frame = wrapWithScrollingInFrame(table, "JXTable (#192, #38-swingx) ColumnControl and Visibility of items"); table.getColumnExt(0).setVisible(false); frame.setVisible(true); } public ColumnControlButtonTest() { super("ColumnControlButtonTest"); } // flag used in setup to explicitly choose LF private boolean defaultToSystemLF; @Override protected void setUp() throws Exception { super.setUp(); // make sure we have the same default for each test defaultToSystemLF = false; setSystemLF(defaultToSystemLF); sortableTableModel = new AncientSwingTeam(); } public static void main(String args[]) { setSystemLF(false); ColumnControlButtonTest test = new ColumnControlButtonTest(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Column.*"); // test.runInteractiveTests("interactive.*TableHeader.*"); // test.runInteractiveTests("interactive.*SorterP.*"); // test.runInteractiveTests("interactive.*Column.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } } swingx-1.0-src/src/test/org/jdesktop/swingx/table/ColumnControlButtonIssues.java0000644000175000017500000000202411210401722027025 0ustar tonytony/* * $Id: ColumnControlButtonIssues.java,v 1.9 2007/07/09 11:40:54 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.table; import java.util.logging.Logger; /** * Test to exposed known issues of ColumnControlButton.

* * Ideally, there would be at least one failing test method per open * issue in the issue tracker. Plus additional failing test methods for * not fully specified or not yet decided upon features/behaviour.

* * Once the issues are fixed and the corresponding methods are passing, they * should be moved over to the XXTest. * * @author Jeanette Winzenburg */ public class ColumnControlButtonIssues extends ColumnControlButtonTest { @SuppressWarnings("all") private static final Logger LOG = Logger .getLogger(ColumnControlButtonIssues.class.getName()); public void testDummy() { // do nothing - placeholder for empty issues } } swingx-1.0-src/src/test/org/jdesktop/swingx/table/DatePickerCellEditorTest.java0000644000175000017500000001677711210401722026505 0ustar tonytony/* * $Id: DatePickerCellEditorTest.java,v 1.12 2008/10/11 20:42:33 rah003 Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.table; import java.text.ParseException; import java.util.Date; import javax.swing.tree.DefaultMutableTreeNode; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXDatePicker; import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; import org.jdesktop.test.CellEditorReport; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; @RunWith(JUnit4.class) public class DatePickerCellEditorTest extends InteractiveTestCase { public static void main(String[] args) { setSystemLF(true); DatePickerCellEditorTest test = new DatePickerCellEditorTest(); try { test.runInteractiveTests(); // test.runInteractiveTests(".*Text.*"); // test.runInteractiveTests(".*XLabel.*"); // test.runInteractiveTests(".*Table.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Test Picker's value --> date mapping strategy. * @throws ParseException * * */ @Test public void testDateEditorValueAsDate() throws ParseException { DatePickerCellEditor editor = new DatePickerCellEditor(); Date input = new Date(); assertEquals("the input date must be unchanged", input, editor.getValueAsDate(input)); assertEquals("input as long must be same", input, editor.getValueAsDate(input.getTime())); // PENDING: fails on server, moved out off the way into visual check for now // String dateString = editor.getFormats()[0].format(input); // Date fullCycle = editor.getFormats()[0].parse(dateString); // assertEquals("the formatted input date string must be same", fullCycle, editor.getValueAsDate(dateString)); String nonsenseString = "invalid"; assertNull("invalid string maps to null", editor.getValueAsDate(nonsenseString)); assertNull("empty String maps to null", editor.getValueAsDate("")); // same with date/string wrapped into TreeNode DefaultMutableTreeNode node = new DefaultMutableTreeNode(input); assertEquals("date must be user-object", input, editor.getValueAsDate(node)); // same with date/string wrapped into a TreeTableNode DefaultMutableTreeTableNode tableNode = new DefaultMutableTreeTableNode(input); assertEquals("date must be user-object", input, editor.getValueAsDate(tableNode)); } /** * test fire stopped after accept in monthview. * * */ @Test public void testDateEditorFireStopMonthAccept() { DatePickerCellEditor editor = new DatePickerCellEditor(); final CellEditorReport report = new CellEditorReport(); editor.addCellEditorListener(report); JXDatePicker picker = (JXDatePicker) editor.getTableCellEditorComponent (null, new Date(), false, -1, -1); picker.getMonthView().commitSelection(); assertEquals(1, report.getEventCount()); assertEquals(1, report.getStoppedEventCount()); } /** * test fire stopped after accept in monthview. * * */ @Test public void testDateEditorFireStopMonthCancel() { DatePickerCellEditor editor = new DatePickerCellEditor(); final CellEditorReport report = new CellEditorReport(); editor.addCellEditorListener(report); JXDatePicker picker = (JXDatePicker) editor.getTableCellEditorComponent (null, new Date(), false, -1, -1); picker.getMonthView().cancelSelection(); assertEquals(1, report.getEventCount()); assertEquals(1, report.getCanceledEventCount()); } /** * test fire stopped after commit picker.editor. * @throws ParseException * */ @Test public void testDateEditorFireStopPickerCommit() throws ParseException { DatePickerCellEditor editor = new DatePickerCellEditor(); final CellEditorReport report = new CellEditorReport(); editor.addCellEditorListener(report); JXDatePicker picker = (JXDatePicker) editor.getTableCellEditorComponent (null, null, false, -1, -1); picker.commitEdit(); assertEquals(1, report.getEventCount()); assertEquals(1, report.getStoppedEventCount()); } /** * test fire cancel after cancel picker.editor. * * @throws ParseException * */ @Test public void testDateEditorFireCancelPickerCancel() throws ParseException { DatePickerCellEditor editor = new DatePickerCellEditor(); final CellEditorReport report = new CellEditorReport(); editor.addCellEditorListener(report); JXDatePicker picker = (JXDatePicker) editor .getTableCellEditorComponent(null, new Date(), false, -1, -1); picker.cancelEdit(); assertEquals(1, report.getEventCount()); assertEquals(1, report.getCanceledEventCount()); } /** * test fire stopped after stopCellEditing. * stop commits, triggers value change in formatted, triggers * BasicDatePickerUI to post action event which triggers * stop editing again ... that's twice! */ @Test public void testDateEditorFireStop() { DatePickerCellEditor editor = new DatePickerCellEditor(); CellEditorReport report = new CellEditorReport(); editor.addCellEditorListener(report); editor.getTableCellEditorComponent(null, new Date(), false, -1, -1); editor.stopCellEditing(); assertEquals(1, report.getEventCount()); assertEquals(1, report.getStoppedEventCount()); } /** * test fire cancel after cancelCellEditing * */ @Test public void testDateEditorFireCancel() { DatePickerCellEditor editor = new DatePickerCellEditor(); CellEditorReport report = new CellEditorReport(); editor.addCellEditorListener(report); editor.getTableCellEditorComponent(null, null, false, -1, -1); editor.cancelCellEditing(); assertEquals(1, report.getEventCount()); assertEquals(1, report.getCanceledEventCount()); } /** * Editor must not fire on getXXComponent() * */ @Test public void testDateEditorNotFire() { DatePickerCellEditor editor = new DatePickerCellEditor(); CellEditorReport report = new CellEditorReport(); editor.addCellEditorListener(report); editor.getTableCellEditorComponent(null, null, false, -1, -1); assertEquals(0, report.getEventCount()); } } swingx-1.0-src/src/test/org/jdesktop/swingx/SerializableTest.java0000644000175000017500000001253211210401722024023 0ustar tonytony/* * $Id: SerializableTest.java,v 1.8 2009/01/27 11:09:16 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx; import java.io.NotSerializableException; import java.util.logging.Logger; import javax.swing.UIManager; import javax.swing.tree.TreeCellRenderer; import org.jdesktop.swingx.calendar.DatePickerFormatter; import org.jdesktop.swingx.renderer.DefaultTreeRenderer; import org.jdesktop.test.SerializableSupport; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Test serializable of all SwingX components. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class SerializableTest extends InteractiveTestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger .getLogger(SerializableTest.class.getName()); /** * Issue #423-swingx: all descendants of JComponent must be * serializable. * * Regression after painter merge: JXPanel$1 * is not serializable. * */ @Test public void testPanel() { JXPanel component = new JXPanel(); try { SerializableSupport.serialize(component); } catch (Exception e) { fail("not serializable " + e); } } /** * Issue #423-swingx: all descendants of JComponent must be * serializable. * * */ @Test public void testRootPane() { JXRootPane component = new JXRootPane(); try { SerializableSupport.serialize(component); } catch (Exception e) { fail("not serializable " + e); } } /** * Issue #423-swingx: all descendants of JComponent must be * serializable.

* * Regression for titled separator after painter merge: JXPanel$1 * is not serializable. * */ @Test public void testTitledSeparator() { JXTitledSeparator component = new JXTitledSeparator(); try { SerializableSupport.serialize(component); } catch (Exception e) { fail("not serializable " + e); } } /** * Issue #423-swingx: all descendants of JComponent must be * serializable.

* * Regression for DefaultTreeRenderer after painter merge: JXPanel$1 * is not serializable. * */ @Test public void testSerializeTreeRenderer() { TreeCellRenderer xListRenderer = new DefaultTreeRenderer(); try { SerializableSupport.serialize(xListRenderer); } catch (Exception e) { fail("not serializable " + e); } } /** * Issue #423-swingx: all descendants of JComponent must be * serializable.

* */ @Test public void testDatePickerFormatter() { DatePickerFormatter component = new DatePickerFormatter(); try { SerializableSupport.serialize(component); } catch (Exception e) { fail("not serializable " + e); } } /** * Issue #423-swingx: all descendants of JComponent must be * serializable.

* * Note: this blows as soon as a JXTable is set! */ @Test public void testTableHeader() throws Exception { JXTableHeader component = new JXTableHeader(); if (javax.swing.plaf.synth.SynthLookAndFeel.class.isAssignableFrom(Class.forName(UIManager.getSystemLookAndFeelClassName()))) { LOG.warning("Table header is not serializable on Linux when using Synth or derived LaFs due to javax.swing.plaf.synth.SynthLabelUI being non serializable."); return; } try { SerializableSupport.serialize(component); } catch (NotSerializableException e) { fail("not serializable " + e); } } /** * Issue #423-swingx: all descendants of JComponent must be * serializable. * * */ @Test public void testRadioGroup() { JXRadioGroup component = new JXRadioGroup(); try { SerializableSupport.serialize(component); } catch (Exception e) { fail("not serializable " + e); } } /** * Issue #423-swingx: all descendants of JComponent must be * serializable.

* */ @Test public void testHyperlink() { JXHyperlink component = new JXHyperlink(); try { SerializableSupport.serialize(component); } catch (Exception e) { fail("not serializable " + e); } } } swingx-1.0-src/src/test/org/jdesktop/swingx/search/0000755000175000017500000000000011210401736021161 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/search/FindTest.java0000644000175000017500000007617611210401722023560 0ustar tonytony/* * $Id: FindTest.java,v 1.3 2008/12/01 14:54:53 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.search; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.GraphicsEnvironment; import java.awt.Window; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.swing.AbstractListModel; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.SwingUtilities; import javax.swing.table.AbstractTableModel; import javax.swing.text.BadLocationException; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXEditorPane; import org.jdesktop.swingx.JXFindBar; import org.jdesktop.swingx.JXFindPanel; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXList; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTree; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Contains unit test for search related classes. * PENDING JW: should be in package search - but references swingx package internals. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class FindTest extends InteractiveTestCase { private static final Logger LOG = Logger .getLogger(FindTest.class.getName()); public static void main(String args[]) { setSystemLF(true); // Locale.setDefault(new Locale("es")); FindTest test = new FindTest(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Compare.*"); // test.runInteractiveTests("interactive.*Tree.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } @Override protected void setUp() throws Exception { super.setUp(); // sanity: new instance for each test SearchFactory.setInstance(new SearchFactory()); } /** * Findbugs: NPE in SearchFactory - showFindDialog for null target component. * */ @Test public void testSearchFactoryNullTarget() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run testSearchFactoryNullTarget - headless environment"); return; } JXTable table = new JXTable(20, 2); SearchFactory.getInstance().showFindDialog(null, table.getSearchable()); } /** * Issue #718-swingx: shared FindPanel not updated on LF change. * * Here: check that containing dialog is disposed, old api (no boolean). */ @SuppressWarnings("deprecation") @Test public void testFindDialogDisposeDeprecated() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } JXFrame frame = new JXFrame(); JXTable table = new JXTable(); frame.add(table); JComponent findPanel = SearchFactory.getInstance().getSharedFindPanel(); SearchFactory.getInstance().showFindDialog(table, table.getSearchable()); Window window = SwingUtilities.getWindowAncestor(findPanel); assertSame(frame, window.getOwner()); SearchFactory.getInstance().hideSharedFindPanel(true); assertFalse("window must not be displayable", window.isDisplayable()); assertNull("findPanel must be unparented", findPanel.getParent()); } /** * Issue #718-swingx: shared FindPanel not updated on LF change. * * Here: check that containing dialog is disposed, new api with flag. */ @Test public void testFindDialogDispose() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } JXFrame frame = new JXFrame(); JXTable table = new JXTable(); frame.add(table); JComponent findPanel = SearchFactory.getInstance().getSharedFindPanel(); SearchFactory.getInstance().showFindDialog(table, table.getSearchable()); Window window = SwingUtilities.getWindowAncestor(findPanel); assertSame(frame, window.getOwner()); SearchFactory.getInstance().hideSharedFindPanel(true); assertFalse("window must not be displayable", window.isDisplayable()); assertNull("findPanel must be unparented", findPanel.getParent()); } /** * Issue #718-swingx: shared FindPanel not updated on LF change. * * Here: check that containing dialog is not disposed. */ @Test public void testFindDialogHide() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } JXFrame frame = new JXFrame(); JXTable table = new JXTable(); frame.add(table); JComponent findPanel = SearchFactory.getInstance().getSharedFindPanel(); SearchFactory.getInstance().showFindDialog(table, table.getSearchable()); Container parent = findPanel.getParent(); Window window = SwingUtilities.getWindowAncestor(findPanel); assertSame(frame, window.getOwner()); SearchFactory.getInstance().hideSharedFindPanel(false); assertFalse("window must not be visible", window.isVisible()); assertSame("findPanel must parent must be unchanged", parent, findPanel.getParent()); assertTrue("window must be displayable", window.isDisplayable()); } /** * test if internal state is reset to not found by * passing a null searchstring. * */ @Test public void testTableResetStateWithNullSearchString() { JXTable table = new JXTable(new TestTableModel()); int row = 39; int firstColumn = 0; String firstSearchText = table.getValueAt(row, firstColumn).toString(); PatternModel model = new PatternModel(); model.setRawText(firstSearchText); // initialize searchable to "found state" int foundIndex = table.getSearchable().search(model.getPattern(), -1); // sanity asserts int foundColumn = ((TableSearchable) table.getSearchable()).lastSearchResult.foundColumn; assertEquals("last line found", row, foundIndex); assertEquals("column must be updated", firstColumn, foundColumn); // search with null searchstring int notFoundIndex = table.getSearchable().search((String) null); assertEquals("nothing found", -1, notFoundIndex); assertEquals("column must be reset", -1, ((TableSearchable) table.getSearchable()).lastSearchResult.foundColumn); } /** * test if internal state is reset to not found by * passing a empty (="") searchstring. * */ @Test public void testTableResetStateWithEmptySearchString() { JXTable table = new JXTable(new TestTableModel()); int row = 39; int firstColumn = 0; String firstSearchText = table.getValueAt(row, firstColumn).toString(); PatternModel model = new PatternModel(); model.setRawText(firstSearchText); // initialize searchable to "found state" int foundIndex = table.getSearchable().search(model.getPattern(), -1); // sanity asserts int foundColumn = ((TableSearchable) table.getSearchable()).lastSearchResult.foundColumn; assertEquals("last line found", row, foundIndex); assertEquals("column must be updated", firstColumn, foundColumn); // search with null searchstring int notFoundIndex = table.getSearchable().search(""); assertEquals("nothing found", -1, notFoundIndex); assertEquals("column must be reset", -1, ((TableSearchable) table.getSearchable()).lastSearchResult.foundColumn); } /** * test if search loops all columns of previous row (backwards search). * * Hmm... not testable? * Needed to widen access for lastFoundColumn. */ @Test public void testTableFoundNextColumnInPreviousRow() { JXTable table = new JXTable(new TestTableModel()); int lastColumn = table.getColumnCount() -1; int row = 39; int firstColumn = lastColumn - 1; String firstSearchText = table.getValueAt(row, firstColumn).toString(); // need a pattern for backwards search PatternModel model = new PatternModel(); model.setRawText(firstSearchText); int foundIndex = table.getSearchable().search(model.getPattern(), -1, true); assertEquals("last line found", row, foundIndex); int foundColumn = ((TableSearchable) table.getSearchable()).lastSearchResult.foundColumn; assertEquals("column must be updated", firstColumn, foundColumn); // the last char(s) of all values is the row index // here we are searching for an entry in the next row relative to // the previous search and expect the match in the first column (index = 0); int previousRow = row -1; String secondSearchText = String.valueOf(previousRow); model.setRawText(secondSearchText); int secondFoundIndex = table.getSearchable().search(model.getPattern(), previousRow, true); // sanity assert assertEquals("must find match in same row", previousRow, secondFoundIndex); assertEquals("column must be updated", lastColumn, ((TableSearchable) table.getSearchable()).lastSearchResult.foundColumn); } /** * test if search loops all columns of next row. * * Hmm... not testable? * Needed to widen access for lastFoundColumn. */ @Test public void testTableFoundPreviousColumnInNextRow() { JXTable table = new JXTable(new TestTableModel()); int row = 0; int firstColumn = 1; String firstSearchText = table.getValueAt(row, firstColumn).toString(); int foundIndex = table.getSearchable().search(firstSearchText); assertEquals("last line found", row, foundIndex); int foundColumn = ((TableSearchable) table.getSearchable()).lastSearchResult.foundColumn; assertEquals("column must be updated", firstColumn, foundColumn); // the last char(s) of all values is the row index // here we are searching for an entry in the next row relative to // the previous search and expect the match in the first column (index = 0); int nextRow = row + 1; String secondSearchText = String.valueOf(nextRow); int secondFoundIndex = table.getSearchable().search(secondSearchText, nextRow); // sanity assert assertEquals("must find match in same row", nextRow, secondFoundIndex); assertEquals("column must be updated", 0, ((TableSearchable) table.getSearchable()).lastSearchResult.foundColumn); } /** * test if match in same row but different column is found in forward * search. * */ @Test public void testTableFoundNextColumnInSameRow() { JXTable table = new JXTable(new TestTableModel()); int row = 90; int firstColumn = 0; String firstSearchText = table.getValueAt(row, firstColumn).toString(); int foundIndex = table.getSearchable().search(firstSearchText); assertEquals("last line found", row, foundIndex); String secondSearchText = table.getValueAt(row, firstColumn +1).toString(); int secondFoundIndex = table.getSearchable().search(secondSearchText, foundIndex); assertEquals("must find match in same row", foundIndex, secondFoundIndex); } /** * Issue #718-swingx: shared FindPanel not updated on LF change. * * Here: check that dialog is new for different owner and old has been disposed. */ @Test public void testFindDialogNew() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } JXFrame frame = new JXFrame(); JXTable table = new JXTable(); frame.add(table); JComponent findPanel = SearchFactory.getInstance().getSharedFindPanel(); // show search dialog for a searchable SearchFactory.getInstance().showFindDialog(table, table.getSearchable()); Window window = SwingUtilities.getWindowAncestor(findPanel); assertSame(frame, window.getOwner()); // setup of second searchable JXFrame second = new JXFrame(); JXTree tree = new JXTree(); second.add(tree); // show search dialog for a searchable SearchFactory.getInstance().showFindDialog(tree, tree.getSearchable()); assertFalse("previous window must not be displayable", window.isDisplayable()); assertSame(second, SwingUtilities.getWindowAncestor(findPanel).getOwner()); } /** * Issue #720: JXTree - selection lost on release the searchable. * * assert JXList behaviour. * Note: JXList not clearing the selection has been an accidental, undocumented * side-effect of DefaultListSelectionModel.setSelectionInterval - it backs * out silently on negative indices. */ @Test public void testKeepSelectionOnNotFoundList() { JXList list = new JXList(new TestListModel()); PatternModel model = new PatternModel(); model.setRawText("one9"); int row = list.getSearchable().search(model.getPattern()); // sanity: found at expected row assertEquals(90, row); // sanity: selection is match marker assertEquals(row, list.getSelectedIndex()); list.getSearchable().search((Pattern) null); assertEquals("not found must not reset selection", row, list.getSelectedIndex()); } /** * Issue #720: JXTree - selection lost on release the searchable. * * assert JXTable behaviour. */ @Test public void testKeepSelectionOnNotFoundTable() { JXTable table = new JXTable(new TestTableModel()); PatternModel model = new PatternModel(); model.setRawText("one9"); int row = table.getSearchable().search(model.getPattern()); // sanity: found at expected row assertEquals(9, row); // sanity: selection is match marker assertEquals(row, table.getSelectedRow()); table.getSearchable().search((Pattern) null); assertEquals("not found must not reset selection", row, table.getSelectedRow()); } /** * Issue #720: JXTree - selection lost on release the searchable. * * Base problem was a slight difference in the tree- vs. ListSelectionModel * (not completely documented). The TreeSelection * interprets a null path array as clearSelection, same for null path in * setSelectionPaths and setSelectionPath. A null element in the array is * undocumented, but setPaths protects itself and interprets an array containing * null paths only as clearSelection as well. * */ @Test public void testKeepSelectionOnNotFoundTree() { JXTree tree = new JXTree(); PatternModel model = new PatternModel(); model.setRawText("foo"); int row = tree.getSearchable().search(model.getPattern()); // sanity: found at expected row assertEquals(3, row); // sanity: selection is match marker assertEquals(row, tree.getMinSelectionRow()); tree.getSearchable().search((Pattern) null); assertEquals("not found must not reset selection", row, tree.getMinSelectionRow()); } /** * Issue #487-swingx: NPE if instantiating with not null Searchable */ @SuppressWarnings("unused") @Test public void testFindBarNPEConstructor() { JXFindBar findBar = new JXFindBar(new JXTable().getSearchable()); } /** * Issue #487-swingx: NPE if setting a not-null Searchable before * showing */ @Test public void testFindBarNPE() { Searchable searchable = new JXTable().getSearchable(); JXFindBar findBar = new JXFindBar(); findBar.setSearchable(searchable); } /** * Issue #374-swingx: default search keystroke never found. * * This was probably introduced when fixing #353-swingx: * swingx must not try to leave sandbox. * */ @Test public void testSearchKeyStroke() { if (System.getSecurityManager() != null) { LOG.info("cannot run testSearchKeyStroke - SecurityManager installed"); return; } // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run testSearchKeyStroke - headless environment"); return; } assertNotNull("searchfactory must return search accelerator", SearchFactory.getInstance().getSearchAccelerator()); } /** * Test SearchHighlight used in incremental search of JXTable. * */ @Test public void testTableIncrementalHighlighter() { JXTable table = new JXTable(new TestTableModel()); table.putClientProperty(AbstractSearchable.MATCH_HIGHLIGHTER, Boolean.TRUE); int row = 3; int column = 1; String firstSearchText = "wo" + row; PatternModel model = new PatternModel(); model.setRawText(firstSearchText); // make sure we had a match int foundIndex = table.getSearchable().search(model.getPattern(), -1); assertEquals("must return be found", row, foundIndex); Component comp = table.prepareRenderer(table.getCellRenderer(row, column), row, column); assertEquals(Color.YELLOW.brighter(), comp.getBackground()); } /** * test incremental search in JXTable. * */ @Test public void testTableIncremental() { JXTable table = new JXTable(new TestTableModel()); String firstSearchText = "on"; PatternModel model = new PatternModel(); model.setRawText(firstSearchText); // make sure we had a match int foundIndex = table.getSearchable().search(model.getPattern(), -1); assertEquals("must return be found", 0, foundIndex); // extended searchstring String secondSearchText ="one"; model.setRawText(secondSearchText); // start search with row >> getRowCount() int secondFoundIndex = table.getSearchable().search(model.getPattern(), foundIndex); assertEquals("must not be found", foundIndex, secondFoundIndex); } /** * test if starting a search in a non-contained index results * in not-found state. * */ @Test public void testTableInvalidStartIndex() { JXTable table = new JXTable(new TestTableModel()); String firstSearchText = "one"; PatternModel model = new PatternModel(); model.setRawText(firstSearchText); // make sure we had a match int foundIndex = table.getSearchable().search(model.getPattern(), -1); assertEquals("must return be found", 0, foundIndex); // start search with row >> getRowCount() int notFoundIndex = table.getSearchable().search(model.getPattern(), table.getRowCount() * 5, false); assertEquals("must not be found", -1, notFoundIndex); } /** * test if match in same row but different column is found in backwards * search. * */ @Test public void testTableFoundPreviousColumnInSameRow() { JXTable table = new JXTable(new TestTableModel()); int lastColumn = table.getColumnCount() -1; int row = 90; String firstSearchText = table.getValueAt(row, lastColumn).toString(); // need a pattern for backwards search PatternModel model = new PatternModel(); model.setRawText(firstSearchText); int foundIndex = table.getSearchable().search(model.getPattern(), -1, true); assertEquals("last line found", row, foundIndex); String secondSearchText = table.getValueAt(row, lastColumn - 1).toString(); model.setRawText(secondSearchText); int secondFoundIndex = table.getSearchable().search(model.getPattern(), foundIndex, true); assertEquals("must find match in same row", foundIndex, secondFoundIndex); } /** * check if not-wrapping returns not found marker (-1). * */ @Test public void testTableNotFoundWithoutWrapping() { JXTable table = new JXTable(new TestTableModel()); int row = 90; String searchText = table.getValueAt(row, 0).toString(); int foundIndex = table.getSearchable().search(searchText); assertEquals("last line found", row, foundIndex); int notFoundIndex = table.getSearchable().search(searchText, foundIndex); assertEquals("nothing found after last line", -1, notFoundIndex); } /** * test if not-wrapping returns not found marker (-1) if the * last found position is the last row. * */ @Test public void testTableNotFoundLastRowWithoutWrapping() { JXTable table = new JXTable(new TestTableModel()); int row = table.getRowCount() - 1; String searchText = table.getValueAt(row, 0).toString(); int foundIndex = table.getSearchable().search(searchText); assertEquals("last line found", row, foundIndex); int notFoundIndex = table.getSearchable().search(searchText, foundIndex); assertEquals("nothing found after last line", -1, notFoundIndex); } /** * test if not-wrapping returns not found marker (-1) if the * last found position is the first row. * */ @Test public void testTableNotFoundFirstRowWithoutWrapping() { JXTable table = new JXTable(new TestTableModel()); int row = 0; PatternModel model = new PatternModel(); String searchText = table.getValueAt(row, 0).toString(); model.setRawText(searchText); int foundIndex = table.getSearchable().search(model.getPattern(), row + 1, true); assertEquals("last line found", row, foundIndex); int notFoundIndex = table.getSearchable().search(model.getPattern(), foundIndex, true); assertEquals("nothing found after last line", -1, notFoundIndex); } /** * Issue #??-swingx: backwards search not implemented in JXEditorPane. * */ @Test public void testEditorBackwards() { JXEditorPane editor = new JXEditorPane(); String text = "fou four"; editor.setText(text); int first = 2; try { editor.getDocument().getText(first, editor.getDocument().getLength() - first); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } PatternModel model = new PatternModel(); model.setRawText("fo"); int foIndex = editor.getSearchable().search(model.getPattern(), text.length() - 1, true); assertEquals("found index must be last occurence", text.lastIndexOf("fo"), foIndex); } /** * Test incremental searching: index must be the same if * extended text still matches. * */ @Test public void testEditorIncremental() { JXEditorPane editor = new JXEditorPane(); String text = "fou four"; editor.setText(text); String search = "fo"; int first = editor.getSearchable().search(search, 0); assertEquals(0, first); String searchExt = search + "u"; int second = editor.getSearchable().search(searchExt, first); assertEquals("index must be same if extension matches", first, second); } /** * NPE on no-match? */ @Test public void testEditorIncrementalNotFound() { JXEditorPane editor = new JXEditorPane(); String text = "fou four"; editor.setText(text); String search = "ou"; int first = editor.getSearchable().search(search, 0); assertEquals(1, first); String searchExt = search + "u"; try { int second = editor.getSearchable().search(searchExt, first); assertEquals("not found", -1, second); } catch (NullPointerException npe) { fail("npe"); } } /** * test that search moves forward. * */ @Test public void testEditorFindNext() { JXEditorPane editor = new JXEditorPane(); String text = "fou four"; editor.setText(text); String search = "fou"; int first = editor.getSearchable().search(search, -1); assertEquals(0, first); int second = editor.getSearchable().search(search, first); assertEquals(4, second); } /** * Testing graceful handling of start index out-of range * of document size. * */ @Test public void testEditorTolerateExceedingStartIndex() { JXEditorPane editor = new JXEditorPane(); editor.setText("fou four"); try { int foIndex = editor.getSearchable().search("fo", 20); assertEquals(-1, foIndex); } catch (Exception ex) { fail("search must not throw if index out off range"); } } @Test public void testEditorEmptyDocument() { JXEditorPane editor = new JXEditorPane(); int foIndex = editor.getSearchable().search("fo", -1); assertEquals(-1, foIndex); foIndex = editor.getSearchable().search("fo", 0); assertEquals(-1, foIndex); } /** * testing incremental search: * must start search at given position (inclusive). * * This implies that search(xx, -1) is equivalent to * search(xx, 0) if the match is at position 0. * */ @Test public void testEditorBoundarySearchIndex() { JXEditorPane editor = new JXEditorPane(); editor.setText("f"); // can't test in one method - the searchable has internal state int startOff = editor.getSearchable().search("f", -1); assertEquals("must return first occurence if startIndex if off", 0, startOff); // sanity - must not find mismatch if longer int foIndex = editor.getSearchable().search("fo", -1); assertEquals("must not find exceeding text", -1, foIndex); foIndex = editor.getSearchable().search("f", 0); assertEquals("must return first occurence from startIndex inclusively",0 , foIndex); } /** * Issue #100-swingx: expect to return the start of the match. * Only then it's possible to implement a reasonably behaved * incremental search. * */ @Test public void testEditorFindMatchPosition() { JXEditorPane editor = new JXEditorPane(); editor.setText("fou four"); int foIndex = editor.getSearchable().search("fo", -1); assertEquals(0, foIndex); } /** * testing Searchable assumption along the lines of: * found = searchable.search(text) * searchable.getValueAt(found).startsWith(text) or * searchable.getValueAt(found).contains(text) * */ @Test public void testEditorFindMatch() { JXEditorPane editor = new JXEditorPane(); editor.setText("fou four"); int foIndex = editor.getSearchable().search("fo", -1); assertEquals("selected text must be equals to input", "fo", editor.getSelectedText()); try { String textAt = editor.getText(foIndex, 2); assertEquals("fo", textAt); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testTable() { JXTable table = new JXTable(new TestTableModel()); // There are 100 instances of "One" in the test document int useIndex = -1; int lastIndex = -1; for (int i = 0; i < 100; i++) { lastIndex = table.getSearchable().search("One", useIndex); assertTrue(lastIndex != -1); assertTrue(lastIndex != useIndex); assertEquals("Row not selected", lastIndex, table.getSelectedRow()); assertEquals("Column not selected", 0, table.getSelectedColumn()); String value = (String)table.getValueAt(table.getSelectedRow(), table.getSelectedColumn()); assertTrue(value.startsWith("One")); useIndex = lastIndex; } } @Test public void testNullSearchable() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { return; } JXFindPanel find = new JXFindPanel(); find.match(); } public static class TestTableModel extends AbstractTableModel { public static String[] data = { "One", "Two", "Three", "Four", "Five" }; public int getRowCount() { return 100; } public int getColumnCount() { return data.length; } public Object getValueAt(int row, int column) { checkCoordinates(row, column); StringBuffer buffer = new StringBuffer(data[column]); buffer.append(row); return buffer.toString(); } private void checkCoordinates(int row, int column) { if ((row < 0) || (row >= getRowCount()) || (column < 0) || (column >= getColumnCount())) throw new IllegalArgumentException("coordinates invalid - row/column: " + row + "/" + column); } } public static class TestListModel extends AbstractListModel { public int getSize() { return 100; } public Object getElementAt(int index) { int dataPos = index % TestTableModel.data.length; return TestTableModel.data[dataPos] + index; } } /** * A small class that implements the Searchable interface. */ public static class TestSearchable extends JLabel implements Searchable { private boolean succeed; public TestSearchable() { this(false); } /** * @param succeed flag to indicate that all searches succeed. */ public TestSearchable(boolean succeed) { this.succeed = succeed; } public int search(String searchString) { return search(searchString, -1); } public int search(String searchString, int startIndex) { return succeed ? 100 : -1; } public int search(String searchString, int startIndex, boolean backward) { return succeed ? 100 : -1; } public int search(Pattern pattern) { return search(pattern, -1); } public int search(Pattern pattern, int startIndex) { return succeed ? 100 : -1; } public int search(Pattern pattern, int startIndex, boolean backwards) { return succeed ? 100 : -1; } } } swingx-1.0-src/src/test/org/jdesktop/swingx/search/SearchableTest.java0000644000175000017500000001623211210401722024714 0ustar tonytony/* * $Id: SearchableTest.java,v 1.2 2008/12/02 17:11:05 kleopatra Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.search; import java.util.Arrays; import junit.framework.TestCase; import org.jdesktop.swingx.JXList; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTree; import org.jdesktop.swingx.decorator.AbstractHighlighter; import org.jdesktop.swingx.decorator.BorderHighlighter; import org.jdesktop.swingx.decorator.SearchPredicate; import org.jdesktop.swingx.search.FindTest.TestListModel; import org.jdesktop.swingx.search.FindTest.TestTableModel; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * TODO add type doc * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class SearchableTest extends TestCase { /** * test that any old matchHighlighter is removed from the * target's pipeline. * */ @Test public void testSetMatchHighlighterCleanup() { JXTable table = new JXTable(new TestTableModel()); table.putClientProperty(AbstractSearchable.MATCH_HIGHLIGHTER, Boolean.TRUE); // move first column to end int firstColumn = 0; int row = 39; String firstSearchText = table.getValueAt(row, firstColumn).toString(); PatternModel model = new PatternModel(); model.setRawText(firstSearchText); // initialize searchable to "found state" table.getSearchable().search(model.getPattern(), -1); AbstractHighlighter hl = ((AbstractSearchable) table.getSearchable()).getMatchHighlighter(); assertSame(hl, table.getHighlighters()[table.getHighlighters().length - 1]); AbstractHighlighter replaceHL = new BorderHighlighter(); ((AbstractSearchable) table.getSearchable()).setMatchHighlighter(replaceHL); // initialize searchable to "found state" table.getSearchable().search(model.getPattern(), -1); assertSame(replaceHL, table.getHighlighters()[table.getHighlighters().length - 1]); assertFalse("previous matchhighlighter must be removed", Arrays.asList(table.getHighlighters()).contains(hl)); } /** * test that the search predicate's highlight column index is in * model coordinates * */ @Test public void testTableMovedColumn() { JXTable table = new JXTable(new TestTableModel()); table.putClientProperty(AbstractSearchable.MATCH_HIGHLIGHTER, Boolean.TRUE); // move first column to end int firstColumn = table.getColumnCount() - 1; table.getColumnModel().moveColumn(0, firstColumn); int row = 39; String firstSearchText = table.getValueAt(row, firstColumn).toString(); PatternModel model = new PatternModel(); model.setRawText(firstSearchText); // initialize searchable to "found state" table.getSearchable().search(model.getPattern(), -1); // column index in view coordinates int foundColumn = ((AbstractSearchable) table.getSearchable()).lastSearchResult.foundColumn; assertEquals("column must be updated", firstColumn, foundColumn); AbstractHighlighter hl = ((AbstractSearchable) table.getSearchable()).getMatchHighlighter(); assertTrue("searchPredicate", hl.getHighlightPredicate() instanceof SearchPredicate); SearchPredicate predicate = (SearchPredicate) hl.getHighlightPredicate(); assertEquals(table.convertColumnIndexToModel(firstColumn), predicate.getHighlightColumn()); } /** * test that the search predicate's highlight column index is in * model coordinates * */ @Test public void testTableUseMatchHighlighter() { JXTable table = new JXTable(new TestTableModel()); table.putClientProperty(AbstractSearchable.MATCH_HIGHLIGHTER, Boolean.TRUE); assertTrue("use match highlighter", ((AbstractSearchable) table.getSearchable()).markByHighlighter()); AbstractHighlighter hl = ((AbstractSearchable) table.getSearchable()).getMatchHighlighter(); assertNotNull(hl); } /** * test that the search predicate's highlight column index is in * model coordinates * */ @Test public void testListUseMatchHighlighter() { JXList table = new JXList(new TestListModel()); table.putClientProperty(AbstractSearchable.MATCH_HIGHLIGHTER, Boolean.TRUE); assertTrue("use match highlighter", ((AbstractSearchable) table.getSearchable()).markByHighlighter()); AbstractHighlighter hl = ((AbstractSearchable) table.getSearchable()).getMatchHighlighter(); assertNotNull(hl); } /** * test that the search predicate's highlight column index is in * model coordinates * */ @Test public void testTreeUseMatchHighlighter() { JXTree table = new JXTree(); table.putClientProperty(AbstractSearchable.MATCH_HIGHLIGHTER, Boolean.TRUE); assertTrue("use match highlighter", ((AbstractSearchable) table.getSearchable()).markByHighlighter()); AbstractHighlighter hl = ((AbstractSearchable) table.getSearchable()).getMatchHighlighter(); assertNotNull(hl); } /** * Task: new api in AbstractSearchable to support match highlighter. */ @Test public void testTargetTable() { JXTable table = new JXTable(); AbstractSearchable searchable = (AbstractSearchable) table.getSearchable(); assertSame("get target same as table", table, searchable.getTarget()); } /** * Task: new api in AbstractSearchable to support match highlighter. */ @Test public void testTargetList() { JXList table = new JXList(); AbstractSearchable searchable = (AbstractSearchable) table.getSearchable(); assertSame("get target same as table", table, searchable.getTarget()); } /** * Task: new api in AbstractSearchable to support match highlighter. */ @Test public void testTargetTree() { JXTree table = new JXTree(); AbstractSearchable searchable = (AbstractSearchable) table.getSearchable(); assertSame("get target same as table", table, searchable.getTarget()); } @Override protected void setUp() throws Exception { super.setUp(); // sanity: new instance for each test SearchFactory.setInstance(new SearchFactory()); } } swingx-1.0-src/src/test/org/jdesktop/swingx/search/PatternModelTest.java0000644000175000017500000002007111210401722025255 0ustar tonytony/* * $Id: PatternModelTest.java,v 1.2 2008/10/11 20:42:33 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.search; import java.util.List; import junit.framework.TestCase; import org.jdesktop.swingx.search.PatternModel; import org.jdesktop.test.PropertyChangeReport; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * Testing PatternModel. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class PatternModelTest extends TestCase { final static String startAnchor = "^"; final static String endAnchor = "$"; final static String middleStartAnchor = "some" + startAnchor + "one"; final static String middleEndAnchor = "some" + endAnchor + "one"; private PropertyChangeReport propertyReport; @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } /** * test initial autoAdjust of foundIndex in backward search. * */ @Test public void testFoundIndexAutoAdjustBackward() { PatternModel model = new PatternModel(); model.setBackwards(true); assertTrue("is autoAdjust by default", model.isAutoAdjustFoundIndex()); model.addPropertyChangeListener(propertyReport); int foundIndex = 10; model.setFoundIndex(foundIndex); // assert changed value assertEquals("foundIndex must be set", foundIndex -1, model.getFoundIndex()); assertTrue("changing foundIndex must have fired foundIndex property", propertyReport.hasEvents("foundIndex")); } /** * test initial autoAdjust of foundIndex in forward search. * */ @Test public void testFoundIndexAutoAdjustNotFound() { PatternModel model = new PatternModel(); assertTrue("is autoAdjust by default", model.isAutoAdjustFoundIndex()); model.addPropertyChangeListener(propertyReport); int foundIndex = -1; model.setFoundIndex(foundIndex); // assert changed value assertEquals("foundIndex must be set", foundIndex, model.getFoundIndex()); } /** * test initial autoAdjust of foundIndex in forward search. * */ @Test public void testFoundIndexAutoAdjustForward() { PatternModel model = new PatternModel(); assertTrue("is autoAdjust by default", model.isAutoAdjustFoundIndex()); model.addPropertyChangeListener(propertyReport); int foundIndex = 10; model.setFoundIndex(foundIndex); // assert changed value assertEquals("foundIndex must be set", foundIndex + 1, model.getFoundIndex()); assertTrue("changing foundIndex must have fired foundIndex property", propertyReport.hasEvents("foundIndex")); } /** * test initial value and notification of "foundIndex" property. * */ @Test public void testFoundIndex() { PatternModel model = new PatternModel(); model.setIncremental(true); // assert initial value assertEquals("not found on start", -1, model.getFoundIndex()); model.addPropertyChangeListener(propertyReport); model.setFoundIndex(10); // assert changed value assertEquals("foundIndex must be set", 10, model.getFoundIndex()); assertTrue("changing foundIndex must have fired foundIndex property", propertyReport.hasEvents("foundIndex")); } @Test public void testCaseSensitive() { PatternModel model = new PatternModel(); model.setRawText("tab"); assertTrue("must find not case sensitive by default", model.getPattern().matcher("JTABLE").find()); model.addPropertyChangeListener(propertyReport); model.setCaseSensitive(true); assertTrue("changing case sensitive must fire casesensitive property", propertyReport.hasEvents("caseSensitive")); assertTrue("changing case sensitive must fire pattern property", propertyReport.hasEvents("pattern")); } @Test public void testAvailableMatchRules() { PatternModel model = new PatternModel(); List rules = model.getMatchRules(); assertNotNull("rules must not be null", rules); } @Test public void testRegexCreator() { PatternModel model = new PatternModel(); model.addPropertyChangeListener(propertyReport); model.setRegexCreatorKey(PatternModel.REGEX_UNCHANGED); assertEquals("search string mode must be", PatternModel.REGEX_UNCHANGED, model.getRegexCreatorKey()); assertTrue(propertyReport.hasEvents("regexCreatorKey")); // model.setSearchStringMode(PatternModel.SEARCH_STRING_ANCHORED); // model.setSearchStringMode(PatternModel.SEARCH_STRING_WILDCARD); // model.setSearchStringMode(PatternModel.SEARCH_STRING_EXPLICIT); } @Test public void testMatchRule() { PatternModel model = new PatternModel(); model.addPropertyChangeListener(propertyReport); // default searchStringMode assertEquals("search string mode must be", PatternModel.REGEX_MATCH_RULES, model.getRegexCreatorKey()); // default searchCategory assertEquals("search category must be ", PatternModel.MATCH_RULE_CONTAINS, model.getMatchRule()); // change category and test if property change is fired model.setMatchRule(PatternModel.MATCH_RULE_EQUALS); assertTrue("model must have fired " + "matchRule ", propertyReport.hasEvents("matchRule")); } @Test public void testChangeMatchRule() { PatternModel model = new PatternModel(); String contained = "t"; model.setRawText(contained); String match = "x" + contained + "x"; assertTrue("pattern must find " + match, model.getPattern().matcher(match).find()); model.addPropertyChangeListener(propertyReport); model.setMatchRule(PatternModel.MATCH_RULE_EQUALS); assertTrue("model must have fire pattern change", propertyReport.hasEvents("pattern")); assertFalse("pattern must reject " + match, model.getPattern().matcher(match).find()); model.setMatchRule(PatternModel.MATCH_RULE_STARTSWITH); match = "txx"; assertTrue("pattern must find " + match, model.getPattern().matcher(match).find()); model.setMatchRule(PatternModel.MATCH_RULE_ENDSWITH); match = "xxt"; assertTrue("pattern must find " + match, model.getPattern().matcher(match).find()); } /** * test if rawtext is treated as literal. * */ @Test public void testRawMiddleAnchorTokens() { PatternModel patternModel = new PatternModel(); patternModel.setRawText(startAnchor); String literalAnchor = "some" + startAnchor +"one"; assertTrue("must find literal containing startAnchor " + literalAnchor, patternModel.getPattern().matcher(literalAnchor).find()); String literal = "someone"; assertFalse("must reject literal not containing startAnchor " + literal, patternModel.getPattern().matcher(literal).find()); } /** * test if rawtext is treated as literal. * */ @Test public void testRawStartAnchor() { PatternModel patternModel = new PatternModel(); String anchored = startAnchor + "hap"; patternModel.setRawText(anchored); String literalAnchor = startAnchor + "happy"; assertTrue("must find literal containing startAnchor " + literalAnchor, patternModel.getPattern().matcher(literalAnchor).find()); String literal = "happy"; assertFalse("must reject literal not containing startAnchor " + literal, patternModel.getPattern().matcher(literal).find()); } @Override protected void setUp() { propertyReport = new PropertyChangeReport(); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXTableHeaderIssues.java0000644000175000017500000002657711210401722024371 0ustar tonytony/* * Created on 28.06.2006 * */ package org.jdesktop.swingx; import java.awt.Component; import java.awt.Dimension; import java.awt.Insets; import java.awt.Point; import java.awt.event.ActionEvent; import java.util.List; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.border.AbstractBorder; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.plaf.metal.MetalBorders; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.decorator.SortOrder; import org.jdesktop.swingx.table.DefaultTableColumnModelExt; import org.jdesktop.swingx.table.TableColumnExt; public class JXTableHeaderIssues extends JXTableHeaderTest { @SuppressWarnings("all") private static final Logger LOG = Logger .getLogger(JXTableHeaderIssues.class.getName()); public static void main(String args[]) { JXTableHeaderIssues test = new JXTableHeaderIssues(); // setSystemLF(true); try { // test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Siz.*"); // test.runInteractiveTests("interactive.*Render.*"); test.runInteractiveTests("interactive.*Auto.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #683-swingx: autoscroll if columns are dragged outside. * * Enabled if autoscroll property is true. Changed default to true. * Temporarily disabled - clashes with table's horizontalScrollEnabled. */ public void testAutoscrollsDefaultEmptyConstructor() { JXTableHeader header = new JXTableHeader(); assertTrue(header.getAutoscrolls()); } /** * Quick proof-of-concept: JXTableHeader can go dirty and * suppress moving of "docked" column. * */ public void interactiveDockColumn() { final JXTableHeader header = new JXTableHeader() { private int oldDistance; @Override public void setDraggedDistance(int distance) { oldDistance = getDraggedDistance(); if (isDocked(getDraggedColumn())) { distance = 0; } if (isDraggedOverDocked(distance)) { distance = 0; setDraggedColumn(null); } super.setDraggedDistance(distance); } private boolean isDraggedOverDocked(int distance) { if (getDraggedColumn() == null) return false; int dragPosition = getDragX(distance); int columnUnder = columnAtPoint(new Point(dragPosition, 0)); if (columnUnder >= 0) { return isDocked(getColumnModel().getColumn(columnUnder)); } return false; } private int getDragX(int distance) { DefaultTableColumnModelExt columnModel = (DefaultTableColumnModelExt) getColumnModel(); List columns = columnModel.getColumns(false); int startX = 0; for (int i = 0; i < columns.size(); i++) { if (columns.get(i) == getDraggedColumn()) { // at the wrong column the very moment // before the dock neighbour is // actually replaced with the second next dock neighbour // need to add the stop-column width as well if (distance * oldDistance < 0) { startX += columns.get(i).getWidth(); } break; } startX += columns.get(i).getWidth(); } return startX + distance; } private boolean isDocked(TableColumn column) { if (column instanceof TableColumnExt) { return Boolean.TRUE.equals(((TableColumnExt) column).getClientProperty("docked")); } return false; } }; final TableColumnModel cModel = new DefaultTableColumnModelExt() { @Override public void moveColumn(int columnIndex, int newIndex) { if (isDocked(columnIndex) || isDocked(newIndex)) return; super.moveColumn(columnIndex, newIndex); } private boolean isDocked(int columnIndex) { TableColumnExt column = getColumnExt(columnIndex); if (column != null) { return Boolean.TRUE.equals(column.getClientProperty("docked")); } return false; } }; JXTable table = new JXTable(10, 5) { @Override protected JTableHeader createDefaultTableHeader() { header.setColumnModel(columnModel); return header; } @Override protected TableColumnModel createDefaultColumnModel() { return cModel; } }; table.getColumnExt(0).putClientProperty("docked", Boolean.TRUE); showWithScrollingInFrame(table, "block dragging"); } /** * Issue #281-swingx, Issue #334-swing: * header should be auto-repainted on changes to * header title, value. Must update size if appropriate. * * still not solved: core #4292511 - autowrapping is weird, * even with the swingx fix * */ public void interactiveUpdateHeaderAndSizeRequirements() { final String[] alternate = { // "simple", "This is a test of a large label to see if it wraps ", "simple", // "

Line 1
Line 2
" }; final JXTable table = new JXTable(10, 2); table.getColumn(0).setHeaderValue(alternate[0]); table.getColumn(1).setHeaderValue(alternate[1]); JXFrame frame = wrapWithScrollingInFrame(table, "update header"); Action action = new AbstractAction("update headervalue") { boolean first; public void actionPerformed(ActionEvent e) { table.getColumn(1).setHeaderValue(first ? alternate[0] : alternate[1]); first = !first; } }; addAction(frame, action); frame.setVisible(true); } /** * Issue 337-swingx: header heigth depends on sort icon (for ocean only?) * Looks like a problem in MetalBorders.TableHeaderBorder: extends AbstractBorder but * does not override getBorderInsets(comp, insets) which is used by the labelUI getPrefSize * to determine the insets and calc the view rect. * */ @SuppressWarnings("unused") public void interactiveSortedPreferredHeight() { final JXTable table = new JXTable(10, 1); table.getColumnExt(0).setPreferredWidth(200); final JTable other = new JTable(10, 1); // other.setAutoCreateRowSorter(true); other.getColumnModel().getColumn(0).setPreferredWidth(200); final DefaultTableCellRenderer renderer =(DefaultTableCellRenderer) other.getTableHeader().getDefaultRenderer(); Component comp = renderer.getTableCellRendererComponent(other, "A", false, false, -1, 0); final Border border = renderer.getBorder(); final Border emptyBorder = BorderFactory.createEmptyBorder(0, 0, 0, 20); TableCellRenderer wrapper = new TableCellRenderer() { public Component getTableCellRendererComponent(JTable mtable, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JComponent comp = (JComponent) renderer.getTableCellRendererComponent(mtable, value, isSelected, hasFocus, row, column); if (table.getSortedColumn() == null) { comp.setBorder(border); } else { comp.setBorder(new CompoundBorder(border, emptyBorder)); } return comp; } }; other.getTableHeader().setDefaultRenderer(wrapper); Action action = new AbstractActionExt("toggle sorter order") { public void actionPerformed(ActionEvent e) { if (table.getSortedColumn() == null) { table.toggleSortOrder(0); } else { table.resetSortOrder(); } table.getTableHeader().revalidate(); other.getTableHeader().revalidate(); } }; JXFrame frame = wrapWithScrollingInFrame(table, other, "xheader <--> header border height"); addAction(frame, action); frame.setVisible(true); } /** * Issue 337-swingx: header heigth depends on sort icon (for ocean only?) * Looks like a problem in MetalBorders.TableHeaderBorder: extends AbstractBorder but * does not override getBorderInsets(comp, insets) which is used by the labelUI getPrefSize * to determine the insets and calc the view rect. * */ public void testMetalBorderInsets() { JLabel label = new JLabel("sometext"); AbstractBorder metalBorder = new MetalBorders.TableHeaderBorder(); assertEquals(metalBorder.getBorderInsets(label), metalBorder.getBorderInsets(label, new Insets(0,0,0,0))); } /** * Issue 337-swingx: header heigth depends on sort icon (for ocean only?) * Looks like a problem in MetalBorders.TableHeaderBorder: extends AbstractBorder but * does not override getBorderInsets(comp, insets) which is used by the labelUI getPrefSize * to determine the insets and calc the view rect. * * Here we compound the default metal border */ public void testMetalBorderInsetsHack() { JLabel label = new JLabel("sometext"); AbstractBorder metalBorder = new MetalBorders.TableHeaderBorder(); CompoundBorder compound = new CompoundBorder(metalBorder, BorderFactory.createEmptyBorder()); assertEquals(compound.getBorderInsets(label), compound.getBorderInsets(label, new Insets(0,0,0,0))); } /** * Issue 337-swingx: header heigth depends on sort icon (for ocean only?) * NOTE: this seems to be independent of the tweaks to xTableHeaders * prefSize. */ public void testSortedPreferredHeight() { JXTable table = new JXTable(10, 2); JXTableHeader tableHeader = (JXTableHeader) table.getTableHeader(); Dimension dim = tableHeader.getPreferredSize(); table.setSortOrder(0, SortOrder.ASCENDING); assertEquals("Header pref height must be unchanged if sorted", dim.height, tableHeader.getPreferredSize().height); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXListTest.java0000644000175000017500000012314411210401722022574 0ustar tonytony/* * $Id: JXListTest.java,v 1.51 2009/01/21 18:37:27 kschaefe Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx; import java.awt.Color; import java.beans.PropertyChangeListener; import java.net.MalformedURLException; import java.net.URL; import java.text.Collator; import java.util.Vector; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListCellRenderer; import javax.swing.DefaultListModel; import javax.swing.DefaultListSelectionModel; import javax.swing.ListCellRenderer; import javax.swing.ListModel; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; import org.jdesktop.swingx.JXList.DelegatingRenderer; import org.jdesktop.swingx.decorator.ColorHighlighter; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.Filter; import org.jdesktop.swingx.decorator.FilterPipeline; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.PatternFilter; import org.jdesktop.swingx.decorator.SearchPredicate; import org.jdesktop.swingx.decorator.SelectionMapper; import org.jdesktop.swingx.decorator.SortKey; import org.jdesktop.swingx.decorator.SortOrder; import org.jdesktop.swingx.hyperlink.LinkModel; import org.jdesktop.swingx.renderer.DefaultListRenderer; import org.jdesktop.swingx.renderer.StringValue; import org.jdesktop.swingx.renderer.StringValues; import org.jdesktop.swingx.rollover.ListRolloverController; import org.jdesktop.swingx.rollover.RolloverProducer; import org.jdesktop.test.AncientSwingTeam; import org.jdesktop.test.ListDataReport; import org.jdesktop.test.PropertyChangeReport; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * Testing JXList. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class JXListTest extends InteractiveTestCase { protected ListModel listModel; protected DefaultListModel ascendingListModel; @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } /** * Issue #855-swingx: throws AIOOB on repeated remove/add. * Reason is that the lead/anchor is not removed in removeIndexInterval */ @Test public void testAddRemoveSelect() { DefaultListModel model = new DefaultListModel(); model.addElement("something"); JXList list = new JXList(model, true); list.setSortOrder(SortOrder.ASCENDING); list.setSelectedIndex(0); model.remove(0); assertTrue("sanity - empty selection after remove", list.isSelectionEmpty()); model.addElement("element"); assertTrue("sanity - empty selection re-adding", list.isSelectionEmpty()); list.setSelectedIndex(0); } /** * Issue #855-swingx: throws AIOOB on repeated remove/add. * Reason is that the lead/anchor is not removed in removeIndexInterval. * * Compare JXTable behaviour: doesn't blow. JXList probably does because of * the necessary event mapping. Sequence of selection/pipeline induced * cleanup is different. * */ @Test public void testAddRemoveSelectTable() { DefaultTableModel model = new DefaultTableModel(0, 1); model.addRow(new Object[] {"something"}); JXTable list = new JXTable(model); list.setSortOrder(0, SortOrder.ASCENDING); list.setRowSelectionInterval(0, 0); model.removeRow(0); assertTrue("sanity - empty selection after remove", list.getSelectionModel().isSelectionEmpty()); model.addRow(new Object[] {"something"}); assertTrue("sanity - empty selection re-adding", list.getSelectionModel().isSelectionEmpty()); list.setRowSelectionInterval(0, 0); } /** * Issue #816-swingx: Delegating renderer must create list's default. * Consistent api: expose wrappedRenderer the same way as wrappedModel */ @Test public void testWrappedRendererDefault() { JXList list = new JXList(); DelegatingRenderer renderer = (DelegatingRenderer) list.getCellRenderer(); assertSame("wrapping renderer must use list's default on null", renderer.getDelegateRenderer(), list.getWrappedCellRenderer()); } /** * Issue #816-swingx: Delegating renderer must create list's default. * Consistent api: expose wrappedRenderer the same way as wrappedModel */ @Test public void testWrappedRendererCustom() { JXList list = new JXList(); DelegatingRenderer renderer = (DelegatingRenderer) list.getCellRenderer(); ListCellRenderer custom = new DefaultListRenderer(); list.setCellRenderer(custom); assertSame("wrapping renderer must use list's default on null", renderer.getDelegateRenderer(), list.getWrappedCellRenderer()); } /** * Issue #816-swingx: Delegating renderer must create list's default. * Delegating uses default on null, here: default default. */ @Test public void testDelegatingRendererUseDefaultSetNull() { JXList list = new JXList(); ListCellRenderer defaultRenderer = list.createDefaultCellRenderer(); DelegatingRenderer renderer = (DelegatingRenderer) list.getCellRenderer(); list.setCellRenderer(null); assertEquals("wrapping renderer must use list's default on null", defaultRenderer.getClass(), renderer.getDelegateRenderer().getClass()); } /** * Issue #816-swingx: Delegating renderer must create list's default. * Delegating has default from list initially, here: default default. */ @Test public void testDelegatingRendererUseDefault() { JXList list = new JXList(); ListCellRenderer defaultRenderer = list.createDefaultCellRenderer(); assertEquals("sanity: creates default", DefaultListRenderer.class, defaultRenderer.getClass()); DelegatingRenderer renderer = (DelegatingRenderer) list.getCellRenderer(); assertEquals(defaultRenderer.getClass(), renderer.getDelegateRenderer().getClass()); } /** * Issue #816-swingx: Delegating renderer must create list's default. * Delegating has default from list initially, here: custom default. */ @Test public void testDelegatingRendererUseCustomDefaultSetNull() { JXList list = new JXList() { @Override protected ListCellRenderer createDefaultCellRenderer() { return new CustomDefaultRenderer(); } }; ListCellRenderer defaultRenderer = list.createDefaultCellRenderer(); DelegatingRenderer renderer = (DelegatingRenderer) list.getCellRenderer(); list.setCellRenderer(null); assertEquals("wrapping renderer must use list's default on null", defaultRenderer.getClass(), renderer.getDelegateRenderer().getClass()); } /** * Issue #816-swingx: Delegating renderer must create list's default. * Delegating has default from list initially, here: custom default. */ @Test public void testDelegatingRendererUseCustomDefault() { JXList list = new JXList() { @Override protected ListCellRenderer createDefaultCellRenderer() { return new CustomDefaultRenderer(); } }; ListCellRenderer defaultRenderer = list.createDefaultCellRenderer(); assertEquals("sanity: creates custom", CustomDefaultRenderer.class, defaultRenderer.getClass()); DelegatingRenderer renderer = (DelegatingRenderer) list.getCellRenderer(); assertEquals(defaultRenderer.getClass(), renderer.getDelegateRenderer().getClass()); } /** * Dummy extension for testing - does nothing more as super. */ public static class CustomDefaultRenderer extends DefaultListCellRenderer { } /** * Issue #767-swingx: consistent string representation. * * Here: test api on JXTable. */ @Test public void testGetString() { JXList list = new JXList(AncientSwingTeam.createNamedColorListModel()); StringValue sv = new StringValue() { public String getString(Object value) { if (value instanceof Color) { Color color = (Color) value; return "R/G/B: " + color.getRGB(); } return StringValues.TO_STRING.getString(value); } }; list.setCellRenderer(new DefaultListRenderer(sv)); String text = list.getStringAt(0); assertEquals(sv.getString(list.getElementAt(0)), text); } /** * Issue 377-swingx: list with filters enabled fires incorrect events. * * Here: test single item remove fires interval removed */ @Test public void testListDataEventRemove() { JXList list = new JXList(ascendingListModel, true); ListDataReport report = new ListDataReport(); list.getModel().addListDataListener(report); // remove row ascendingListModel.remove(0); assertEquals("list must have fired event", 1, report.getEventCount()); assertEquals("list must have fired event of type removed", 1, report.getRemovedEventCount()); assertEquals("the index of removed item ", 0, report.getLastEvent().getIndex0()); } /** * Issue 377-swingx: list with filters enabled fires incorrect events. * * Here: test that a single item removal of a filtered element doesn't fire. */ @Test public void testListDataEventRemoveSingleFiltered() { JXList list = new JXList(ascendingListModel, true); assertEquals(20, list.getElementCount()); // filter out the first 10 list.setFilters(new FilterPipeline(createNumberFilter(10, 100, true))); assertEquals(10, list.getElementCount()); ListDataReport report = new ListDataReport(); list.getModel().addListDataListener(report); // remove a row which had been filtered ascendingListModel.remove(0); assertEquals("list must not have fired event for filtered remove", 0, report.getEventCount()); } /** * Issue 377-swingx: list with filters enabled fires incorrect events. * * Here: test that a removing a interval which is partly filtered maps * correctly to the visible interval. * */ @Test public void testListDataEventRemoveCutIntervalFiltered() { JXList list = new JXList(ascendingListModel, true); assertEquals(20, list.getElementCount()); // filter out the first 10 list.setFilters(new FilterPipeline(createNumberFilter(10, 100, true))); assertEquals(10, list.getElementCount()); assertEquals(10, list.getElementAt(0)); ListDataReport report = new ListDataReport(); list.getModel().addListDataListener(report); // remove a row which had been filtered ascendingListModel.removeRange(8, 12); assertEquals(7, ascendingListModel.get(7)); assertEquals(13, ascendingListModel.get(8)); assertEquals("list must have fired event", 1, report.getEventCount()); assertEquals("list must have fired event of type removed", 1, report.getRemovedEventCount()); assertEquals("first removed index ", 0, report.getLastRemovedEvent().getIndex0()); assertEquals("last removed index", 2, report.getLastRemovedEvent().getIndex1()); } /** * Issue 377-swingx: list with filters enabled fires incorrect events. * * Here: a removing a interval including all unfiltered value * */ @Test public void testListDataEventRemoveIntervalFilteredAll() { JXList list = new JXList(ascendingListModel, true); assertEquals(20, list.getElementCount()); // filter out the first 7 and last 7 list.setFilters(new FilterPipeline(createNumberFilter(8, 12, true))); assertEquals(5, list.getElementCount()); assertEquals(8, list.getElementAt(0)); ListDataReport report = new ListDataReport(); list.getModel().addListDataListener(report); // remove a row which had been filtered ascendingListModel.removeRange(7, 12); assertEquals(0, list.getElementCount()); assertEquals(14, ascendingListModel.getSize()); assertEquals("list must have fired event", 1, report.getEventCount()); assertEquals("list must have fired event of type removed", 1, report.getRemovedEventCount()); assertEquals("first removed index ", 0, report.getLastRemovedEvent().getIndex0()); assertEquals("last removed index", 4, report.getLastRemovedEvent().getIndex1()); } /** * Issue 377-swingx: list with filters enabled fires incorrect events. * * set single item fires contentsChanged with single index. */ @Test public void testListDataEventSingleSet() { JXList list = new JXList(ascendingListModel, true); ListDataReport report = new ListDataReport(); list.getModel().addListDataListener(report); // sanity assertEquals(0, report.getEventCount()); // remove row ascendingListModel.setElementAt(-1, 0); assertEquals("list must have fired event", 1, report.getEventCount()); assertEquals("list must have fired event of type changed", 1, report.getChangedEventCount()); assertEquals("changed index ", 0, report.getLastEvent().getIndex1()); } /** * Issue 377-swingx: list with filters enabled fires incorrect events. * * insert fires intervalAdded. */ @Test public void testListDataEventAdd() { JXList list = new JXList(ascendingListModel, true); ListDataReport report = new ListDataReport(); list.getModel().addListDataListener(report); // remove row ascendingListModel.insertElementAt(-1, 0); assertEquals("list must have fired event", 1, report.getEventCount()); assertEquals("list must have fired event of type added", 1, report.getAddedEventCount()); } /** * Issue 377-swingx: list with filters enabled fires incorrect events. * * event source is the wrapping list model. */ @Test public void testListDataEventSource() { JXList list = new JXList(ascendingListModel, true); ListDataReport report = new ListDataReport(); list.getModel().addListDataListener(report); // some change ascendingListModel.insertElementAt(-1, 0); assertEquals("list must have fired event", 1, report.getEventCount()); assertEquals("list must have fired event of type changed", list.getModel(), report.getLastEvent().getSource()); } /** * Issue #477-swingx: list with filter not updated after setModel. * * Reason is that there's no call to filter.flush in that path * of action. Probably due to mostly c&p from JXTable - which * always goes through tableChanged (which JList doesn't). * How to test? * */ @Test public void testSetModelFlushFilter() { final JXList list = new JXList(); list.setFilterEnabled(true); PatternFilter filter = new PatternFilter(".*1.*", 0, 0); final FilterPipeline pipeline = new FilterPipeline(filter); final DefaultListModel model = new DefaultListModel(); for (int i = 0; i < 10; i++) model.addElement("Element " + i); list.setFilters(pipeline); list.setModel(model); assertEquals(1, list.getElementCount()); } /** * Issue #477-swingx: * * Selection must be cleared after setModel. This is from * super's contract. * */ @Test public void testSetModelEmptySelection() { final JXList list = new JXList(); list.setFilterEnabled(true); final DefaultListModel model = new DefaultListModel(); for (int i = 0; i < 10; i++) model.addElement("Element " + i); list.setModel(model); int selection = 0; list.setSelectedIndex(selection); PatternFilter filter = new PatternFilter(".*", 0, 0); final FilterPipeline pipeline = new FilterPipeline(filter); list.setFilters(pipeline); assertEquals("setting filters must keep selection", selection, list.getSelectedIndex()); list.setModel(model); assertEquals(model.getSize(), list.getElementCount()); assertTrue("setting model must clear selectioon", list.isSelectionEmpty()); } /** * test that swingx renderer is used by default. * */ @Test public void testDefaultListRenderer() { JXList list = new JXList(); ListCellRenderer renderer = ((DelegatingRenderer) list.getCellRenderer()).getDelegateRenderer(); assertTrue("default renderer expected to be DefaultListRenderer " + "\n but is " + renderer.getClass(), renderer instanceof DefaultListRenderer); } /** * Issue #473-swingx: NPE in list with highlighter.

* * Renderers are doc'ed to cope with invalid input values. * Highlighters can rely on valid ComponentAdapter state. * JXList delegatingRenderer is the culprit which does set * invalid ComponentAdapter state. Negative invalid index. * */ @Test public void testIllegalNegativeListRowIndex() { JXList list = new JXList(new Object[] {1, 2, 3}); ListCellRenderer renderer = list.getCellRenderer(); renderer.getListCellRendererComponent(list, "dummy", -1, false, false); SearchPredicate predicate = new SearchPredicate("\\QNode\\E"); Highlighter searchHighlighter = new ColorHighlighter(predicate, null, Color.RED); list.addHighlighter(searchHighlighter); renderer.getListCellRendererComponent(list, "dummy", -1, false, false); } /** * Issue #473-swingx: NPE in list with highlighter.

* * Renderers are doc'ed to cope with invalid input values. * Highlighters can rely on valid ComponentAdapter state. * JXList delegatingRenderer is the culprit which does set * invalid ComponentAdapter state. Invalid index > valid range. * */ @Test public void testIllegalExceedingListRowIndex() { JXList list = new JXList(new Object[] {1, 2, 3}); ListCellRenderer renderer = list.getCellRenderer(); renderer.getListCellRendererComponent(list, "dummy", list.getElementCount(), false, false); SearchPredicate predicate = new SearchPredicate("\\QNode\\E"); Highlighter searchHighlighter = new ColorHighlighter(predicate, null, Color.RED); list.addHighlighter(searchHighlighter); renderer.getListCellRendererComponent(list, "dummy", list.getElementCount(), false, false); } /** * test convenience method accessing the configured adapter. * */ @Test public void testConfiguredComponentAdapter() { JXList list = new JXList(new Object[] {1, 2, 3}); ComponentAdapter adapter = list.getComponentAdapter(); assertEquals(0, adapter.column); assertEquals(0, adapter.row); adapter.row = 1; // corrupt adapter adapter.column = 1; adapter = list.getComponentAdapter(0); assertEquals(0, adapter.column); assertEquals(0, adapter.row); } /** * Test assumptions of accessing list model/view values through * the list's componentAdapter. * * PENDING: the default's getValue() implementation is incorrect! * */ @Test public void testComponentAdapterCoordinates() { JXList list = new JXList(ascendingListModel, true); Object originalFirstRowValue = list.getElementAt(0); Object originalLastRowValue = list.getElementAt(list.getElementCount() - 1); assertEquals("view row coordinate equals model row coordinate", list.getModel().getElementAt(0), originalFirstRowValue); // sort first column - actually does not change anything order list.toggleSortOrder(); // sanity asssert assertEquals("view order must be unchanged ", list.getElementAt(0), originalFirstRowValue); // invert sort list.toggleSortOrder(); // sanity assert assertEquals("view order must be reversed changed ", list.getElementAt(0), originalLastRowValue); ComponentAdapter adapter = list.getComponentAdapter(); assertEquals("adapter filteredValue expects row view coordinates", list.getElementAt(0), adapter.getFilteredValueAt(0, 0)); // adapter coordinates are view coordinates adapter.row = 0; adapter.column = 0; assertEquals("adapter.getValue must return value at adapter coordinates", list.getElementAt(0), adapter.getValue()); assertEquals("adapter.getValue must return value at adapter coordinates", list.getElementAt(0), adapter.getValue(0)); } /** * test exceptions on null data(model, vector, array). * */ @Test public void testNullData() { try { new JXList((ListModel) null); fail("JXList contructor must throw on null data"); } catch (IllegalArgumentException e) { // expected } catch (Exception e) { fail("unexpected exception type " + e); } try { new JXList((Vector) null); fail("JXList contructor must throw on null data"); } catch (IllegalArgumentException e) { // expected } catch (Exception e) { fail("unexpected exception type " + e); } try { new JXList((Object[]) null); fail("JXList contructor must throw on null data"); } catch (IllegalArgumentException e) { // expected } catch (Exception e) { fail("unexpected exception type " + e); } } /** * test filterEnabled property on initialization. * */ @Test public void testConstructorFilterEnabled() { // assertFilterEnabled(new JXList(), false); assertFilterEnabled(new JXList(new DefaultListModel()), false); assertFilterEnabled(new JXList(new Vector()), false); assertFilterEnabled(new JXList(new Object[] { }), false); assertFilterEnabled(new JXList(false), false); assertFilterEnabled(new JXList(new DefaultListModel(), false), false); assertFilterEnabled(new JXList(new Vector(), false), false); assertFilterEnabled(new JXList(new Object[] { }, false), false); assertFilterEnabled(new JXList(true), true); assertFilterEnabled(new JXList(new DefaultListModel(), true), true); assertFilterEnabled(new JXList(new Vector(), true), true); assertFilterEnabled(new JXList(new Object[] { }, true), true); } private void assertFilterEnabled(JXList list, boolean b) { assertEquals(b, list.isFilterEnabled()); } /** * added xtable.setSortOrder(int, SortOrder) * */ @Test public void testSetSortOrder() { JXList list = new JXList(ascendingListModel, true); list.setSortOrder(SortOrder.ASCENDING); assertEquals("column must be sorted after setting sortOrder on ", SortOrder.ASCENDING, list.getSortOrder()); } /** * JXList has responsibility to guarantee usage of * its comparator: setComparator if already sorted. */ @Test public void testDynamicComparatorToSortController() { JXList list = new JXList(listModel, true); list.toggleSortOrder(); list.setComparator(Collator.getInstance()); SortKey sortKey = SortKey.getFirstSortKeyForColumn(list.getFilters().getSortController().getSortKeys(), 0); assertNotNull(sortKey); assertEquals(list.getComparator(), sortKey.getComparator()); } /** * JXList has responsibility to guarantee usage of * its comparator: toggle. */ @Test public void testToggleComparatorToSortController() { JXList list = new JXList(listModel, true); list.setComparator(Collator.getInstance()); list.toggleSortOrder(); SortKey sortKey = SortKey.getFirstSortKeyForColumn(list.getFilters().getSortController().getSortKeys(), 0); assertNotNull(sortKey); assertEquals(list.getComparator(), sortKey.getComparator()); } /** * JXList has responsibility to guarantee usage of * its comparator: set. */ @Test public void testSetComparatorToSortController() { JXList list = new JXList(listModel, true); list.setComparator(Collator.getInstance()); list.setSortOrder(SortOrder.DESCENDING); SortKey sortKey = SortKey.getFirstSortKeyForColumn(list.getFilters().getSortController().getSortKeys(), 0); assertNotNull(sortKey); assertEquals(list.getComparator(), sortKey.getComparator()); } /** * add and test comparator property. * */ @Test public void testComparator() { JXList list = new JXList(); assertNull(list.getComparator()); Collator comparator = Collator.getInstance(); PropertyChangeReport report = new PropertyChangeReport(); list.addPropertyChangeListener(report); list.setComparator(comparator); assertEquals(comparator, list.getComparator()); assertEquals(1, report.getEventCount()); assertEquals(1, report.getEventCount("comparator")); } /** * testing new sorter api: * getSortOrder(), toggleSortOrder(), resetSortOrder(). * */ @Test public void testToggleSortOrder() { JXList list = new JXList(ascendingListModel, true); assertSame(SortOrder.UNSORTED, list.getSortOrder()); list.toggleSortOrder(); assertSame(SortOrder.ASCENDING, list.getSortOrder()); list.toggleSortOrder(); assertSame(SortOrder.DESCENDING, list.getSortOrder()); list.resetSortOrder(); assertSame(SortOrder.UNSORTED, list.getSortOrder()); } /** * prepare sort testing: internal probs with SortController? */ @Test public void testSortController() { JXList list = new JXList(ascendingListModel, true); assertNotNull("sortController must be initialized", list.getSortController()); } /** * Issue #232-swingx: selection not kept if selectionModel had been changed. * */ @Test public void testSelectionMapperUpdatedOnSelectionModelChange() { JXList table = new JXList(true); // created lazily, to see the failure, // need to get hold before replacing list's selection SelectionMapper mapper = table.getSelectionMapper(); ListSelectionModel model = new DefaultListSelectionModel(); table.setSelectionModel(model); assertEquals(model, mapper.getViewSelectionModel()); } /** * Issue #232-swingx: selection not kept if selectionModel had been changed. * * PENDING: selectionMapper shouldn't be available if list not filterable? */ @Test public void testSelectionMapperFilterDisabled() { JXList table = new JXList(); // created lazily, need to get hold before replacing list's selection SelectionMapper mapper = table.getSelectionMapper(); ListSelectionModel model = new DefaultListSelectionModel(); table.setSelectionModel(model); assertEquals(model, mapper.getViewSelectionModel()); } /** * test if LinkController/executeButtonAction is properly registered/unregistered on * setRolloverEnabled. * */ @Test public void testLinkControllerListening() { JXList table = new JXList(); table.setRolloverEnabled(true); assertNotNull("LinkController must be listening", getLinkControllerAsPropertyChangeListener(table, RolloverProducer.CLICKED_KEY)); assertNotNull("LinkController must be listening", getLinkControllerAsPropertyChangeListener(table, RolloverProducer.ROLLOVER_KEY)); assertNotNull("execute button action must be registered", table.getActionMap().get(JXList.EXECUTE_BUTTON_ACTIONCOMMAND)); table.setRolloverEnabled(false); assertNull("LinkController must not be listening", getLinkControllerAsPropertyChangeListener(table, RolloverProducer.CLICKED_KEY )); assertNull("LinkController must be listening", getLinkControllerAsPropertyChangeListener(table, RolloverProducer.ROLLOVER_KEY)); assertNull("execute button action must be de-registered", table.getActionMap().get(JXList.EXECUTE_BUTTON_ACTIONCOMMAND)); } private PropertyChangeListener getLinkControllerAsPropertyChangeListener(JXList table, String propertyName) { PropertyChangeListener[] listeners = table.getPropertyChangeListeners(propertyName); for (int i = 0; i < listeners.length; i++) { if (listeners[i] instanceof ListRolloverController) { return (ListRolloverController) listeners[i]; } } return null; } @Test public void testConvertToModelPreconditions() { final JXList list = new JXList(ascendingListModel, true); assertEquals(20, list.getElementCount()); list.setFilters(new FilterPipeline(new Filter[] {new PatternFilter("0", 0, 0) })); assertEquals(2, list.getElementCount()); try { list.convertIndexToModel(list.getElementCount()); fail("accessing list out of range index must throw execption"); } catch (IndexOutOfBoundsException ex) { // this is correct behaviour } catch (Exception ex) { fail("got " + ex); } } @Test public void testElementAtPreconditions() { final JXList list = new JXList(ascendingListModel, true); assertEquals(20, list.getElementCount()); list.setFilters(new FilterPipeline(new Filter[] {new PatternFilter("0", 0, 0) })); assertEquals(2, list.getElementCount()); try { list.getElementAt(list.getElementCount()); fail("accessing list out of range index must throw execption"); } catch (IndexOutOfBoundsException ex) { // this is correct behaviour } catch (Exception ex) { fail("got " + ex); } } /** * * Issue #173-swingx. * * table.setFilters() leads to selectionListener * notification while internal table state not yet stable. * * example (second one, from Nicola): * http://www.javadesktop.org/forums/thread.jspa?messageID=117814 * */ @Test public void testSelectionListenerNotification() { final JXList list = new JXList(ascendingListModel, true); assertEquals(20, list.getElementCount()); final int modelRow = 0; // set a selection list.setSelectedIndex(modelRow); ListSelectionListener l = new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) return; int viewRow = list.getSelectedIndex(); assertEquals("view index visible", 0, viewRow); // JW: the following checks if the reverse conversion succeeds list.convertIndexToModel(viewRow); } }; list.getSelectionModel().addListSelectionListener(l); list.setFilters(new FilterPipeline(new Filter[] {new PatternFilter("0", 0, 0) })); assertEquals(2, list.getElementCount()); } /** * setFilterEnabled throws NPE if formerly had selection. * * */ @Test public void testSetFilterEnabledWithSelection() { final JXList list = new JXList(ascendingListModel); assertEquals(20, list.getElementCount()); final int modelRow = 0; // set a selection list.setSelectedIndex(modelRow); list.setFilterEnabled(true); } @Test public void testEmptyFilter() { JXList list = new JXList(ascendingListModel); assertEquals(ascendingListModel.getSize(), list.getElementCount()); assertEquals(ascendingListModel.getElementAt(0), list.getElementAt(0)); } @Test public void testFilterEnabled() { JXList list = new JXList(ascendingListModel, true); assertNotSame(ascendingListModel, list.getModel()); assertEquals(ascendingListModel.getSize(), list.getElementCount()); assertEquals(ascendingListModel.getElementAt(0), list.getElementAt(0)); } /** * Emergency break for #2-swinglabs: * it's not allowed to reset filterEnabled property to false again. * */ @Test public void testFilterEnabledAndDisabled() { JXList list = new JXList(ascendingListModel, true); try { list.setFilterEnabled(false); fail("must not reset the filterEnabled property"); } catch (IllegalStateException e) { // do nothing this is the exception we expect. } catch (Exception e) { fail("unexpected exception type" + e); } // assertSame(ascendingListModel, list.getModel()); // assertEquals(ascendingListModel.getSize(), list.getElementCount()); // assertEquals(ascendingListModel.getElementAt(0), list.getElementAt(0)); } @Test public void testSortingFilterEnabled() { JXList list = new JXList(ascendingListModel, true); FilterPipeline pipeline = list.getFilters(); assertNotNull(pipeline); list.setSortOrder(SortOrder.DESCENDING); assertEquals(ascendingListModel.getSize(), list.getElementCount()); assertEquals(ascendingListModel.getElementAt(0), list.getElementAt(list.getElementCount() - 1)); } @Test public void testSortingKeepsModelSelection() { JXList list = new JXList(ascendingListModel, true); list.setSelectedIndex(0); list.setSortOrder(SortOrder.DESCENDING); assertEquals("last row must be selected after sorting", ascendingListModel.getSize() - 1, list.getSelectedIndex()); } /** * Issue #2-swinglabs: setting filter if not enabled throws exception on selection. * Reported by Kim. * * Fix: should not accept filter if not enabled. * PENDING JW: Doesn't? appears to be fixed? Check! * * */ @Test public void testFilterDisabled() { JXList list = new JXList(); list.setModel(ascendingListModel); Filter[] filter = new Filter[] { new PatternFilter("1", 0, 0) }; try { list.setFilters(new FilterPipeline(filter)); fail("setFilter must not be called if filters not enabled"); } catch (IllegalStateException e) { // do nothing, this is the documented behaviour } catch (Exception e) { fail("unexpected exception type " + e); } } /** * test if selection is kept after deleting a row above the * selected. * * This fails after quick fix for #370-swingx. * */ @Test public void testSelectionAfterAddAtFirst() { JXList list = new JXList(ascendingListModel, true); // selecte second row list.setSelectedIndex(0); Object oldFirst = list.getElementAt(0); Object newFirst = new Integer(-1); // add first ascendingListModel.insertElementAt(newFirst, 0); // sanity assertEquals(newFirst, list.getElementAt(0)); assertEquals(oldFirst, list.getElementAt(1)); assertEquals("first row must be selected inserting new first", 0, list.getSelectedIndex()); } /** * sanity test: compare table with list behaviour (#377-swingx) * */ @Test public void testSelectionAfterAddAtFirstCompareTable() { DefaultTableModel ascendingModel = new DefaultTableModel(20, 2); JXTable table = new JXTable(ascendingModel); // select second row table.setRowSelectionInterval(0, 0); // remove first ascendingModel.addRow(new Object[]{"", ""}); assertEquals("second row must be selected after adding new first", 0, table.getSelectedRow()); } /** * test if selection is kept after deleting a row above the * selected. * * This fails after quick fix for #370-swingx. * */ @Test public void testSelectionAfterAddAbove() { JXList list = new JXList(ascendingListModel, true); // selecte second row list.setSelectedIndex(1); Object oldFirst = list.getElementAt(1); Object newFirst = new Integer(-1); // add first ascendingListModel.insertElementAt(newFirst, 0); // sanity assertEquals(newFirst, list.getElementAt(0)); assertEquals(oldFirst, list.getElementAt(2)); assertEquals("second row must be selected inserting new first", 2, list.getSelectedIndex()); } /** * Issue #223 * test if selection is updated on add row above selection. * */ @Test public void testAddRowAboveSelectionInvertedOrder() { JXList list = new JXList(ascendingListModel, true); // select the last row in view coordinates int selectedRow = list.getElementCount() - 2; list.setSelectedIndex(selectedRow); // set a pipeline - ascending, no change list.toggleSortOrder(); // revert order list.toggleSortOrder(); assertEquals("second row must be selected", 1, list.getSelectedIndex()); // add row in model coordinates // insert high value Object row = new Integer(100); ascendingListModel.addElement(row); // selection must be moved one below assertEquals("selection must be incremented by one ", 2, list.getSelectedIndex()); } /** * test if selection is kept after deleting a row above the * selected. * * This fails after quick fix for #370-swingx. * */ @Test public void testSelectionAfterDeleteAbove() { JXList list = new JXList(ascendingListModel, true); // selecte second row list.setSelectedIndex(1); // remove first ascendingListModel.remove(0); assertEquals("first row must be selected removing old first", 0, list.getSelectedIndex()); } /** * sanity test: compare table with list behaviour (#370-swingx) * */ @Test public void testSelectionAfterDeleteAboveCompareTable() { DefaultTableModel ascendingModel = new DefaultTableModel(20, 2); JXTable table = new JXTable(ascendingModel); // select second row table.setRowSelectionInterval(1, 1); // remove first ascendingModel.removeRow(0); assertEquals("first row must be selected after removing old first", 0, table.getSelectedRow()); } protected ListModel createListModel() { JXList list = new JXList(); return new DefaultComboBoxModel(list.getActionMap().allKeys()); } protected DefaultListModel createAscendingListModel(int startRow, int count) { DefaultListModel l = new DefaultListModel(); for (int row = startRow; row < startRow + count; row++) { l.addElement(new Integer(row)); } return l; } protected DefaultListModel createListModelWithLinks() { DefaultListModel model = new DefaultListModel(); for (int i = 0; i < 20; i++) { try { LinkModel link = new LinkModel("a link text " + i, null, new URL("http://some.dummy.url" + i)); if (i == 1) { URL url = JXEditorPaneTest.class.getResource("resources/test.html"); link = new LinkModel("a resource", null, url); } model.addElement(link); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return model; } /** * Creates and returns a number filter, passing values which are numbers and * have int values inside or outside of the bounds (included), depending on the given * flag. * * @param lowerBound * @param upperBound * @param inside * @return */ protected Filter createNumberFilter(final int lowerBound, final int upperBound, final boolean inside) { PatternFilter f = new PatternFilter() { @Override public boolean test(int row) { Object value = getInputValue(row, getColumnIndex()); if (!(value instanceof Number)) return false; boolean isInside = ((Number) value).intValue() >= lowerBound && ((Number) value).intValue() <= upperBound; return inside ? isInside : !isInside; } }; return f; } @Override protected void setUp() throws Exception { super.setUp(); listModel = createListModel(); ascendingListModel = createAscendingListModel(0, 20); } public JXListTest() { super("JXList Tests"); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXTitledPanelTest.java0000644000175000017500000002727511210401722024076 0ustar tonytony/* * $Id: JXTitledPanelTest.java,v 1.17 2009/03/23 13:28:30 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Color; import java.awt.ComponentOrientation; import java.awt.Font; import java.awt.event.ActionEvent; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.LineBorder; import org.jdesktop.test.PropertyChangeReport; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class JXTitledPanelTest extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(JXTitledPanelTest.class .getName()); // flag used in setup to explicitly choose LF private boolean defaultToSystemLF; @Override protected void setUp() throws Exception { super.setUp(); // make sure we have the same default for each test defaultToSystemLF = false; setSystemLF(defaultToSystemLF); } public JXTitledPanelTest() { super("JXTitledPane interactive test"); } /** * Sanity: changed ui-delegate to install the opaqueness via LookAndFeel. Doing so * is the equivalent of UIResource for primitive types. */ @Test public void testOpaque() { JXTitledPanel titledPanel = new JXTitledPanel(); boolean opaque = titledPanel.isOpaque(); titledPanel.setOpaque(!opaque); assertEquals("sanity: opaqueness toggled: ", !opaque, titledPanel.isOpaque()); titledPanel.updateUI(); assertEquals("ui must not overwrite custom setting: ", !opaque, titledPanel.isOpaque()); } /** * Issue #1063-swingx: JXTitledPanel must not overwrite custom border */ @Test public void testBorderOnLFChange() { JXTitledPanel titledPanel = new JXTitledPanel(); assertTrue("sanity: titledPanels default border must be ui-installable " + titledPanel.getBorder(), SwingXUtilities.isUIInstallable(titledPanel.getBorder())); LineBorder border = new LineBorder(titledPanel.getBackground()); titledPanel.setBorder(border); assertEquals("sanity: border set", border, titledPanel.getBorder()); titledPanel.updateUI(); assertEquals("border untouched ", border, titledPanel.getBorder()); } @Test public void testLayoutOnLFChange() { JXTitledPanel titledPanel = new JXTitledPanel(); assertNotNull(titledPanel.getContentContainer()); titledPanel.getContentContainer().setLayout(new BorderLayout()); String lf = UIManager.getLookAndFeel().getName(); setSystemLF(!defaultToSystemLF); if (lf.equals(UIManager.getLookAndFeel().getName())) { LOG.info("cannot run layoutOnLFChange - equal LF" + lf); return; } SwingUtilities.updateComponentTreeUI(titledPanel); assertTrue(titledPanel.getContentContainer().getLayout() instanceof BorderLayout); } /** * Issue ??: notifications missing on all "title"XX properties. * */ @Test public void testTitlePropertiesNotify() { String title = "starting title"; final JXTitledPanel panel = new JXTitledPanel(title); PropertyChangeReport report = new PropertyChangeReport(); panel.addPropertyChangeListener(report); Font deriveFont = panel.getTitleFont().deriveFont(27f); panel.setTitleFont(deriveFont); assertTrue("panel must notify on titleFont change", report.hasEvents("titleFont")); // TODO: Whoever owns this please fix this. The tests should run clean. // fail("JXTitledPanelTest must be updated to new api"); // panel.setTitleForeground(Color.black); // assertTrue("panel must notify on titleForeground change", report.hasEvents("titleForeground")); // panel.setTitleDarkBackground(Color.black); // assertTrue("panel must notify on titleDarkBackground change", report.hasEvents("titleDarkBackground")); // panel.setTitleLightBackground(Color.black); // assertTrue("panel must notify on titleLightBackground change", report.hasEvents("titleLightBackground")); } /** * SwingX Issue #9: missing notification on title change. * happens if a generic property change listener (== one who * wants to get all property changes) is registered. */ @Test public void testTitleNotify() { String title = "starting title"; final JXTitledPanel panel = new JXTitledPanel(title); PropertyChangeReport report = new PropertyChangeReport(); panel.addPropertyChangeListener(report); panel.setTitle("new title"); assertTrue("panel must have fired propertyChange", report.hasEvents()); } /** * SwingX Issue #9: missing notification on title change. * Notification is correct, if a named propertyChangeListener is * registered. */ @Test public void testTitleNotifyNamed() { String title = "starting title"; final JXTitledPanel panel = new JXTitledPanel(title); PropertyChangeReport report = new PropertyChangeReport(); panel.addPropertyChangeListener( "title", report); panel.setTitle("new title"); assertTrue("panel must have fired propertyChange", report.hasEvents()); } /** * incorrect propertyChangeEvent on setTitle(null). * */ @Test public void testTitleNotifyPropertyValue() { String title = "starting title"; final JXTitledPanel panel = new JXTitledPanel(title); PropertyChangeReport report = new PropertyChangeReport(); panel.addPropertyChangeListener( "title", report); panel.setTitle(null); assertTrue("panel must have fired propertyChange", report.hasEvents()); assertEquals("new property value must be equal to getTitle", panel.getTitle(), report.getLastNewValue("title")); } //--------------------- interactive tests /** * Issue #1063-swingx: JXTitledPanel must respect custom border. */ public void interactiveBorderOnUpdateUI() { final JXTitledPanel titledPanel = new JXTitledPanel("Search"); titledPanel.setBorder(new LineBorder(titledPanel.getBackground())); showInFrame(titledPanel, "border on laf change"); } public void interactiveRToL() { String title = "starting title"; JXTitledPanel titledPane = new JXTitledPanel(title); titledPane.setLeftDecoration(new JLabel("Leading")); titledPane.setRightDecoration(new JLabel("Trailing")); // panel.getContentContainer().setLayout(new BoxLayout(panel.getContentContainer(), BoxLayout.PAGE_AXIS)); Icon icon = new ImageIcon(getClass().getResource("resources/images/wellBottom.gif")); final JLabel label = new JLabel(title); label.setIcon(icon); final JPanel panel = new JPanel(new BorderLayout()); panel.add(titledPane, BorderLayout.NORTH); panel.add(label); JXFrame frame = wrapInFrame(panel, "toggle Title"); Action toggleCO = new AbstractAction("toggle orientation") { public void actionPerformed(ActionEvent e) { ComponentOrientation current = panel.getComponentOrientation(); if (current == ComponentOrientation.LEFT_TO_RIGHT) { panel.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); label.setText("RightToLeft"); } else { panel.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); label.setText("LeftToRight"); } } }; addAction(frame, toggleCO); frame.pack(); frame.setVisible(true); } public void interactiveIconAndHtmlTest() { String title = "starting title "; final JXTitledPanel panel = new JXTitledPanel(title); Icon icon = new ImageIcon(getClass().getResource("resources/images/wellBottom.gif")); panel.setLeftDecoration(new JLabel(icon)); panel.getContentContainer().setLayout(new BoxLayout(panel.getContentContainer(), BoxLayout.Y_AXIS)); panel.getContentContainer().add(new JLabel(title)); JXFrame frame = wrapInFrame(panel, "toggle Title"); frame.setVisible(true); } /** * trying to set divers TitledPanel properties interactively. * can't set titlefont. */ public void interactiveTitleTest() { String title = "starting title"; final JXTitledPanel panel = new JXTitledPanel(title); panel.getContentContainer().setLayout(new BoxLayout(panel.getContentContainer(), BoxLayout.Y_AXIS)); Action toggleLight = new AbstractAction("toggle lightBackground") { public void actionPerformed(ActionEvent e) { LOG.info("JXTitledPanelText must be updated to new api"); // Color oldFont = panel.getTitleLightBackground(); // panel.setTitleLightBackground(oldFont.darker()); } }; panel.getContentContainer().add(new JButton(toggleLight)); panel.getContentContainer().setLayout(new BoxLayout(panel.getContentContainer(), BoxLayout.Y_AXIS)); Action toggleDark = new AbstractAction("toggle darkbackground") { public void actionPerformed(ActionEvent e) { LOG.info("JXTitledPanelText must be updated to new api"); // Color oldFont = panel.getTitleDarkBackground(); // panel.setTitleDarkBackground(oldFont.darker()); } }; panel.getContentContainer().add(new JButton(toggleDark)); Action toggleForeground = new AbstractAction("toggle Foreground") { public void actionPerformed(ActionEvent e) { Color oldColor = panel.getTitleForeground(); panel.setTitleForeground(oldColor.darker()); } }; panel.getContentContainer().add(new JButton(toggleForeground)); Action toggleFont = new AbstractAction("toggle Font") { public void actionPerformed(ActionEvent e) { Font oldFont = panel.getTitleFont(); System.out.println("oldfont size: " + oldFont.getSize()); panel.setTitleFont(oldFont.deriveFont(oldFont.getSize()*2.f)); } }; panel.getContentContainer().add(new JButton(toggleFont)); Action toggleTitle = new AbstractAction("toggle title") { int count = 0; public void actionPerformed(ActionEvent e) { panel.setTitle(" * " + count++ + " title"); } }; panel.getContentContainer().add(new JButton(toggleTitle)); JFrame frame = wrapInFrame(panel, "toggle Title"); frame.setVisible(true); } public static void main(String args[]) { JXTitledPanelTest test = new JXTitledPanelTest(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } } swingx-1.0-src/src/test/org/jdesktop/swingx/border/0000755000175000017500000000000011210401736021171 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/border/DropShadowBorderTest.java0000644000175000017500000001330611210401722026102 0ustar tonytony/* * $Id: DropShadowBorderTest.java,v 1.1 2009/01/26 22:53:17 rah003 Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.border; import java.awt.Color; import java.awt.ComponentOrientation; import java.awt.Insets; import java.awt.event.ActionEvent; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JLabel; import javax.swing.SwingConstants; import javax.swing.border.Border; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.icon.SortArrowIcon; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; /** * Tests related to DropShadowBorders. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class DropShadowBorderTest extends InteractiveTestCase { /** * Issue ??-swingx: IconBorder must handle null icon. * */ @Test public void testIconBorderNullIcon() { IconBorder border = new IconBorder(); JLabel label = new JLabel("dummy"); border.getBorderInsets(label); } @Test public void testIconBorderSetNullIcon() { IconBorder border = new IconBorder(new SortArrowIcon(true)); border.setIcon(null); JLabel label = new JLabel("dummy"); border.getBorderInsets(label); } /** * test new padding api. * */ @Test public void testPadding() { IconBorder border = new IconBorder(new SortArrowIcon(true)); int oldPadding = border.getPadding(); int padding = oldPadding + 10; border.setPadding(padding); assertEquals(padding, border.getPadding()); } @Test public void testNotNegativePadding() { IconBorder border = new IconBorder(new SortArrowIcon(true), SwingConstants.EAST, - 10); assertTrue(border.getPadding() >= 0); border.setPadding(-10); assertTrue(border.getPadding() >= 0); } /** * test default padding for backward compatibility. * Was hardcoded to 2*4. * */ @Test public void testDefaultPadding() { Icon icon = new SortArrowIcon(true); IconBorder border = new IconBorder(icon, SwingConstants.WEST); JLabel label = new JLabel("dummy"); label.setBorder(border); Insets insets = border.getBorderInsets(label); // internal knowledge: default padding has been 2 * 4 assertEquals(insets.left, icon.getIconWidth() + 8); } //------------------- visual checks /** * Visuals: null border, component orientation, padding. * */ public void interactiveIconBorderNullIcon() { final Icon icon = new SortArrowIcon(true); final IconBorder border = new IconBorder(icon); final JLabel label = new JLabel("...dummy............ with icon border"); Border lineBorder = BorderFactory.createLineBorder(Color.RED, 2); label.setBorder(BorderFactory.createCompoundBorder(lineBorder, border)); Action setIcon = new AbstractActionExt("null icon") { public void actionPerformed(ActionEvent e) { border.setIcon(null); label.repaint(); setEnabled(false); } }; Action setPadding = new AbstractActionExt("set padding") { public void actionPerformed(ActionEvent e) { border.setPadding(border.getPadding() + 10); label.repaint(); } }; final JXFrame frame = wrapInFrame(label, "IconBorder"); Action toggleComponentOrientation = new AbstractActionExt("toggle orientation") { public void actionPerformed(ActionEvent e) { ComponentOrientation current = frame.getComponentOrientation(); if (current == ComponentOrientation.LEFT_TO_RIGHT) { frame.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); } else { frame.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); } frame.validate(); frame.repaint(); } }; addAction(frame, toggleComponentOrientation); addAction(frame, setIcon); addAction(frame, setPadding); frame.setSize(400, 200); frame.setVisible(true); } public static void main(String args[]) { DropShadowBorderTest test = new DropShadowBorderTest(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Mark.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } } swingx-1.0-src/src/test/org/jdesktop/swingx/border/IconBorderTest.java0000644000175000017500000001325311210401722024721 0ustar tonytony/* * $Id: IconBorderTest.java,v 1.1 2009/01/26 22:53:16 rah003 Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.border; import java.awt.Color; import java.awt.ComponentOrientation; import java.awt.Insets; import java.awt.event.ActionEvent; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JLabel; import javax.swing.SwingConstants; import javax.swing.border.Border; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.icon.SortArrowIcon; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; /** * Tests related to SwingX Borders. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class IconBorderTest extends InteractiveTestCase { /** * Issue ??-swingx: IconBorder must handle null icon. * */ @Test public void testIconBorderNullIcon() { IconBorder border = new IconBorder(); JLabel label = new JLabel("dummy"); border.getBorderInsets(label); } @Test public void testIconBorderSetNullIcon() { IconBorder border = new IconBorder(new SortArrowIcon(true)); border.setIcon(null); JLabel label = new JLabel("dummy"); border.getBorderInsets(label); } /** * test new padding api. * */ @Test public void testPadding() { IconBorder border = new IconBorder(new SortArrowIcon(true)); int oldPadding = border.getPadding(); int padding = oldPadding + 10; border.setPadding(padding); assertEquals(padding, border.getPadding()); } @Test public void testNotNegativePadding() { IconBorder border = new IconBorder(new SortArrowIcon(true), SwingConstants.EAST, - 10); assertTrue(border.getPadding() >= 0); border.setPadding(-10); assertTrue(border.getPadding() >= 0); } /** * test default padding for backward compatibility. * Was hardcoded to 2*4. * */ @Test public void testDefaultPadding() { Icon icon = new SortArrowIcon(true); IconBorder border = new IconBorder(icon, SwingConstants.WEST); JLabel label = new JLabel("dummy"); label.setBorder(border); Insets insets = border.getBorderInsets(label); // internal knowledge: default padding has been 2 * 4 assertEquals(insets.left, icon.getIconWidth() + 8); } //------------------- visual checks /** * Visuals: null border, component orientation, padding. * */ public void interactiveIconBorderNullIcon() { final Icon icon = new SortArrowIcon(true); final IconBorder border = new IconBorder(icon); final JLabel label = new JLabel("...dummy............ with icon border"); Border lineBorder = BorderFactory.createLineBorder(Color.RED, 2); label.setBorder(BorderFactory.createCompoundBorder(lineBorder, border)); Action setIcon = new AbstractActionExt("null icon") { public void actionPerformed(ActionEvent e) { border.setIcon(null); label.repaint(); setEnabled(false); } }; Action setPadding = new AbstractActionExt("set padding") { public void actionPerformed(ActionEvent e) { border.setPadding(border.getPadding() + 10); label.repaint(); } }; final JXFrame frame = wrapInFrame(label, "IconBorder"); Action toggleComponentOrientation = new AbstractActionExt("toggle orientation") { public void actionPerformed(ActionEvent e) { ComponentOrientation current = frame.getComponentOrientation(); if (current == ComponentOrientation.LEFT_TO_RIGHT) { frame.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); } else { frame.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); } frame.validate(); frame.repaint(); } }; addAction(frame, toggleComponentOrientation); addAction(frame, setIcon); addAction(frame, setPadding); frame.setSize(400, 200); frame.setVisible(true); } public static void main(String args[]) { IconBorderTest test = new IconBorderTest(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Mark.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } } swingx-1.0-src/src/test/org/jdesktop/swingx/border/MatteBorderExtUnitTest.java0000644000175000017500000000727311210401724026433 0ustar tonytony/* * $Id: MatteBorderExtUnitTest.java,v 1.1 2009/01/20 20:00:58 kschaefe Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.border; import java.awt.Color; import java.awt.Point; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import org.jdesktop.swingx.border.MatteBorderExt; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; @RunWith(JUnit4.class) public class MatteBorderExtUnitTest extends junit.framework.TestCase { public MatteBorderExtUnitTest() { super("MatteBorderExt unit test"); } // XXX placeholder @Test public void testDummy() { } public static void main(String[] args) { try { // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { } final TestCase[] testCases = createTestCases(); if (testCases.length > 0) { // Automatically exit after last window is closed. testCases[testCases.length - 1].frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); Point location = testCases[0].frame.getLocation(); for (int i = testCases.length - 1; i >= 0; i--) { location.translate(30, 30); // stagger frames testCases[i].frame.setTitle("MatteBorderExt Unit Test " + (i + 1)); testCases[i].frame.setLocation(location); testCases[i].frame.setVisible(true); } } } /** * For unit testing only * @return test cases to be run in sequence */ private static TestCase[] createTestCases() { final TestCase[] testCases = new TestCase[] { new TestCase() { // 1 public JComponent define() { Class klass = MatteBorderExtUnitTest.class; Icon[] icons = new Icon[] { new ImageIcon(klass.getResource("resources/images/wellTopLeft.gif")), new ImageIcon(klass.getResource("resources/images/wellTop.gif")), new ImageIcon(klass.getResource("resources/images/wellTopRight.gif")), new ImageIcon(klass.getResource("resources/images/wellRight.gif")), new ImageIcon(klass.getResource("resources/images/wellBottomRight.gif")), new ImageIcon(klass.getResource("resources/images/wellBottom.gif")), new ImageIcon(klass.getResource("resources/images/wellBottomLeft.gif")), new ImageIcon(klass.getResource("resources/images/wellLeft.gif")), }; JPanel panel = new JPanel(); panel.setBackground(Color.white); panel.setBorder(new MatteBorderExt(14, 14, 14, 14, icons)); return panel; } }, }; return testCases; } private static abstract class TestCase { public TestCase() { this.frame = wrap(define()); } public abstract JComponent define(); public JFrame wrap(JComponent component) { this.component = component; final JFrame frame = new JFrame(); frame.getContentPane().add(component); frame.pack(); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); return frame; } public JComponent component; public final JFrame frame; } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXMonthViewTest.java0000644000175000017500000027371211210401722023610 0ustar tonytony/** * $Id: JXMonthViewTest.java,v 1.65 2009/03/31 15:39:28 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.Color; import java.awt.ComponentOrientation; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.Insets; import java.lang.reflect.InvocationTargetException; import java.text.DateFormatSymbols; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.SortedSet; import java.util.TimeZone; import java.util.TreeSet; import java.util.logging.Logger; import javax.swing.Action; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.SwingUtilities; import javax.swing.UIManager; import org.jdesktop.swingx.calendar.CalendarUtils; import org.jdesktop.swingx.calendar.DateSelectionModel; import org.jdesktop.swingx.calendar.DaySelectionModel; import org.jdesktop.swingx.calendar.DateSelectionModel.SelectionMode; import org.jdesktop.swingx.event.DateSelectionListener; import org.jdesktop.swingx.event.DateSelectionEvent.EventType; import org.jdesktop.swingx.hyperlink.AbstractHyperlinkAction; import org.jdesktop.swingx.test.DateSelectionReport; import org.jdesktop.test.ActionReport; import org.jdesktop.test.PropertyChangeReport; import org.jdesktop.test.TestUtils; import org.jmock.Mock; import org.jmock.MockObjectTestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Test case for JXMonthView * * There's another class with passing unit tests for JXMonthView (JXMonthViewVisualTest) * because this * extends mock while the other extends InteractiveTestCase. Both are expected * to pass. * * @author Joshua Outwater */ @RunWith(JUnit4.class) public class JXMonthViewTest extends MockObjectTestCase { private static final Logger LOG = Logger.getLogger(JXMonthViewTest.class .getName()); private Locale componentLocale; // pre-defined reference dates - all relative to current date at around 5 am private Date today; private Date tomorrow; private Date afterTomorrow; private Date yesterday; // calendar default instance init with today private Calendar calendar; private JXMonthView monthView; @Override @Before public void setUp() { calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 5); today = calendar.getTime(); calendar.add(Calendar.DAY_OF_MONTH, -1); yesterday = calendar.getTime(); calendar.add(Calendar.DAY_OF_MONTH, 2); tomorrow = calendar.getTime(); calendar.add(Calendar.DAY_OF_MONTH, 1); afterTomorrow = calendar.getTime(); calendar.setTime(today); //the test is configured for a US defaulted system //the localization tests handle actual localization issues componentLocale = JComponent.getDefaultLocale(); // LOG.info("componentLocale " + componentLocale); // JComponent.setDefaultLocale(Locale.US); monthView = new JXMonthView(); } @Override @After public void tearDown() { JComponent.setDefaultLocale(componentLocale); } /** * Issue #1072-swingx: nav icons incorrect for RToL if zoomable */ @Test public void testNavigationIconsUpdatedWithCO() { Action action = monthView.getActionMap().get("nextMonth"); if (monthView.getComponentOrientation().isLeftToRight()) { Icon icon = (Icon) action.getValue(Action.SMALL_ICON); assertNotNull("sanity: the decorated month nav action has an icon", icon); assertEquals(UIManager.getIcon("JXMonthView.monthUpFileName"), icon); monthView.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); // assertNotSame(icon, action.getValue(Action.SMALL_ICON)); assertEquals(action.getValue(Action.SMALL_ICON), UIManager.getIcon("JXMonthView.monthDownFileName")); } else { } } /** * Issue #1046-swingx: month title not updated when traversing months * (programatically or by navigating in monthView) */ @Test public void testZoomableNameOnMonthChange() { JXMonthView monthView = new JXMonthView(); AbstractHyperlinkAction action = (AbstractHyperlinkAction) monthView.getActionMap().get("zoomOut"); assertSame(monthView, action.getTarget()); String[] monthNames = new DateFormatSymbols(monthView.getLocale()).getMonths(); Calendar calendar = monthView.getCalendar(); int month = calendar.get(Calendar.MONTH); assertTrue(action.getName().startsWith(monthNames[month])); calendar.add(Calendar.MONTH, 1); monthView.setFirstDisplayedDay(calendar.getTime()); int nextMonth = calendar.get(Calendar.MONTH); assertTrue("month changed: old/new " + month + "/" + nextMonth, nextMonth != month); assertTrue("name must be updated, expected: " + monthNames[nextMonth] + " was: " + action.getName() , action.getName().startsWith(monthNames[nextMonth])); } /** * Issue #1046-swingx: month title not updated when traversing months * (programatically or by navigating in monthView) */ @Test public void testZoomableNameOnLocaleChange() { JXMonthView monthView = new JXMonthView(); AbstractHyperlinkAction action = (AbstractHyperlinkAction) monthView.getActionMap().get("zoomOut"); assertSame(monthView, action.getTarget()); Locale locale = Locale.FRENCH; if (locale.equals(monthView.getLocale())) { locale = Locale.GERMAN; } monthView.setLocale(locale); String[] monthNames = new DateFormatSymbols(monthView.getLocale()).getMonths(); Calendar calendar = monthView.getCalendar(); int month = calendar.get(Calendar.MONTH); assertTrue("name must be updated with locale, expected: " + monthNames[month] + " was: " + action.getName(), action.getName().startsWith(monthNames[month])); } /** * Issue #1046-swingx: month title not updated when traversing months * (programatically or by navigating in monthView) * * Test that zoomOutActin is installed for zoomable. */ @Test public void testZoomableZoomOutAction() { JXMonthView monthView = new JXMonthView(); assertNotNull("monthView must have zoomOutAction", monthView.getActionMap().get("zoomOut")); monthView.setZoomable(true); assertNotNull("monthView must have zoomOutAction", monthView.getActionMap().get("zoomOut")); } /** * Test that navigational actions are installed */ @Test public void testNavigationActionsInstalled() { JXMonthView monthView = new JXMonthView(); assertActionInstalled(monthView, "scrollToNextMonth"); assertActionInstalled(monthView, "scrollToPreviousMonth"); // actions mapped by CalendarHeaderHandler assertActionInstalled(monthView, "nextMonth"); assertActionInstalled(monthView, "previousMonth"); } /** * @param monthView * @param actionKey */ private void assertActionInstalled(JXMonthView monthView, String actionKey) { assertNotNull("ui must have installed action for " + actionKey, monthView.getActionMap().get(actionKey)); } /** * Test that navigational actions are working as expected. */ @Test public void testNavigationActionsWorking() { assertActionPerformed(new JXMonthView(), "scrollToNextMonth", Calendar.MONTH, 1); assertActionPerformed(new JXMonthView(), "nextMonth", Calendar.MONTH, 1); assertActionPerformed(new JXMonthView(), "scrollToPreviousMonth", Calendar.MONTH, -1); assertActionPerformed(new JXMonthView(), "previousMonth", Calendar.MONTH, -1); } private void assertActionPerformed(JXMonthView monthView, String actionKey, int calendarField, int amount) { Calendar calendar = monthView.getCalendar(); calendar.add(calendarField, amount); Action action = monthView.getActionMap().get(actionKey); action.actionPerformed(null); assertEquals(calendar.getTime(), monthView.getFirstDisplayedDay()); } @Test public void testZoomableProperty() { assertFalse("default zoomable is off", monthView.isZoomable()); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setZoomable(true); TestUtils.assertPropertyChangeEvent(report, "zoomable", false, true); assertTrue("traversable follows zoomable", monthView.isTraversable()); } /** * Issue #932-swingx: ui overwrites custom settings. * test daysoftheweekforeground property. * */ @Test public void testDaysOfTheWeekForegroundUpdateUI() { Color old = monthView.getDaysOfTheWeekForeground(); Color color = Color.PINK; if (color.equals(old)) { color = Color.MAGENTA; } monthView.setDaysOfTheWeekForeground(color); monthView.updateUI(); assertEquals(color, monthView.getDaysOfTheWeekForeground()); } /** * Issue #??-swingx: test accaptable values in setDayForeground. * Doc'ed to accept Calendar.SUNDAY - Calendar.SATURDAY, but not * enforced. * */ @Test(expected=IllegalArgumentException.class) public void testDayForegroundBeforeSunday() { monthView.setDayForeground(Calendar.SUNDAY - 1, Color.RED); } /** * Issue #??-swingx: test accaptable values in setDayForeground. * Doc'ed to accept Calendar.SUNDAY - Calendar.SATURDAY, but not * enforced. * */ @Test(expected=IllegalArgumentException.class) public void testDayForegroundAfterSaturday() { monthView.setDayForeground(Calendar.SATURDAY + 1, Color.RED); } /** * Issue #931-swingx: missing change notification. * test setting monthStringInsets property. * */ @Test public void testPreferredRowCount() { int old = monthView.getPreferredRowCount(); int color = old + 20; PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setPreferredRowCount(color); assertEquals(color, monthView.getPreferredRowCount()); TestUtils.assertPropertyChangeEvent(report, "preferredRowCount", old, color); } /** * Issue #931-swingx: missing change notification. * test setting monthStringInsets property. * */ @Test public void testPreferredColumnCount() { int old = monthView.getPreferredColumnCount(); int color = old + 20; PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setPreferredColumnCount(color); assertEquals(color, monthView.getPreferredColumnCount()); TestUtils.assertPropertyChangeEvent(report, "preferredColumnCount", old, color); } /** * Issue #931-swingx: missing change notification. * test setting monthStringInsets property. * */ @Test public void testMonthStringInsets() { Insets old = monthView.getMonthStringInsets(); Insets color = new Insets(21, 22, 23, 24); assertFalse("sanity: the new insets are not equals", color.equals(old)); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setMonthStringInsets(color); assertEquals(color, monthView.getMonthStringInsets()); TestUtils.assertPropertyChangeEvent(report, "monthStringInsets", old, color); } /** * Issue #931-swingx: missing change notification. * test setting monthStringBackground property. * */ @Test public void testTodayBackground() { Color old = monthView.getTodayBackground(); Color color = Color.PINK; if (color.equals(old)) { color = Color.MAGENTA; } PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setTodayBackground(color); assertEquals(color, monthView.getTodayBackground()); TestUtils.assertPropertyChangeEvent(report, "todayBackground", old, color); } /** * Issue #931-swingx: missing change notification. * test setting monthStringBackground property. * */ @Test public void testMonthStringBackground() { Color old = monthView.getMonthStringBackground(); Color color = Color.PINK; if (color.equals(old)) { color = Color.MAGENTA; } PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setMonthStringBackground(color); assertEquals(color, monthView.getMonthStringBackground()); TestUtils.assertPropertyChangeEvent(report, "monthStringBackground", old, color); } /** * Issue #931-swingx: missing change notification. * test setting monthStringForeground property. * */ @Test public void testMonthStringForeground() { Color old = monthView.getMonthStringForeground(); Color color = Color.PINK; if (color.equals(old)) { color = Color.MAGENTA; } PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setMonthStringForeground(color); assertEquals(color, monthView.getMonthStringForeground()); TestUtils.assertPropertyChangeEvent(report, "monthStringForeground", old, color); } /** * Issue #931-swingx: missing change notification. * test setting font property - was fired twice due to unneeded * override of setFont (removed). * */ @Test public void testFont() { Font old = monthView.getFont(); Font padding = old.deriveFont(old.getSize2D() * 2); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setFont(padding); assertEquals(padding, monthView.getFont()); TestUtils.assertPropertyChangeEvent(report, "font", old, padding); } /** * Issue #931-swingx: missing change notification. * test setting boxPaddingY property. * */ @Test public void testBoxPaddingY() { int old = monthView.getBoxPaddingY(); int padding = old + 2; PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setBoxPaddingY(padding); assertEquals(padding, monthView.getBoxPaddingY()); TestUtils.assertPropertyChangeEvent(report, "boxPaddingY", old, padding); } /** * Issue #931-swingx: missing change notification. * test setting boxPaddingX property. * */ @Test public void testBoxPaddingX() { int old = monthView.getBoxPaddingX(); int padding = old + 2; PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setBoxPaddingX(padding); assertEquals(padding, monthView.getBoxPaddingX()); TestUtils.assertPropertyChangeEvent(report, "boxPaddingX", old, padding); } /** * Issue #931-swingx: missing change notification. * test setting selectionBackground property. * */ @Test public void testDaysOfTheWeekForeground() { Color old = monthView.getDaysOfTheWeekForeground(); Color color = Color.PINK; if (color.equals(old)) { color = Color.MAGENTA; } PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setDaysOfTheWeekForeground(color); assertEquals(color, monthView.getDaysOfTheWeekForeground()); TestUtils.assertPropertyChangeEvent(report, "daysOfTheWeekForeground", old, color); } /** * Issue #931-swingx: missing change notification. * test setting selectionBackground property. * */ @Test public void testFlaggedDayForeground() { Color old = monthView.getFlaggedDayForeground(); Color color = Color.PINK; if (color.equals(old)) { color = Color.MAGENTA; } PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setFlaggedDayForeground(color); assertEquals(color, monthView.getFlaggedDayForeground()); TestUtils.assertPropertyChangeEvent(report, "flaggedDayForeground", old, color); } /** * Issue #931-swingx: missing change notification. * test setting selectionBackground property. * */ @Test public void testSelectionForeground() { Color old = monthView.getSelectionForeground(); Color color = Color.PINK; if (color.equals(old)) { color = Color.MAGENTA; } PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setSelectionForeground(color); assertEquals(color, monthView.getSelectionForeground()); TestUtils.assertPropertyChangeEvent(report, "selectionForeground", old, color); } /** * Issue #931-swingx: missing change notification. * test setting selectionBackground property. * */ @Test public void testSelectionBackground() { Color old = monthView.getSelectionBackground(); Color color = Color.PINK; if (color.equals(old)) { color = Color.MAGENTA; } PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setSelectionBackground(color); assertEquals(color, monthView.getSelectionBackground()); TestUtils.assertPropertyChangeEvent(report, "selectionBackground", old, color); } @Test public void testInitialOpaque() { assertTrue(monthView.isOpaque()); } @Test public void testInitialBoxPadding() { assertTrue(monthView.getBoxPaddingX() > 0); assertEquals(UIManager.getInt("JXMonthView.boxPaddingX"), monthView.getBoxPaddingX()); assertTrue(monthView.getBoxPaddingY() > 0); assertEquals(UIManager.getInt("JXMonthView.boxPaddingY"), monthView.getBoxPaddingY()); } /** * Issue #752-swingx: custom daysOfWeek lost in updateUI */ @Test public void testDaysOfWeekUpdateUI() { JXMonthView monthView = new JXMonthView(); String[] days = {"S", "M", "D", "M", "D", "F", "S"}; monthView.setDaysOfTheWeek(days); assertEquals(Arrays.asList(days), Arrays.asList(monthView.getDaysOfTheWeek())); monthView.updateUI(); assertEquals(Arrays.asList(days), Arrays.asList(monthView.getDaysOfTheWeek())); } /** * Issue #752-swingx: custom daysOfWeek lost in updateUI */ @Test public void testDaysOfWeekUpdateUIAllowNull() { JXMonthView monthView = new JXMonthView(); String[] days = null; monthView.setDaysOfTheWeek(days); assertNotNull("daysOfTheWeek must not be null", monthView.getDaysOfTheWeek()); } /** * Issue #752-swingx: custom daysOfWeek lost in updateUI */ @Test public void testDaysOfWeekInitial() { JXMonthView monthView = new JXMonthView(); assertNotNull("daysOfTheWeek must not be null", monthView.getDaysOfTheWeek()); } /** * Issue #752-swingx: custom daysOfWeek lost in updateUI */ @Test public void testDaysOfWeekCopied() { JXMonthView monthView = new JXMonthView(); assertNotSame(monthView.getDaysOfTheWeek(), monthView.getDaysOfTheWeek()); } /** * Issue #752-swingx: custom daysOfWeek lost in updateUI */ @Test public void testDaysOfWeekReset() { JXMonthView monthView = new JXMonthView(); // start off with ui-provided dates String[] uiDays = monthView.getDaysOfTheWeek(); String[] days = {"S", "M", "D", "M", "D", "F", "S"}; // set the custom monthView.setDaysOfTheWeek(days); // sanity assertEquals(Arrays.asList(days), Arrays.asList(monthView.getDaysOfTheWeek())); monthView.setDaysOfTheWeek(null); assertEquals("use ui-provided daysOfWeek after reset", Arrays.asList(uiDays), Arrays.asList(monthView.getDaysOfTheWeek())); } /** * Issue #751-swingx: property naming violations */ @Test public void testShowingLeadingNotification() { JXMonthView monthView = new JXMonthView(); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); boolean showing = monthView.isShowingLeadingDays(); monthView.setShowingLeadingDays(!showing); TestUtils.assertPropertyChangeEvent(report, "showingLeadingDays", showing, !showing); } /** * Issue #751-swingx: property naming violations */ @Test public void testShowingLeadingNoNotification() { JXMonthView monthView = new JXMonthView(); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); boolean showing = monthView.isShowingLeadingDays(); monthView.setShowingLeadingDays(showing); assertEquals(0, report.getEventCount("showingLeadingDates")); } /** * Issue #751-swingx: property naming violations */ @Test public void testShowingTrailingNotification() { JXMonthView monthView = new JXMonthView(); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); boolean showing = monthView.isShowingTrailingDays(); monthView.setShowingTrailingDays(!showing); TestUtils.assertPropertyChangeEvent(report, "showingTrailingDays", showing, !showing); } /** * Issue #751-swingx: property naming violations */ @Test public void testShowingTrailingNoNotification() { JXMonthView monthView = new JXMonthView(); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); boolean showing = monthView.isShowingTrailingDays(); monthView.setShowingTrailingDays(showing); assertEquals(0, report.getEventCount("showingTrailingDays")); } /** * Issue #751-swingx: property naming violations */ @Test public void testShowingWeekNumbersNotification() { JXMonthView monthView = new JXMonthView(); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); boolean showing = monthView.isShowingWeekNumber(); monthView.setShowingWeekNumber(!showing); TestUtils.assertPropertyChangeEvent(report, "showingWeekNumber", showing, !showing); } /** * Issue #751-swingx: property naming violations */ @Test public void testShowingWeekNumbersNoNotification() { JXMonthView monthView = new JXMonthView(); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); boolean showing = monthView.isShowingWeekNumber(); monthView.setShowingWeekNumber(showing); assertEquals(0, report.getEventCount("showingWeekNumber")); } /** * Issue #751-swingx: property naming violations */ @Test public void testTraversableNotification() { JXMonthView monthView = new JXMonthView(); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); boolean showing = monthView.isTraversable(); monthView.setTraversable(!showing); TestUtils.assertPropertyChangeEvent(report, "traversable", showing, !showing); } /** * Issue #751-swingx: property naming violations */ @Test public void testTraversableNoNotification() { JXMonthView monthView = new JXMonthView(); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); boolean showing = monthView.isTraversable(); monthView.setTraversable(showing); assertEquals(0, report.getEventCount("traversable")); } /** * Issue #733-swingx: model and monthView cal not synched. * * Here: test that model settings are respected in constructor - minimaldays. */ @Test public void testCalendarsContructorUnchangedFirstDayOfWeek() { DateSelectionModel model = new DaySelectionModel(); int first = model.getFirstDayOfWeek() + 1; model.setFirstDayOfWeek(first); JXMonthView monthView = new JXMonthView(new Date(), model); assertEquals("model's calendar properties must be unchanged: minimalDays", first, model.getFirstDayOfWeek()); // sanity: taken in monthView assertEquals("monthView's calendar properties must be synched", first, monthView.getFirstDayOfWeek()); } /** * Issue #733-swingx: model and monthView cal not synched. * * Here: test that monthView is updated to model after setSelectionModel. */ @Test public void testCalendarsSetModel() { JXMonthView monthView = new JXMonthView(); int firstDayOfWeek = monthView.getFirstDayOfWeek(); Locale locale = Locale.UK; if (locale.equals(monthView.getLocale())) { locale = Locale.FRENCH; } TimeZone tz = TimeZone.getTimeZone("GMT+4"); if (monthView.getTimeZone().equals(tz)) { tz = TimeZone.getTimeZone("GMT+5"); } DateSelectionModel model = new DaySelectionModel(locale); model.setTimeZone(tz); int modelMinimal = model.getMinimalDaysInFirstWeek(); monthView.setSelectionModel(model); assertEquals("timeZone must be updated from model", tz, monthView.getTimeZone()); assertEquals("Locale must be updated from model", locale, monthView.getLocale()); // be aware if it makes no sense to assert if (firstDayOfWeek != model.getFirstDayOfWeek()) { assertEquals("firstDayOfWeek must be updated from model", model.getFirstDayOfWeek(), monthView.getFirstDayOfWeek()); } else { LOG.info("cannot assert firstDayOfWeek - was same"); } // @KEEP - this is an open issue: monthView must not change the // model settings but minimalDaysInFirstWeek > 1 confuse the // BasicMonthViewUI - remove if passing in xIssues assertEquals("model minimals must not be changed", modelMinimal, model.getMinimalDaysInFirstWeek()); } /** * Issue #736-swingx: model and monthView cal not synched. * * Here: test that model settings are respected in constructor - minimaldays. */ @SuppressWarnings("unused") @Test public void testCalendarsContructorUnchangedMinimalDaysOfModel() { DateSelectionModel model = new DaySelectionModel(); int first = model.getMinimalDaysInFirstWeek() + 1; model.setMinimalDaysInFirstWeek(first); JXMonthView monthView = new JXMonthView(new Date(), model); assertEquals("model's calendar properties must be unchanged: minimalDays", first, model.getMinimalDaysInFirstWeek()); } /** * Issue #736-swingx: model and monthView cal not synched. * * Here: test that model settings are respected in setModel - minimaldays. * * Model must not reset minimalDaysInfirstWeek, but Locales with values * > 1 confuse the BasicDatePickerUI - need to track down and solve there. */ @Test public void testCalendarsSetModelUnchangedMinimalDaysInFirstWeek() { JXMonthView monthView = new JXMonthView(); DateSelectionModel model = new DaySelectionModel(); int first = model.getMinimalDaysInFirstWeek() + 1; model.setMinimalDaysInFirstWeek(first); monthView.setSelectionModel(model); assertEquals("model minimals must not be changed", first, model.getMinimalDaysInFirstWeek()); } /** * Issue #733-swingx: model and monthView cal not synched. * * Here: minimal days of first week. */ @Test public void testCalendarsMinimalDaysOfFirstWeekModelChanged() { JXMonthView monthView = new JXMonthView(); int first = monthView.getCalendar().getMinimalDaysInFirstWeek() + 1; assertTrue(first <= Calendar.SATURDAY); monthView.getSelectionModel().setMinimalDaysInFirstWeek(first); assertEquals(first, monthView.getCalendar().getMinimalDaysInFirstWeek()); } /** * Issue #733-swingx: TimeZone in model and monthView not synched. * * Test that the selected is normalized in the monthView's timezone. */ @Test public void testCalendarsTimeZoneNormalizedDate() { JXMonthView monthView = new JXMonthView(); // config with a known timezone TimeZone tz = TimeZone.getTimeZone("GMT+4"); if (tz.equals(monthView.getTimeZone())) { tz = TimeZone.getTimeZone("GMT+5"); } monthView.setTimeZone(tz); monthView.setSelectionDate(new Date()); Date selected = monthView.getSelectionDate(); Calendar calendar = monthView.getCalendar(); assertEquals(selected, CalendarUtils.startOfDay(calendar, selected)); } /** * Issue #733-swingx: model and monthView cal not synched. * * Here: timezone of flagged dates not synched. * This was introduced by moving the control of flagged dates into * a internal model. Need to synch that model as well. */ @Test public void testFlaggedDatesTimeZone() { JXMonthView monthView = new JXMonthView(); // config with a known timezone and date TimeZone tz = TimeZone.getTimeZone("GMT+4"); if (tz.equals(monthView.getTimeZone())) { tz = TimeZone.getTimeZone("GMT+5"); } monthView.setTimeZone(tz); monthView.setFlaggedDates(today); Date flagged = monthView.getFlaggedDates().first(); assertEquals(flagged, CalendarUtils.startOfDay(monthView.getCalendar(), flagged)); } /** * Issue #733-swingx: model and monthView cal not synched. * * Here: setting the timezone clears the flagged dates, must notify of change. */ @Test public void testFlaggedDatesTimeZoneNotifyOnChange() { JXMonthView monthView = new JXMonthView(); monthView.setFlaggedDates(today); SortedSet flagged = monthView.getFlaggedDates(); // config with a known timezone and date TimeZone tz = TimeZone.getTimeZone("GMT+4"); if (tz.equals(monthView.getTimeZone())) { tz = TimeZone.getTimeZone("GMT+5"); } PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setTimeZone(tz); TestUtils.assertPropertyChangeEvent(report, "flaggedDates", flagged, monthView.getFlaggedDates(), false); } /** * Issue #733-swingx: model and monthView cal not synched. * * Here: setting the timezone clears the flagged dates, must notify of change. */ @Test public void testFlaggedDatesTimeZoneNotNotifyWithoutChange() { JXMonthView monthView = new JXMonthView(); // config with a known timezone and date TimeZone tz = TimeZone.getTimeZone("GMT+4"); if (tz.equals(monthView.getTimeZone())) { tz = TimeZone.getTimeZone("GMT+5"); } PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setTimeZone(tz); assertEquals("no change in flaggedDates must not fire", 0, report.getEventCount("flaggedDates")); } /** * Issue #733-swingx: model and monthView cal not synched. * * Here: Locale changed in monthView. */ @Test public void testCalendarsLocaleChangedMonthView() { JXMonthView monthView = new JXMonthView(); Locale locale = Locale.UK; if (locale.equals(monthView.getLocale())) { locale = Locale.FRENCH; } monthView.setLocale(locale); assertEquals("locale set in monthView must be passed to model", locale, monthView.getSelectionModel().getLocale()); } /** * Issue #733-swingx: model and monthView cal not synched. * * Here: Locale changed in selection model. */ @Test public void testCalendarsLocaleChangedModel() { JXMonthView monthView = new JXMonthView(); Locale locale = Locale.UK; if (locale.equals(monthView.getLocale())) { locale = Locale.FRENCH; } monthView.getSelectionModel().setLocale(locale); assertEquals("locale set in model must be passed to monthView", locale, monthView.getLocale()); } /** * Issue #733-swingx: model and monthView cal not synched. * * Here: Locale changed in monthView. */ @Test public void testCalendarsLocaleContructor() { Locale locale = Locale.UK; if (locale.equals(JComponent.getDefaultLocale())) { locale = Locale.FRENCH; } JXMonthView monthView = new JXMonthView(locale); assertEquals("initial locale in constructor must be passed to model", locale, monthView.getSelectionModel().getLocale()); } /** * Issue #733-swingx: model and monthView cal not synched. * * Here: set first day of week in monthView. */ @Test public void testCalendarsFirstDayOfWeekMonthView() { JXMonthView monthView = new JXMonthView(); int first = monthView.getFirstDayOfWeek() + 1; // sanity assertTrue(first <= Calendar.SATURDAY); monthView.setFirstDayOfWeek(first); assertEquals(first, monthView.getFirstDayOfWeek()); assertEquals(first, monthView.getCalendar().getFirstDayOfWeek()); assertEquals(first, monthView.getSelectionModel().getFirstDayOfWeek()); } /** * Issue #733-swingx: model and monthView cal not synched. * * Here: set first day of week in model. */ @Test public void testCalendarsFirstDayOfWeekModel() { JXMonthView monthView = new JXMonthView(); int first = monthView.getFirstDayOfWeek() + 1; // sanity assertTrue(first <= Calendar.SATURDAY); monthView.getSelectionModel().setFirstDayOfWeek(first); assertEquals(first, monthView.getFirstDayOfWeek()); assertEquals(first, monthView.getCalendar().getFirstDayOfWeek()); assertEquals(first, monthView.getSelectionModel().getFirstDayOfWeek()); } /** * Issue #733-swingx: model and monthView cal not synched. * * Here: first day of week. */ @Test public void testCalendarsFirstDayOfWeekInitial() { JXMonthView monthView = new JXMonthView(); assertEquals(monthView.getFirstDayOfWeek(), monthView.getSelectionModel().getFirstDayOfWeek()); } /** * Issue #733-swingx: model and monthView cal not synched. * * Here: minimal days of first week. */ @Test public void testCalendarsMinimalDaysOfFirstWeekInitial() { JXMonthView monthView = new JXMonthView(); int first = monthView.getCalendar().getMinimalDaysInFirstWeek(); assertEquals(first, monthView.getSelectionModel().getMinimalDaysInFirstWeek()); } /** * Issue ??-swingx: selection related properties must be independent * of way-of setting. * * View must delegate to model, so asking view or model with same * parameters must return the same result. * * Here: isSelected * */ @Test public void testMonthViewSameAsSelectionModelIsSelected() { JXMonthView monthView = new JXMonthView(); // guard against accidental startofday calendar.set(Calendar.HOUR_OF_DAY, 5); Date date = calendar.getTime(); monthView.setSelectionDate(date); assertTrue(monthView.isSelected(date)); assertTrue(monthView.getSelectionModel().isSelected(date)); } /** * Issue ??-swingx: selection related properties must be independent * of way-of setting. * * View must delegate to model, so asking view or model with same * parameters must return the same result. * * Here: isSelected * */ @Test public void testMonthViewSameAsSelectionModelSelectedDate() { JXMonthView monthView = new JXMonthView(); // guard against accidental startofday calendar.set(Calendar.HOUR_OF_DAY, 5); Date date = calendar.getTime(); monthView.setSelectionDate(date); assertEquals(monthView.getSelectionDate(), monthView.getSelectionModel().getFirstSelectionDate()); } /** * Issue ??-swingx: selection related properties must be independent * of way-of setting. * * View must delegate to model, so asking view or model with same * parameters must return the same result. * * Here: isSelected * */ @Test public void testMonthViewSameAsSelectionModelIsUnselectable() { JXMonthView monthView = new JXMonthView(); // guard against accidental startofday calendar.set(Calendar.HOUR_OF_DAY, 5); Date date = calendar.getTime(); monthView.setUnselectableDates(date); assertTrue(monthView.isUnselectableDate(date)); assertTrue(monthView.getSelectionModel().isUnselectableDate(date)); } /** * Issue ??-swingx: selection related properties must be independent * of way-of setting. * * View must delegate to model, so asking view or model with same * parameters must return the same result. * * Here: set unselectables on model * */ @Test public void testSelectionModelSameAsMonthViewIsUnselectableDate() { JXMonthView monthView = new JXMonthView(); // guard against accidental startofday calendar.set(Calendar.HOUR_OF_DAY, 5); Date date = calendar.getTime(); SortedSet unselectables = new TreeSet(); unselectables.add(date); monthView.getSelectionModel().setUnselectableDates(unselectables); assertTrue(monthView.getSelectionModel().isUnselectableDate(date)); assertTrue(monthView.isUnselectableDate(date)); } /** * Issue ??-swingx: selection related properties must be independent * of way-of setting. * * View must delegate to model, so asking view or model with same * parameters must return the same result. * * Here: set selected on model * */ @Test public void testSelectionModelSameAsMonthViewIsSelected() { JXMonthView monthView = new JXMonthView(); // guard against accidental startofday calendar.set(Calendar.HOUR_OF_DAY, 5); Date date = calendar.getTime(); monthView.getSelectionModel().setSelectionInterval(date, date); assertTrue(monthView.getSelectionModel().isSelected(date)); assertTrue(monthView.isSelected(date)); } /** * Issue ??-swingx: selection related properties must be independent * of way-of setting. * * View must delegate to model, so asking view or model with same * parameters must return the same result. * * Here: set selected on model, ask for selected date * */ @Test public void testSelectionModelSameAsMonthViewSelectedDate() { JXMonthView monthView = new JXMonthView(); // guard against accidental startofday calendar.set(Calendar.HOUR_OF_DAY, 5); Date date = calendar.getTime(); monthView.getSelectionModel().setSelectionInterval(date, date); assertEquals(monthView.getSelectionModel().getFirstSelectionDate(), monthView.getSelectionDate()); } /** * #703-swingx: set date to first of next doesn't update the view. * * Behaviour is consistent with core components, must not update * */ @Test public void testAutoScrollOnSelection() { JXMonthView us = new JXMonthView(); final Calendar today = Calendar.getInstance(); CalendarUtils.endOfMonth(today); us.setSelectionDate(today.getTime()); Date first = us.getFirstDisplayedDay(); today.add(Calendar.DAY_OF_MONTH, 2); us.setSelectionDate(today.getTime()); assertEquals(first, us.getFirstDisplayedDay()); } /** * #705-swingx: revalidate must not reset first firstDisplayed. * * */ @Test public void testAutoScrollOnSelectionRevalidate() throws InterruptedException, InvocationTargetException { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } final JXMonthView us = new JXMonthView(); final Calendar today = Calendar.getInstance(); CalendarUtils.endOfMonth(today); us.setSelectionDate(today.getTime()); final JXFrame frame = new JXFrame(); frame.add(us); final Date first = us.getFirstDisplayedDay(); today.add(Calendar.DAY_OF_MONTH, 2); us.setSelectionDate(today.getTime()); SwingUtilities.invokeAndWait(new Runnable() { public void run() { us.revalidate(); // need to validate frame - why? frame.validate(); assertEquals("firstDisplayed must not be changed on revalidate", first, us.getFirstDisplayedDay()); // assertEquals(first, us.getFirstDisplayedDate()); // fail("weird (threading issue?): the firstDisplayed is changed in layoutContainer - not testable here"); } }); } /** * Issue 711-swingx: today is notify-only property. * Today is start of day. */ @Test public void testTodayInitial() { JXMonthView monthView = new JXMonthView(); CalendarUtils.startOfDay(calendar); assertEquals(calendar.getTime(), monthView.getToday()); } /** * Issue 711-swingx: today is notify-only property. * Increment sets to start of day of tomorrow. */ @Test public void testTodayIncrement() { JXMonthView monthView = new JXMonthView(); calendar.add(Calendar.DAY_OF_MONTH, 1); CalendarUtils.startOfDay(calendar); monthView.incrementToday(); assertEquals(calendar.getTime(), monthView.getToday()); } /** * Issue 711-swingx: today is notify-only property. * SetToday should */ @Test public void testTodaySetNotification() { JXMonthView monthView = new JXMonthView(); Date today = monthView.getToday(); // tomorrow calendar.add(Calendar.DAY_OF_MONTH, 1); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setToday(calendar.getTime()); CalendarUtils.startOfDay(calendar); TestUtils.assertPropertyChangeEvent(report, "today", today, calendar.getTime()); } /** * Issue 711-swingx: today is notify-only property. * SetToday should */ @Test public void testTodaySet() { JXMonthView monthView = new JXMonthView(); // tomorrow calendar.add(Calendar.DAY_OF_MONTH, 1); monthView.setToday(calendar.getTime()); CalendarUtils.startOfDay(calendar); assertEquals(calendar.getTime(), monthView.getToday()); } /** * For safety, getToday should return a clone. */ @Test public void testTodayCopy() { JXMonthView monthView = new JXMonthView(); Date today = monthView.getToday(); Date other = monthView.getToday(); assertNotNull(today); assertNotSame(today, other); } /** * Issue #708-swingx: updateUI changes state. * * Here: test that today is unchanged. */ @Test public void testUpdateUIToday() { JXMonthView monthView = new JXMonthView(); Date first = monthView.getToday(); monthView.updateUI(); assertEquals(first, monthView.getToday()); }; /** * Issue #711-swingx: remove fake property change notification. * * Here: test that ensureVisibleDate fires once only. */ @Test public void testEnsureVisibleDateNofication() { JXMonthView monthView = new JXMonthView(); Date firstDisplayedDate = monthView.getFirstDisplayedDay(); // previous month calendar.add(Calendar.MONTH, -1); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.ensureDateVisible(calendar.getTime()); CalendarUtils.startOfMonth(calendar); TestUtils.assertPropertyChangeEvent(report, "firstDisplayedDay", firstDisplayedDate, calendar.getTime(), false); } /** * Issue #711-swingx: remove fake property change notification. * * Here: test that setFirstDisplayedDate fires once only. */ @Test public void testFirstDisplayedDateNofication() { JXMonthView monthView = new JXMonthView(); Date firstDisplayedDate = monthView.getFirstDisplayedDay(); // previous month calendar.add(Calendar.MONTH, -1); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setFirstDisplayedDay(calendar.getTime()); CalendarUtils.startOfMonth(calendar); TestUtils.assertPropertyChangeEvent(report, "firstDisplayedDay", firstDisplayedDate, calendar.getTime(), false); } /** * Issue #708-swingx * * test update of lastDisplayedDate if resized. */ @Test public void testLastDisplayedOnResize() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } // get a reference width so we can simulate a one-month resize JXMonthView compare = new JXMonthView(); compare.setPreferredColumnCount(2); JXMonthView monthView = new JXMonthView(); JXFrame frame = new JXFrame(); frame.add(monthView); frame.pack(); Date last = monthView.getLastDisplayedDay(); // set a size that should guarantee the same number of columns as the compare monthView frame.setSize(compare.getPreferredSize().width + 50, monthView.getPreferredSize().height + 50); frame.validate(); // build a date corresponding to the expected end of next month calendar.setTime(last); // next month calendar.add(Calendar.DAY_OF_MONTH, 1); CalendarUtils.endOfMonth(calendar); assertEquals(calendar.getTime(), monthView.getLastDisplayedDay()); } /** * Issue #708-swingx: updateUI changes state. * * Here: test that firstDisplayedDate is unchanged. */ @Test public void testUpdateUIFirst() { final JXMonthView monthView = new JXMonthView(); Date first = monthView.getFirstDisplayedDay(); monthView.updateUI(); assertEquals(first, monthView.getFirstDisplayedDay()); }; /** * Issue #708-swingx: updateUI changes state. * * Here: test that lastDisplayedDate is unchanged. */ @Test public void testUpdateUILast() { final JXMonthView monthView = new JXMonthView(); Date first = monthView.getLastDisplayedDay(); monthView.updateUI(); assertEquals(first, monthView.getLastDisplayedDay()); }; /** * Issue #660-swingx: JXMonthView must protect its calendar. * Client manipulation on calendar must not change internal state. * * This is guaranteed by returning a clone instead of the life object. */ @Test public void testMonthViewCalendarInvariant() { JXMonthView monthView = new JXMonthView(); TimeZone tz = monthView.getTimeZone(); Calendar calendar = monthView.getCalendar(); calendar.setTimeZone(getTimeZone(tz, CalendarUtils.THREE_HOURS)); assertEquals("monthView must protect its calendar", tz, monthView.getTimeZone()); } /** * Issue #660-swingx: JXMonthView must protect its calendar. * * Added invariant to the monthView's getCalender: clone and * config to firstDisplayDate. * * The various tests are various contexts which broke the * expectation before fixing the issue. * Here the context is: select. */ @Test public void testMonthViewCalendarInvariantOnSetSelection() { JXMonthView monthView = new JXMonthView(); assertEquals(1, monthView.getCalendar().get(Calendar.DATE)); Date first = monthView.getFirstDisplayedDay(); assertEquals("monthViews calendar represents the first day of the month", first, monthView.getCalendar().getTime()); Calendar cal = Calendar.getInstance(); // add one day, now we are on the second cal.setTime(first); cal.add(Calendar.DATE, 1); Date date = cal.getTime(); monthView.addSelectionInterval(date , date); assertEquals("selection must not change the calendar", first, monthView.getCalendar().getTime()); } /** * Issue #660-swingx: JXMonthView must protect its calendar. * * Added invariant to the monthView's getCalender: clone and * config to firstDisplayDate. * * The various tests are various contexts which broke the * expectation before fixing the issue. * Here the context is: check for selection. */ @Test public void testMonthViewCalendarInvariantOnQuerySelectioon() { JXMonthView monthView = new JXMonthView(); assertEquals(1, monthView.getCalendar().get(Calendar.DATE)); Date first = monthView.getFirstDisplayedDay(); assertEquals("monthViews calendar represents the first day of the month", first, monthView.getCalendar().getTime()); Calendar cal = Calendar.getInstance(); // add one day, now we are on the second cal.setTime(first); cal.add(Calendar.DATE, 1); Date date = cal.getTime(); monthView.isSelected(date); assertEquals("query selection must not change the calendar", first, monthView.getCalendar().getTime()); } /** * Issue #660-swingx: JXMonthView must protect its calendar. * * Added invariant to the monthView's getCalender: clone and * config to firstDisplayDate. * * The various tests are various contexts which broke the * expectation before fixing the issue. * Here the context is: set first displayed date (formerly left * the calendar at the last displayed date). */ @Test public void testMonthViewCalendarInvariantOnSetFirstDisplayedDate() { JXMonthView monthView = new JXMonthView(); Date first = monthView.getFirstDisplayedDay(); Calendar cal = Calendar.getInstance(); // add one day, now we are on the second cal.setTime(first); cal.add(Calendar.MONTH, 1); Date next = cal.getTime(); monthView.setFirstDisplayedDay(next); assertEquals("monthViews calendar represents the first day of the month", next, monthView.getCalendar().getTime()); } /** * safety net: add api ensureDateVisible with Date parameter */ @Test public void testEnsureDateVisibleDateParamNextYear() { JXMonthView monthView = new JXMonthView(); Calendar temp = (Calendar) calendar.clone(); CalendarUtils.startOfMonth(temp); // sanity assertEquals("sanity...", temp.getTime(), monthView.getFirstDisplayedDay()); calendar.add(Calendar.YEAR, 1); Date nextYear = calendar.getTime(); temp = (Calendar) calendar.clone(); CalendarUtils.startOfMonth(temp); monthView.ensureDateVisible(nextYear); assertEquals("must be scrolled to next year", temp.getTime(), monthView.getFirstDisplayedDay()); } /** * safety net: add api ensureDateVisible with Date parameter */ @Test public void testEnsureDateVisibleDateParamNextMonth() { JXMonthView monthView = new JXMonthView(); Calendar temp = (Calendar) calendar.clone(); CalendarUtils.startOfMonth(temp); assertEquals("sanity..", temp.getTime(), monthView.getFirstDisplayedDay()); calendar.add(Calendar.MONTH, 1); Date nextMonth = calendar.getTime(); temp = (Calendar) calendar.clone(); CalendarUtils.startOfMonth(temp); monthView.ensureDateVisible(nextMonth); assertEquals("must be scrolled to next month", temp.getTime(), monthView.getFirstDisplayedDay()); } /** * safety net: add api ensureDateVisible with Date parameter */ @Test public void testEnsureDateVisibleDateParamThisMonth() { JXMonthView monthView = new JXMonthView(); Calendar temp = (Calendar) calendar.clone(); CalendarUtils.startOfMonth(temp); Date first = monthView.getFirstDisplayedDay(); assertEquals("sanity...", temp.getTime(), first); CalendarUtils.endOfMonth(calendar); Date thisMonth = calendar.getTime(); monthView.ensureDateVisible(thisMonth); assertEquals("same month, nothing changed", first, monthView.getFirstDisplayedDay()); } /** * safety net: refactor ensureDateVisible */ @Test public void testEnsureDateVisibleNextYear() { JXMonthView monthView = new JXMonthView(); Calendar temp = (Calendar) calendar.clone(); CalendarUtils.startOfMonth(temp); assertEquals("sanity...", temp.getTime(), monthView.getFirstDisplayedDay()); calendar.add(Calendar.YEAR, 1); Date nextYear = calendar.getTime(); temp = (Calendar) calendar.clone(); CalendarUtils.startOfMonth(temp); monthView.ensureDateVisible(nextYear); assertEquals("must be scrolled to next year", temp.getTime(), monthView.getFirstDisplayedDay()); } /** * safety net: refactor ensureDateVisible */ @Test public void testEnsureDateVisibleNextMonth() { JXMonthView monthView = new JXMonthView(); Calendar temp = (Calendar) calendar.clone(); CalendarUtils.startOfMonth(temp); assertEquals("sanity ...", temp.getTime(), monthView.getFirstDisplayedDay()); calendar.add(Calendar.MONTH, 1); Date nextMonth = calendar.getTime(); temp = (Calendar) calendar.clone(); CalendarUtils.startOfMonth(temp); monthView.ensureDateVisible(nextMonth); assertEquals("must be scrolled to next month", temp.getTime(), monthView.getFirstDisplayedDay()); } /** * safety net: refactor ensureDateVisible */ @Test public void testEnsureDateVisibleThisMonth() { JXMonthView monthView = new JXMonthView(); Calendar temp = (Calendar) calendar.clone(); CalendarUtils.startOfMonth(temp); Date first = monthView.getFirstDisplayedDay(); assertEquals("sanity ...", temp.getTime(), first); CalendarUtils.endOfMonth(calendar); Date thisMonth = calendar.getTime(); monthView.ensureDateVisible(thisMonth); assertEquals("same month, nothing changed", first, monthView.getFirstDisplayedDay()); } /** * safety net: move responsibility for lastDisplayedDate completely into ui. */ @Test public void testLastDisplayedDateInitial() { JXMonthView monthView = new JXMonthView(); calendar.setTime(monthView.getFirstDisplayedDay()); CalendarUtils.endOfMonth(calendar); assertEquals(calendar.getTime(), monthView.getLastDisplayedDay()); } /** * Issue #618-swingx: JXMonthView displays problems with non-default * timezones. * * Selected dates are "start of day" in the timezone they had been * selected. As such they make no sense in a new timezone: must * either be adjusted or cleared. Currently we clear the selection. */ @Test public void testTimeZoneChangeClearSelection() { JXMonthView monthView = new JXMonthView(); Date date = new Date(); monthView.setSelectionDate(date); // sanity assertTrue(monthView.isSelected(date)); monthView.setTimeZone(getTimeZone(monthView.getTimeZone(), CalendarUtils.THREE_HOURS)); // accidentally passes - because it is meaningful only in the timezone // it was set ... assertFalse(monthView.isSelected(date)); assertTrue("selection must have been cleared", monthView.isSelectionEmpty()); } /** * Issue #618-swingx: JXMonthView displays problems with non-default * timezones. * * Bound dates are "start of day" in the timezone they had been * set. As such they make no sense in a new timezone: must * either be adjusted or cleared. Currently we clear the bound. */ @Test public void testTimeZoneChangeResetLowerBound() { JXMonthView monthView = new JXMonthView(); monthView.setLowerBound(yesterday); monthView.setTimeZone(getTimeZone(monthView.getTimeZone(), CalendarUtils.THREE_HOURS)); assertEquals("lowerBound must have been reset", null, monthView.getLowerBound()); } /** * Issue #618-swingx: JXMonthView displays problems with non-default * timezones. * * Bound dates are "start of day" in the timezone they had been * set. As such they make no sense in a new timezone: must * either be adjusted or cleared. Currently we clear the bound. */ @Test public void testTimeZoneChangeResetUpperBound() { JXMonthView monthView = new JXMonthView(); monthView.setUpperBound(yesterday); monthView.setTimeZone(getTimeZone(monthView.getTimeZone(), CalendarUtils.THREE_HOURS)); assertEquals("upperbound must have been reset", null, monthView.getUpperBound()); } /** * Issue #618-swingx: JXMonthView displays problems with non-default * timezones. * * Flagged dates are "start of day" in the timezone they had been * set. As such they make no sense in a new timezone: must * either be adjusted or cleared. Currently we clear them. */ @Test public void testTimeZoneChangeResetFlaggedDates() { JXMonthView monthView = new JXMonthView(); monthView.setFlaggedDates(new Date[] {yesterday}); monthView.setTimeZone(getTimeZone(monthView.getTimeZone(), CalendarUtils.THREE_HOURS)); // accidentally passes - because it is meaningful only in the timezone // it was set ... assertFalse(monthView.isFlaggedDate(yesterday)); // missing api // assertEquals(0, monthView.getFlaggedDates().size()); assertFalse("flagged dates must have been cleared", monthView.hasFlaggedDates()); } /** * Issue #618-swingx: JXMonthView displays problems with non-default * timezones. * * Unselectable dates are "start of day" in the timezone they had been * set. As such they make no sense in a new timezone: must * either be adjusted or cleared. Currently we clear them. */ @Test public void testTimeZoneChangeResetUnselectableDates() { JXMonthView monthView = new JXMonthView(); monthView.setUnselectableDates(yesterday); monthView.setTimeZone(getTimeZone(monthView.getTimeZone(), CalendarUtils.THREE_HOURS)); // accidentally passes - because it is meaningful only in the timezone // it was set ... assertFalse(monthView.isUnselectableDate(yesterday)); // missing api on JXMonthView assertEquals("unselectable dates must have been cleared", 0, monthView.getSelectionModel().getUnselectableDates().size()); } /** * test anchor: set to param as passed int setFirstDisplayedDate */ @Test public void testAnchorDateInitial() { JXMonthView monthView = new JXMonthView(); // sometime next month calendar.add(Calendar.MONTH, 1); monthView.setFirstDisplayedDay(calendar.getTime()); assertEquals(calendar.getTime(), monthView.getAnchorDate()); CalendarUtils.startOfMonth(calendar); assertEquals(calendar.getTime(), monthView.getFirstDisplayedDay()); } /** * Issue #618-swingx: JXMonthView displays problems with non-default * timezones. * * Here: test anchor invariant to time zone change */ @Test public void testTimeZoneChangeAnchorInvariant() { JXMonthView monthView = new JXMonthView(); Date anchor = monthView.getAnchorDate(); TimeZone timeZone = monthView.getTimeZone(); // just interested in a different timezone, no quantification intended monthView.setTimeZone(getTimeZone(timeZone, CalendarUtils.THREE_HOURS)); assertEquals("anchor must be invariant to timezone change", anchor, monthView.getAnchorDate()); } /** * Issue #618-swingx: JXMonthView displays problems with non-default * timezones. * * Here: test that the first displayed date is offset by offset diff of * timezones. Configure the monthView with a fixed timezone to clear up the * mist ... * * This did fail on the server on 31mar2008, us/pacific timezone, en_US * locale. Trying to sim the context then. * * Failed again at Tue Sep 30 10:12:31 PDT 2008, en_US locale. Next * (testTimeZoneChangeOffsetFirstDisplayedDate) failed at the same time, */ @Test public void testTimeZoneChangeToday() { JXMonthView monthView = new JXMonthView(); // config with a known timezone and date TimeZone tz = TimeZone.getTimeZone("GMT+4"); monthView.setTimeZone(tz); Calendar calendar = Calendar.getInstance(tz); Date today = calendar.getTime(); monthView.setFirstDisplayedDay(today); Date anchor = monthView.getAnchorDate(); assertEquals(today, anchor); Date firstDisplayed = monthView.getFirstDisplayedDay(); calendar.setTime(firstDisplayed); assertTrue(CalendarUtils.isStartOfMonth(calendar)); // get another timezone with known offset TimeZone tzOther = TimeZone.getTimeZone("GMT+7"); // newOffset minus oldOffset (real time, adjusted to DST) int oldOffset = tz.getOffset(anchor.getTime()); int newOffset = tzOther.getOffset(anchor.getTime()); int realOffset = oldOffset - newOffset; monthView.setTimeZone(tzOther); Calendar otherCalendar = Calendar.getInstance(tzOther); otherCalendar.setTime(monthView.getFirstDisplayedDay()); assertTrue(CalendarUtils.isStartOfMonth(otherCalendar)); // PENDING JW: sure this is the correct direction of the shift? // yeah, think so: the anchor is fixed, moving the timezone results // in a shift into the opposite direction of the offset Calendar localCal = Calendar.getInstance(); String server = "server locale: " + Locale.getDefault() + "\n server timezone: " + localCal.getTimeZone() + "\n server local time: " + localCal.getTime(); String timeZones = "first timeZone " + tz + "\n first timezone offset / min " + oldOffset / (1000 * 60) + "\n second timezone " + tzOther + "\n second timezone offset / min " + newOffset / (1000 * 60); String monthViewProps = "monthView locale: " + monthView.getLocale() + "\n monthView anchor " + anchor + "\n monthView firstDisplayed " + monthView.getFirstDisplayedDay(); assertEquals( "first displayed must be offset by real offset " + "\n ********** spurious failure - so try extensiv debug output:" + "\n " + server + "\n " + timeZones + "\n " + monthViewProps, (realOffset) / (1000 * 60), (monthView.getFirstDisplayedDay().getTime() - firstDisplayed.getTime()) / (1000 * 60)); /* * The output of failure: * * junit.framework.AssertionFailedError: first displayed must be offset by real offset ********** spurious failure - so try extensiv debug output: server locale: en_US server timezone: sun.util.calendar.ZoneInfo[id="US/Pacific",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185, lastRule=java.util.SimpleTimeZone[id=US/Pacific,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]] server local time: Tue Sep 30 10:12:31 PDT 2008 first timeZone sun.util.calendar.ZoneInfo[id="GMT+04:00",offset=14400000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null] first timezone offset / min 240 second timezone sun.util.calendar.ZoneInfo[id="GMT+07:00",offset=25200000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null] second timezone offset / min 420 monthView locale: en_US monthView anchor Tue Sep 30 10:12:31 PDT 2008 monthView firstDisplayed Tue Sep 30 10:00:00 PDT 2008 expected:<-180> but was:<43020> at org.jdesktop.swingx.JXMonthViewTest.testTimeZoneChangeToday(JXMonthViewTest.java:1385) at org.jmock.core.VerifyingTestCase.runBare(VerifyingTestCase.java:39) */ } /** * Issue #618-swingx: JXMonthView displays problems with non-default * timezones. * * Here: test that the first displayed date is offset by offset diff of * timezones. * Configure the monthView with a fixed timezone to clear up the mist ... * * failed along with previous test, (Tue Sep 30 10:12:31 PDT 2008, en_US locale) * error out: * first displayed must be offset by real offset expected: * <-10800000> but was:<2581200000> * */ @Test public void testTimeZoneChangeOffsetFirstDisplayedDate() { JXMonthView monthView = new JXMonthView(); // config with a known timezone and date TimeZone tz = TimeZone.getTimeZone("GMT+4"); monthView.setTimeZone(tz); Calendar calendar = Calendar.getInstance(tz); Date today = calendar.getTime(); monthView.setFirstDisplayedDay(today); Date anchor = monthView.getAnchorDate(); assertEquals(today, anchor); Date firstDisplayed = monthView.getFirstDisplayedDay(); calendar.setTime(firstDisplayed); assertTrue(CalendarUtils.isStartOfMonth(calendar)); // get another timezone with known offset TimeZone tzOther = TimeZone.getTimeZone("GMT+7"); // newOffset minus oldOffset (real time, adjusted to DST) int oldOffset = tz.getOffset(anchor.getTime()); int newOffset = tzOther.getOffset(anchor.getTime()); int realOffset = oldOffset - newOffset; monthView.setTimeZone(tzOther); Calendar otherCalendar = Calendar.getInstance(tzOther); otherCalendar.setTime(monthView.getFirstDisplayedDay()); assertTrue(CalendarUtils.isStartOfMonth(otherCalendar)); // PENDING JW: sure this is the correct direction of the shift? // yeah, think so: the anchor is fixed, moving the timezone results // in a shift into the opposite direction of the offset assertEquals("first displayed must be offset by real offset", realOffset, monthView.getFirstDisplayedDay().getTime() - firstDisplayed.getTime()); } /** * Returns a timezone with a rawoffset with a different offset. * * * PENDING: this is acutally for european time, not really thought of * negative/rolling +/- problem? * * @param timeZone the timezone to start with * @param diffRawOffset the raw offset difference. * @return */ private TimeZone getTimeZone(TimeZone timeZone, int diffRawOffset) { int offset = timeZone.getRawOffset(); int newOffset = offset < 0 ? offset + diffRawOffset : offset - diffRawOffset; String[] availableIDs = TimeZone.getAvailableIDs(newOffset); TimeZone newTimeZone = TimeZone.getTimeZone(availableIDs[0]); return newTimeZone; } /** * Issue #618-swingx: JXMonthView displays problems with non-default * timezones. * * Here: test timezone fire */ @Test public void testTimeZoneChangeNotification() { JXMonthView monthView = new JXMonthView(); TimeZone timezone = monthView.getTimeZone(); int offset = timezone.getRawOffset(); int oneHour = 60 * 1000 * 60; int newOffset = offset < 0 ? offset + oneHour : offset - oneHour; String[] availableIDs = TimeZone.getAvailableIDs(newOffset); TimeZone newTimeZone = TimeZone.getTimeZone(availableIDs[0]); // sanity assertFalse(timezone.equals(newTimeZone)); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setTimeZone(newTimeZone); TestUtils.assertPropertyChangeEvent(report, "timeZone", timezone, newTimeZone, false); } /** * Issue #563-swingx: keybindings active if not focused. * Test that the bindings are dynamically installed when * shown in popup and de-installed if shown not in popup. */ @Test public void testComponentInputMapEnabledControlsFocusedKeyBindings() { JXMonthView monthView = new JXMonthView(); // initial: no bindings assertEquals("monthView must not have in-focused keyBindings", 0, monthView.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).size()); monthView.setComponentInputMapEnabled(true); // setting the flag installs bindings assertTrue("monthView must have in-focused keyBindings after showing in popup", monthView.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).size() > 0); monthView.setComponentInputMapEnabled(false); // resetting the flag uninstalls the bindings assertEquals("monthView must not have in-focused keyBindings", 0, monthView.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).size()); } /** * Test default value and property change notificateion of * the componentInputMapEnabled property. * */ @Test public void testComponentInputMapEnabled() { JXMonthView monthView = new JXMonthView(); assertFalse("the default value must be false", monthView.isComponentInputMapEnabled()); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setComponentInputMapEnabled(true); TestUtils.assertPropertyChangeEvent(report, "componentInputMapEnabled", false, true, false); report.clear(); monthView.setComponentInputMapEnabled(false); TestUtils.assertPropertyChangeEvent(report, "componentInputMapEnabled", true, false, false); } /** * test doc'ed behaviour: model must not be null. * */ @Test public void testSetModelNull() { JXMonthView monthView = new JXMonthView(); assertNotNull(monthView.getSelectionModel()); try { monthView.setSelectionModel(null); fail("null model must not be accepted"); } catch (NullPointerException ex) { // expected - but how do we test fail-fast implemented } } /** * Enhanced commit/cancel. * * test that actions resets model.adjusting to false. */ @Test public void testCommitCancelResetsAdjusting() { JXMonthView monthView = new JXMonthView(); monthView.getSelectionModel().setAdjusting(true); monthView.commitSelection(); assertFalse("commit must reset adjusting", monthView.getSelectionModel().isAdjusting()); monthView.getSelectionModel().setAdjusting(true); monthView.cancelSelection(); assertFalse("cancel must reset adjusting", monthView.getSelectionModel().isAdjusting()); } /** * Enhanced commit/cancel. * * test that actions fire as expected. * */ @Test public void testCommitCancelAPIFires() { JXMonthView picker = new JXMonthView(); ActionReport report = new ActionReport(); picker.addActionListener(report); picker.commitSelection(); assertEquals(1, report.getEventCount()); assertEquals(JXMonthView.COMMIT_KEY, report.getLastActionCommand()); report.clear(); picker.cancelSelection(); assertEquals(1, report.getEventCount()); assertEquals(JXMonthView.CANCEL_KEY, report.getLastActionCommand()); } /** * Enhanced commit/cancel. * * test that actions fire as expected. * */ @Test public void testCommitCancelActionsFire() { JXMonthView picker = new JXMonthView(); Action commitAction = picker.getActionMap().get(JXMonthView.COMMIT_KEY); ActionReport report = new ActionReport(); picker.addActionListener(report); commitAction.actionPerformed(null); assertEquals(1, report.getEventCount()); assertEquals(JXMonthView.COMMIT_KEY, report.getLastActionCommand()); report.clear(); Action cancelAction = picker.getActionMap().get(JXMonthView.CANCEL_KEY); cancelAction.actionPerformed(null); assertEquals(1, report.getEventCount()); assertEquals(JXMonthView.CANCEL_KEY, report.getLastActionCommand()); } /** * Enhanced commit/cancel. * * test that actions are registered. * */ @Test public void testCommitCancelActionExist() { JXMonthView picker = new JXMonthView(); assertNotNull(picker.getActionMap().get(JXMonthView.CANCEL_KEY)); assertNotNull(picker.getActionMap().get(JXMonthView.COMMIT_KEY)); } /** * Enhanced commit/cancel. * * test that actions are the same for new/old cancel/accept. * */ @Test public void testCommitCancelSameAsOld() { JXMonthView picker = new JXMonthView(); assertSame(picker.getActionMap().get("cancelSelection"), picker.getActionMap().get(JXMonthView.CANCEL_KEY)); assertSame(picker.getActionMap().get("acceptSelection"), picker.getActionMap().get(JXMonthView.COMMIT_KEY)); } /** * BasicMonthViewUI: use adjusting api in keyboard actions. * Here: test reset in cancel action. */ @Test public void testAdjustingResetOnCancel() { JXMonthView view = new JXMonthView(); Action select = view.getActionMap().get("selectNextDay"); select.actionPerformed(null); DateSelectionReport report = new DateSelectionReport(view.getSelectionModel()); Action cancel = view.getActionMap().get("cancelSelection"); cancel.actionPerformed(null); assertFalse("ui keyboard action must have stopped model adjusting", view.getSelectionModel().isAdjusting()); assertEquals(2, report.getEventCount()); } /** * BasicMonthViewUI: use adjusting api in keyboard actions. * Here: test reset in accept action. */ @Test public void testAdjustingResetOnAccept() { JXMonthView view = new JXMonthView(); Action select = view.getActionMap().get("selectNextDay"); select.actionPerformed(null); DateSelectionReport report = new DateSelectionReport(view.getSelectionModel()); Action cancel = view.getActionMap().get("acceptSelection"); cancel.actionPerformed(null); assertFalse("ui keyboard action must have stopped model adjusting", view.getSelectionModel().isAdjusting()); assertEquals(1, report.getEventCount()); assertEquals(EventType.ADJUSTING_STOPPED, report.getLastEvent().getEventType()); } /** * BasicMonthViewUI: use adjusting api in keyboard actions. * Here: test set selection action. */ @Test public void testAdjustingSetOnSelect() { JXMonthView view = new JXMonthView(); DateSelectionReport report = new DateSelectionReport(view.getSelectionModel()); Action select = view.getActionMap().get("selectNextDay"); select.actionPerformed(null); assertTrue("ui keyboard action must have started model adjusting", view.getSelectionModel().isAdjusting()); assertEquals(2, report.getEventCount()); // assert that the adjusting is fired before the set assertEquals(EventType.DATES_SET, report.getLastEvent().getEventType()); } /** * BasicMonthViewUI: use adjusting api in keyboard actions. * Here: test add selection action. */ @Test public void testAdjustingSetOnAdd() { JXMonthView view = new JXMonthView(); // otherwise the add action isn't called view.setSelectionMode(SelectionMode.SINGLE_INTERVAL_SELECTION); DateSelectionReport report = new DateSelectionReport(view.getSelectionModel()); Action select = view.getActionMap().get("adjustSelectionNextDay"); select.actionPerformed(null); assertTrue("ui keyboard action must have started model adjusting", view.getSelectionModel().isAdjusting()); assertEquals(2, report.getEventCount()); // assert that the adjusting is fired before the add // only: the type a set instead or the expected added - bug or feature? // assertEquals(EventType.DATES_ADDED, report.getLastEvent().getEventType()); // for now we are only interested in the adjusting (must not be the last) // so go for what's actually fired instead of what's expected assertEquals(EventType.DATES_SET, report.getLastEvent().getEventType()); } /** * Issue #557-swingx: always fire actionEvent after esc/enter. * * test fire after accept. */ @Test public void testFireOnKeyboardAccept() { JXMonthView monthView = new JXMonthView(); Date date = new Date(); monthView.setSelectionInterval(date, date); ActionReport report = new ActionReport(); monthView.addActionListener(report); Action accept = monthView.getActionMap().get("acceptSelection"); accept.actionPerformed(null); assertEquals(1, report.getEventCount()); } /** * Issue #557-swingx: always fire actionEvent after esc/enter. * * test fire after cancel. */ @Test public void testFireOnKeyboardCancel() { JXMonthView monthView = new JXMonthView(); Date date = new Date(); monthView.setSelectionInterval(date, date); ActionReport report = new ActionReport(); monthView.addActionListener(report); Action accept = monthView.getActionMap().get("cancelSelection"); accept.actionPerformed(null); assertEquals(1, report.getEventCount()); } /** * expose more selection constraint methods in JXMonthView * */ @Test public void testUpperBound() { JXMonthView view = new JXMonthView(); view.setUpperBound(today); assertEquals(startOfDay(today), view.getUpperBound()); // remove again view.setUpperBound(null); assertEquals(null, view.getUpperBound()); } /** * expose more selection constraint methods in JXMonthView * */ @Test public void testLowerBound() { JXMonthView view = new JXMonthView(); view.setLowerBound(today); assertEquals(startOfDay(today), view.getLowerBound()); // remove again view.setLowerBound(null); assertEquals(null, view.getLowerBound()); } /** * test unselectable: use methods with Date. * */ @Test public void testUnselectableDate() { JXMonthView monthView = new JXMonthView(); // initial assertFalse(monthView.isUnselectableDate(today)); // set unselectable today monthView.setUnselectableDates(today); assertTrue("raqw today must be unselectable", monthView.isUnselectableDate(today)); assertTrue("start of today must be unselectable", monthView.isUnselectableDate(startOfDay(today))); assertTrue("end of today must be unselectable", monthView.isUnselectableDate(endOfDay(today))); monthView.setUnselectableDates(); assertFalse(monthView.isUnselectableDate(today)); assertFalse(monthView.isUnselectableDate(startOfDay(today))); assertFalse(monthView.isUnselectableDate(endOfDay(today))); } /** * test unselectable: use methods with Date. * test NPE as doc'ed. */ @Test public void testUnselectableDatesNPE() { JXMonthView monthView = new JXMonthView(); try { monthView.setUnselectableDates((Date[])null); fail("null array must throw NPE"); } catch (NullPointerException e) { // expected } try { monthView.setUnselectableDates(new Date[] {new Date(), null}); fail("null elements must throw NPE"); } catch (NullPointerException e) { // expected } } /** * Issue #494-swingx: JXMonthView changed all passed-in dates * */ @Test public void testCleanupCopyDate() { JXMonthView monthView = new JXMonthView(); Date copy = new Date(today.getTime()); monthView.setSelectionInterval(today, today); assertEquals("the date used for selection must be unchanged", copy, today); } /** * test cover method: isSelectedDate * */ @Test public void testIsSelectedDate() { JXMonthView monthView = new JXMonthView(); monthView.setSelectionDate(today); assertTrue(monthView.isSelected(today)); assertTrue(monthView.isSelected(startOfDay(today))); } /** * Sanity: test against regression * test cover method: isSelectedDate * */ @Test public void testIsSelectedDate494() { JXMonthView monthView = new JXMonthView(); Date copy = new Date(today.getTime()); monthView.setSelectionDate(today); // use today monthView.isSelected(today); assertEquals("date must not be changed in isSelected", copy, today); } /** * test cover method: setSelectedDate * */ @Test public void testSetSelectedDate() { JXMonthView monthView = new JXMonthView(); Date copy = new Date(today.getTime()); monthView.setSelectionDate(today); // sanity: date unchanged assertEquals(copy, today); assertEquals(startOfDay(today), monthView.getSelectionDate()); monthView.setSelectionDate(null); assertTrue(monthView.isSelectionEmpty()); } /** * test new (convenience) api on JXMonthView * */ @Test public void testGetSelected() { JXMonthView monthView = new JXMonthView(); assertNull(monthView.getSelectionDate()); monthView.setSelectionInterval(today, today); assertEquals("same day", startOfDay(today), monthView.getSelectionDate()); // clear selection monthView.clearSelection(); assertNull(monthView.getSelectionDate()); } @Test public void testDefaultConstructor() { JXMonthView monthView = new JXMonthView(Locale.US); assertTrue(monthView.isSelectionEmpty()); assertTrue(SelectionMode.SINGLE_SELECTION == monthView.getSelectionMode()); assertTrue(Calendar.SUNDAY == monthView.getFirstDayOfWeek()); } @Test public void testLocale() { Locale[] locales = Locale.getAvailableLocales(); for (Locale l : locales) { JComponent.setDefaultLocale(l); JXMonthView monthView = new JXMonthView(); Locale locale = monthView.getLocale(); Calendar cal = Calendar.getInstance(locale); int expectedFirstDayOfWeek = cal.getFirstDayOfWeek(); assertTrue(expectedFirstDayOfWeek == monthView.getFirstDayOfWeek()); } } @Test public void testEmptySelectionInitial() { JXMonthView monthView = new JXMonthView(); assertTrue(monthView.isSelectionEmpty()); SortedSet selection = monthView.getSelection(); assertTrue(selection.isEmpty()); } @Test public void testEmptySelectionClear() { JXMonthView monthView = new JXMonthView(); monthView.setSelectionInterval(today, today); // sanity assertTrue(1 == monthView.getSelection().size()); monthView.clearSelection(); assertTrue(monthView.isSelectionEmpty()); assertTrue(monthView.getSelection().isEmpty()); } @Test public void testSelectionModes() { JXMonthView monthView = new JXMonthView(); assertEquals(SelectionMode.SINGLE_SELECTION, monthView .getSelectionMode()); for (SelectionMode mode : SelectionMode.values()) { monthView.setSelectionMode(mode); assertEquals(mode, monthView.getSelectionModel().getSelectionMode()); assertEquals(mode, monthView.getSelectionMode()); } } @Test public void testSingleSelection() { JXMonthView monthView = new JXMonthView(); monthView.setSelectionMode(SelectionMode.SINGLE_SELECTION); monthView.setSelectionInterval(yesterday, yesterday); assertTrue(1 == monthView.getSelection().size()); assertEquals(startOfDay(yesterday), monthView.getFirstSelectionDate()); monthView.setSelectionInterval(yesterday, afterTomorrow); assertTrue(1 == monthView.getSelection().size()); assertEquals(startOfDay(yesterday), monthView.getFirstSelectionDate()); } @Test public void testSingleIntervalSelection() { JXMonthView monthView = new JXMonthView(); monthView.setSelectionMode(SelectionMode.SINGLE_INTERVAL_SELECTION); monthView.setSelectionInterval(yesterday, yesterday); assertTrue(1 == monthView.getSelection().size()); assertEquals(startOfDay(yesterday), monthView.getFirstSelectionDate()); monthView.setSelectionInterval(yesterday, tomorrow); assertTrue(3 == monthView.getSelection().size()); assertEquals(startOfDay(yesterday), monthView.getFirstSelectionDate()); assertEquals(startOfDay(tomorrow), monthView.getLastSelectionDate()); } @Test public void testMultipleIntervalSelection() { JXMonthView monthView = new JXMonthView(); monthView.setSelectionMode(SelectionMode.MULTIPLE_INTERVAL_SELECTION); monthView.setSelectionInterval(yesterday, yesterday); monthView.addSelectionInterval(afterTomorrow, afterTomorrow); assertEquals(2, monthView.getSelection().size()); assertEquals(startOfDay(yesterday), monthView.getFirstSelectionDate()); assertEquals(startOfDay(afterTomorrow), monthView.getLastSelectionDate()); } @Test public void testDateSelectionListener() { JXMonthView monthView = new JXMonthView(); Mock listenerMock = mock(DateSelectionListener.class); listenerMock.expects(once()).method("valueChanged"); DateSelectionListener listener = (DateSelectionListener) listenerMock.proxy(); monthView.getSelectionModel().addDateSelectionListener(listener); Date date = new Date(); monthView.setSelectionInterval(date, date); } /** * test setting/checking flagged dates (api with Date) */ @Test public void testFlaggedDateRemoveNotify() { JXMonthView monthView = new JXMonthView(); monthView.setFlaggedDates(tomorrow, yesterday); SortedSet oldFlagged = monthView.getFlaggedDates(); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.removeFlaggedDates(tomorrow); TestUtils.assertPropertyChangeEvent(report, "flaggedDates", oldFlagged, monthView.getFlaggedDates()); } /** * test setting/checking flagged dates (api with Date) */ @Test public void testFlaggedDateRemove() { JXMonthView monthView = new JXMonthView(); monthView.addFlaggedDates(tomorrow, yesterday); assertEquals(2, monthView.getFlaggedDates().size()); monthView.removeFlaggedDates(tomorrow); assertTrue(monthView.isFlaggedDate(yesterday)); assertFalse(monthView.isFlaggedDate(tomorrow)); } /** * test setting/checking flagged dates (api with Date) */ @Test public void testFlaggedDateClear() { JXMonthView monthView = new JXMonthView(); monthView.addFlaggedDates(tomorrow, yesterday); assertEquals(2, monthView.getFlaggedDates().size()); monthView.clearFlaggedDates(); assertFalse("flagged dates must be cleared", monthView.hasFlaggedDates()); } /** * test setting/checking flagged dates (api with Date) */ @Test public void testFlaggedDateClearNotify() { JXMonthView monthView = new JXMonthView(); monthView.setFlaggedDates(tomorrow, yesterday); SortedSet oldFlagged = monthView.getFlaggedDates(); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.clearFlaggedDates(); TestUtils.assertPropertyChangeEvent(report, "flaggedDates", oldFlagged, monthView.getFlaggedDates()); } /** * test setting/checking flagged dates (api with Date) */ @Test public void testFlaggedDateAdd() { JXMonthView monthView = new JXMonthView(); monthView.setFlaggedDates(yesterday); monthView.addFlaggedDates(tomorrow); assertEquals(2, monthView.getFlaggedDates().size()); assertTrue(monthView.isFlaggedDate(yesterday)); assertTrue(monthView.isFlaggedDate(tomorrow)); } /** * test setting/checking flagged dates (api with Date) */ @Test public void testFlaggedDateAddNotify() { JXMonthView monthView = new JXMonthView(); monthView.setFlaggedDates(yesterday); SortedSet oldFlagged = monthView.getFlaggedDates(); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.addFlaggedDates(tomorrow); TestUtils.assertPropertyChangeEvent(report, "flaggedDates", oldFlagged, monthView.getFlaggedDates()); } /** * test setting/checking flagged dates (api with Date) */ @Test public void testFlaggedDateSet() { JXMonthView monthView = new JXMonthView(); monthView.setFlaggedDates(today); assertTrue(monthView.isFlaggedDate(today)); monthView.setFlaggedDates(); assertFalse(monthView.isFlaggedDate(today)); } /** * test setting/checking flagged dates (api with Date) */ @Test public void testFlaggedDateNotification() { JXMonthView monthView = new JXMonthView(); SortedSet oldFlagged = monthView.getFlaggedDates(); PropertyChangeReport report = new PropertyChangeReport(); monthView.addPropertyChangeListener(report); monthView.setFlaggedDates(today); TestUtils.assertPropertyChangeEvent(report, "flaggedDates", oldFlagged, monthView.getFlaggedDates()); } /** * test setting/checking flagged dates (api with Date) */ @Test public void testFlaggedDateGet() { JXMonthView monthView = new JXMonthView(); Date date = new Date(); SortedSet set = new TreeSet(); set.add(monthView.getSelectionModel().getNormalizedDate(date)); monthView.setFlaggedDates(date); assertEquals(set, monthView.getFlaggedDates()); } @Test public void testShowLeadingDates() { JXMonthView monthView = new JXMonthView(); assertFalse(monthView.isShowingLeadingDays()); monthView.setShowingLeadingDays(true); assertTrue(monthView.isShowingLeadingDays()); } @Test public void testShowTrailingDates() { JXMonthView monthView = new JXMonthView(); assertFalse(monthView.isShowingTrailingDays()); monthView.setShowingTrailingDays(true); assertTrue(monthView.isShowingTrailingDays()); } private Date startOfDay(Date date) { return CalendarUtils.startOfDay(calendar, date); } private Date endOfDay(Date date) { return CalendarUtils.endOfDay(calendar, date); } }swingx-1.0-src/src/test/org/jdesktop/swingx/JXTaskPaneContainerTest.java0000644000175000017500000000465211210401722025234 0ustar tonytony/* * $Id: JXTaskPaneContainerTest.java,v 1.7 2009/01/27 22:53:23 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx; import java.awt.event.ActionEvent; import javax.swing.plaf.UIResource; import junit.framework.TestCase; import org.jdesktop.swingx.action.AbstractActionExt; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; @RunWith(JUnit4.class) public class JXTaskPaneContainerTest extends TestCase { @Test public void testAddon() throws Exception { // move around all addons TestUtilities.cycleAddons(new JXTaskPaneContainer()); } /** * Issue #843-swingx: BasicTaskPaneContainerUI must respect custom Layout. */ @Test public void testRespectCustomLayoutGap() { JXTaskPaneContainer container = new JXTaskPaneContainer(); VerticalLayout layout = (VerticalLayout) container.getLayout(); VerticalLayout custom = new VerticalLayout(layout.getGap() + 10); container.setLayout(custom); container.updateUI(); assertEquals(custom.getGap(), ((VerticalLayout) container.getLayout()) .getGap()); } /** * Issue #843-swingx: BasicTaskPaneContainerUI must respect custom Layout. */ @Test public void testRespectCustomLayout() { JXTaskPaneContainer container = new JXTaskPaneContainer(); VerticalLayout layout = (VerticalLayout) container.getLayout(); VerticalLayout custom = new VerticalLayout(layout.getGap() + 10); container.setLayout(custom); container.updateUI(); assertSame(custom, container.getLayout()); } /** * Issue #843-swingx: BasicTaskPaneContainerUI must respect custom Layout. */ @Test public void testLayoutUIResource() { JXTaskPaneContainer container = new JXTaskPaneContainer(); assertTrue(container.getLayout() instanceof UIResource); } private void fillTaskPane(JXTaskPane first) { first.add(new AbstractActionExt("some") { public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } }); first.add(new AbstractActionExt("other") { public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } }); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXStatusBarVisualCheck.java0000644000175000017500000001471711210401722025060 0ustar tonytony/* * Created on 16.03.2006 * */ package org.jdesktop.swingx; import java.awt.event.ActionEvent; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JRootPane; import javax.swing.border.TitledBorder; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.test.AncientSwingTeam; public class JXStatusBarVisualCheck extends InteractiveTestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger .getLogger(JXStatusBarVisualCheck.class.getName()); public static void main(String[] args) { JXStatusBarVisualCheck test = new JXStatusBarVisualCheck(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Decorate.*"); } catch (Exception ex) { } } /** * Issue #936-swingx: JXRootPane can't cope with default decoration. */ public void interactiveDefaultDecorated() { JXTable table = new JXTable(new AncientSwingTeam()); final JXFrame frame = wrapWithScrollingInFrame(table, "toggle laf decoration"); Action toggleDecoration = new AbstractAction("toggleDecoration") { public void actionPerformed(ActionEvent e) { boolean wasDecoratedByLAF = frame.isUndecorated(); frame.setVisible(false); frame.dispose(); frame.setUndecorated(!wasDecoratedByLAF); frame.getRootPane().setWindowDecorationStyle(wasDecoratedByLAF ? JRootPane.NONE : JRootPane.FRAME ); frame.setVisible(true); } }; addAction(frame, toggleDecoration); addStatusMessage(frame, "we must be showing"); show(frame); } /** * Use-case: mimic win2k explorer status bar. * * has a - leading message area which resizes on frame resize - two trailing * fixed size text areas with different fixed sizes. * * goal: - add the message text - add the trailing labels - auto-space (in * win2k that would be "gaps" between the labels, in other LFs it would be), * that is no need to manually insert anything nor fiddle with "insets". The * LF should come up with a reasonable default. - simple constraint for * trailing, that is no need for any hack with weights * */ public void interactiveWin2kExplorerStatus() { JComponent panel = new JXPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); panel.add(createIconLabel("resources/images/explorer_win2k.png")); panel.add(createIconLabel("resources/images/explorer_win2k_narrow.png")); final JXFrame frame = wrapInFrame(panel, "Compare with screenshots"); addMessage(frame, "18 Objekt(e) (Freier Speicherplatz 2,08 GB)"); JXStatusBar statusBar = getStatusBar(frame); statusBar.add(new JLabel("286 Byte")); // , JLabel.TRAILING); statusBar.add(new JLabel("[ ] Arbeitsplatz")); //, JLabel.TRAILING); frame.setSize(1000, 200); frame.setVisible(true); } /** * Use-case: mimic win2k eclipse status bar. * * has a * - trailing fixed size area for progress info * - before that: three fixed-size text areas (which are near to * same size, but aren't :-) Hmm.... maybe they aren't even fixed-size, * the separators in the wide vs narrow screenshot aren't exactly aligned. * * This might be a compound statusbar (one being the context infos, the * other for progress info) - so could be considered a edge case, * not necessarily included. * * goals (as far as the text fields go) are similar to the explorer * plus: * - support equals size cells * - keep layout if one of the text labels is removed/hidden * * */ public void interactiveWin2kEclipseStatus() { JComponent panel = new JXPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); panel.add(createIconLabel("resources/images/eclipse_win2k.png")); panel.add(createIconLabel("resources/images/eclipse_win2k_narrow.png")); panel.add(createIconLabel("resources/images/eclipse_win2k_empty.png")); final JXFrame frame = wrapInFrame(panel, "Compare with screenshots"); // JW: this is a hack .. add an empty label to force the following // components to trailing addMessage(frame, ""); JXStatusBar statusBar = getStatusBar(frame); statusBar.add(new JLabel("Writable")); // , JLabel.TRAILING); final JLabel insertLabel = new JLabel("Smart Insert"); statusBar.add(insertLabel); //, JLabel.TRAILING); statusBar.add(new JLabel("2440 : 59")); //, JLabel.TRAILING); // mimic a second statusbar? statusBar.add(new JLabel("Building workspace ...")); Action action = new AbstractActionExt("toggle insertLabel") { public void actionPerformed(ActionEvent e) { insertLabel.setVisible(!insertLabel.isVisible()); } }; addAction(frame, action); frame.setSize(1000, 200); frame.setVisible(true); } private JLabel createIconLabel(String resource) { Icon wideIcon = new ImageIcon(getClass().getResource(resource)); JLabel wide = new JLabel(wideIcon); wide.setAlignmentX(JLabel.TRAILING); return wide; } /** * Issue ??-swingx: JXStatusBar must be bidi-compliant. * * On toggle CO, status bar should revers order of components. */ public void interactiveRToL() { final JComponent panel = new JXPanel(); panel.add(new JLabel("leading")); panel.add(new JLabel("trailing")); panel.setBorder(new TitledBorder("FlowLayout")); final JXFrame frame = wrapWithScrollingInFrame(panel, "Bidi-compliance of StatusBar"); addMessage(frame, "leading"); JXStatusBar statusBar = getStatusBar(frame); statusBar.add(new JLabel("trailing")); addComponentOrientationToggle(frame); frame.setSize(200, 400); frame.setVisible(true); } /** * do-nothing method - suppress warning if there are no other * test fixtures to run. * */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXTreeUnitTest.java0000644000175000017500000006230311210401722023417 0ustar tonytony/* * $Id: JXTreeUnitTest.java,v 1.39 2009/03/20 15:11:24 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx; import java.awt.Color; import java.util.Hashtable; import java.util.Vector; import javax.swing.JTree; import javax.swing.UIManager; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellEditor; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeCellEditor; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreePath; import org.jdesktop.swingx.JXTree.DelegatingRenderer; import org.jdesktop.swingx.JXTreeTableUnitTest.InsertTreeTableModel; import org.jdesktop.swingx.decorator.ColorHighlighter; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.SearchPredicate; import org.jdesktop.swingx.renderer.DefaultTreeRenderer; import org.jdesktop.swingx.renderer.StringValue; import org.jdesktop.swingx.renderer.StringValues; import org.jdesktop.swingx.tree.DefaultXTreeCellEditor; import org.jdesktop.swingx.tree.DefaultXTreeCellRenderer; import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.swingx.treetable.TreeTableModel; import org.jdesktop.test.AncientSwingTeam; import org.jdesktop.test.PropertyChangeReport; import org.jdesktop.test.TestUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for JXTree. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class JXTreeUnitTest extends InteractiveTestCase { protected TreeTableModel treeTableModel; public JXTreeUnitTest() { super("JXTree Test"); } /** * Issue #1061-swingx: renderer/editor inconsistent on startup */ @Test public void testRendererOnInit() { TestTree tree = new TestTree(); assertSame(tree.getSuperRenderer(), tree.getCellRenderer()); } /** * Issue #1061-swingx: renderer/editor inconsistent on startup */ @Test public void testEditorOnInit() { TestTree tree = new TestTree(); assertSame(tree.getSuperEditor(), tree.getCellEditor()); } /** * Issue #1061-swingx: renderer/editor inconsistent on startup */ @Test public void testDefaultRendererOnInit() { TestTree tree = new TestTree(); assertNotNull("sanity: default renderer created", tree.getCreatedDefaultRenderer()); assertSame("sanity: default renderer used as wrappee", tree.getCreatedDefaultRenderer(), tree.getWrappedCellRenderer()); } /** * Issue #1061-swingx: renderer/editor inconsistent on startup. * Note: this test will fail once we use an enhanced cellEditor (which can cope with * SwingX default renderers). */ @Test public void testDefaultRendererUsedInEditorOnInit() { TestTree tree = new TestTree(); assertTrue("sanity: editor is of type DefaultXTreeCellEditor", tree.getCellEditor() instanceof DefaultXTreeCellEditor); assertSame(tree.getWrappedCellRenderer(), ((DefaultXTreeCellEditor) tree.getCellEditor()).getRenderer()); } /** * Subclass for testing: access cellRenderer/cellEditor fields */ public static class TestTree extends JXTree { private TreeCellRenderer createdDefaultRenderer; public TreeCellRenderer getSuperRenderer() { return cellRenderer; } public TreeCellEditor getSuperEditor() { return cellEditor; } public TreeCellRenderer getCreatedDefaultRenderer() { return createdDefaultRenderer; } @Override protected TreeCellRenderer createDefaultCellRenderer() { createdDefaultRenderer = super.createDefaultCellRenderer(); return createdDefaultRenderer; } } /** * Issue #862-swingx: JXTree - add api for selection colors. */ @Test public void testSelectionBackground() { JXTree tree = new JXTree(); Color uiColor = UIManager.getColor("Tree.selectionBackground"); assertEquals(uiColor, tree.getSelectionBackground()); Color customColor = Color.RED; tree.setSelectionBackground(customColor); tree.updateUI(); assertEquals("custom color must not be reset by ui", customColor, tree.getSelectionBackground()); } /** * Issue #862-swingx: JXTree - add api for selection colors. */ @Test public void testSelectionForeground() { JXTree tree = new JXTree(); Color uiColor = UIManager.getColor("Tree.selectionForeground"); assertEquals(uiColor, tree.getSelectionForeground()); Color customColor = Color.RED; tree.setSelectionForeground(customColor); tree.updateUI(); assertEquals("custom color must not be reset by ui", customColor, tree.getSelectionForeground()); } /** * Issue #862-swingx: JXTree - add api for selection colors. */ @Test public void testSelectionBackgroundChange() { JXTree tree = new JXTree(); Color uiColor = tree.getSelectionBackground(); Color customColor = Color.RED; PropertyChangeReport report = new PropertyChangeReport(); tree.addPropertyChangeListener(report); tree.setSelectionBackground(customColor); TestUtils.assertPropertyChangeEvent(report, "selectionBackground", uiColor, customColor); } /** * Issue #862-swingx: JXTree - add api for selection colors. */ @Test public void testSelectionForegroundChange() { JXTree tree = new JXTree(); Color uiColor = tree.getSelectionForeground(); Color customColor = Color.RED; PropertyChangeReport report = new PropertyChangeReport(); tree.addPropertyChangeListener(report); tree.setSelectionForeground(customColor); TestUtils.assertPropertyChangeEvent(report, "selectionForeground", uiColor, customColor); } /** * Issue #817-swingx: Delegating renderer must create list's default. * Consistent api: expose wrappedRenderer the same way as wrappedModel */ @Test public void testWrappedRendererDefault() { JXTree list = new JXTree(); DelegatingRenderer renderer = (DelegatingRenderer) list.getCellRenderer(); assertSame("wrapping renderer must use list's default on null", renderer.getDelegateRenderer(), list.getWrappedCellRenderer()); } /** * Issue #817-swingx: Delegating renderer must create list's default. * Consistent api: expose wrappedRenderer the same way as wrappedModel */ @Test public void testWrappedRendererCustom() { JXTree list = new JXTree(); DelegatingRenderer renderer = (DelegatingRenderer) list.getCellRenderer(); TreeCellRenderer custom = new DefaultTreeRenderer(); list.setCellRenderer(custom); assertSame("wrapping renderer must use list's default on null", renderer.getDelegateRenderer(), list.getWrappedCellRenderer()); } /** * Issue #817-swingx: Delegating renderer must create list's default. * Delegating uses default on null, here: default default. */ @Test public void testDelegatingRendererUseDefaultSetNull() { JXTree list = new JXTree(); TreeCellRenderer defaultRenderer = list.createDefaultCellRenderer(); DelegatingRenderer renderer = (DelegatingRenderer) list.getCellRenderer(); list.setCellRenderer(null); assertEquals("wrapping renderer must use list's default on null", defaultRenderer.getClass(), renderer.getDelegateRenderer().getClass()); } /** * Issue #817-swingx: Delegating renderer must create list's default. * Delegating has default from list initially, here: default default. * * Note: this test has to be changed once we switch to default to DefaultTreeRenderer. */ @Test public void testDelegatingRendererUseDefault() { JXTree list = new JXTree(); TreeCellRenderer defaultRenderer = list.createDefaultCellRenderer(); assertEquals("sanity: creates default", DefaultXTreeCellRenderer.class, defaultRenderer.getClass()); DelegatingRenderer renderer = (DelegatingRenderer) list.getCellRenderer(); assertEquals(defaultRenderer.getClass(), renderer.getDelegateRenderer().getClass()); } /** * Issue #817-swingx: Delegating renderer must create list's default. * Delegating has default from list initially, here: custom default. */ @Test public void testDelegatingRendererUseCustomDefaultSetNull() { JXTree list = new JXTree() { @Override protected TreeCellRenderer createDefaultCellRenderer() { return new CustomDefaultRenderer(); } }; TreeCellRenderer defaultRenderer = list.createDefaultCellRenderer(); DelegatingRenderer renderer = (DelegatingRenderer) list.getCellRenderer(); list.setCellRenderer(null); assertEquals("wrapping renderer must use list's default on null", defaultRenderer.getClass(), renderer.getDelegateRenderer().getClass()); } /** * Issue #817-swingx: Delegating renderer must create list's default. * Delegating has default from list initially, here: custom default. */ @Test public void testDelegatingRendererUseCustomDefault() { JXTree list = new JXTree() { @Override protected TreeCellRenderer createDefaultCellRenderer() { return new CustomDefaultRenderer(); } }; TreeCellRenderer defaultRenderer = list.createDefaultCellRenderer(); assertEquals("sanity: creates custom", CustomDefaultRenderer.class, defaultRenderer.getClass()); DelegatingRenderer renderer = (DelegatingRenderer) list.getCellRenderer(); assertEquals(defaultRenderer.getClass(), renderer.getDelegateRenderer().getClass()); } /** * Dummy extension for testing - does nothing more as super. * For tree, we subclass swingx renderer, as the default still it core default. */ public static class CustomDefaultRenderer extends DefaultTreeRenderer { } /** * Issue #767-swingx: consistent string representation. * * Here: test api on JXTable. */ @Test public void testGetStringForRow() { JXTree tree = new JXTree(AncientSwingTeam.createNamedColorTreeModel()); tree.expandAll(); StringValue sv = new StringValue() { public String getString(Object value) { if (value instanceof Color) { Color color = (Color) value; return "R/G/B: " + color.getRGB(); } return StringValues.TO_STRING.getString(value); } }; tree.setCellRenderer(new DefaultTreeRenderer(sv)); Object value =((DefaultMutableTreeNode) tree.getPathForRow(2).getLastPathComponent()).getUserObject(); String text = tree.getStringAt(2); assertEquals(sv.getString(value), text); } /** * Issue #767-swingx: consistent string representation. * * Here: test api on JXTable. */ @Test public void testGetStringForPath() { JXTree tree = new JXTree(AncientSwingTeam.createNamedColorTreeModel()); tree.expandAll(); StringValue sv = new StringValue() { public String getString(Object value) { if (value instanceof Color) { Color color = (Color) value; return "R/G/B: " + color.getRGB(); } return StringValues.TO_STRING.getString(value); } }; tree.setCellRenderer(new DefaultTreeRenderer(sv)); Object value =((DefaultMutableTreeNode) tree.getPathForRow(2).getLastPathComponent()).getUserObject(); String text = tree.getStringAt(tree.getPathForRow(2)); assertEquals(sv.getString(value), text); } /** * Issue #769-swingx: setXXIcon on renderer vs setXXIcon on Tree/Table. * Characterize tree behaviour. * * Here: icon on renderer must be respected if overwrite is false. */ @Test public void testIconSetOnRendererFalseOverwrite() { JXTree tree = new JXTree(); DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer(); renderer.setLeafIcon(null); tree.setCellRenderer(renderer); assertEquals("renderer must have null leaf icon", null, renderer.getLeafIcon()); } /** * Issue #769-swingx: setXXIcon on renderer vs setXXIcon on Tree/Table. * Characterize tree behaviour. * * Here: icon on renderer must be overwritten if overwrite is true. */ @Test public void testIconSetOnRendererTrueOverwrite() { JXTree tree = new JXTree(); tree.setLeafIcon(null); tree.setOverwriteRendererIcons(true); // PENDING: incomplete api - no getter // Icon leaf = tree.getLeafIcon(); DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer(); assertNotNull("sanity - the renderer has a leafIcon ", renderer.getLeafIcon()); tree.setCellRenderer(renderer); assertEquals("renderer leaf icon must be overwritten by tree's leaf icon", null, renderer.getLeafIcon()); } /** * Issue #769-swingx: setXXIcon on renderer vs setXXIcon on Tree/Table. * Characterize tree behaviour. * * Here: set icon on tree is passed on to renderer always. */ @Test public void testIconSetOnTreeFalseOverwrite() { JXTree tree = new JXTree(); DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer(); assertNotNull(renderer.getLeafIcon()); tree.setCellRenderer(renderer); tree.setLeafIcon(null); assertEquals("renderer must have null leaf icon", null, renderer.getLeafIcon()); } /** * Issue #769-swingx: setXXIcon on renderer vs setXXIcon on Tree/Table. * Characterize tree behaviour. * * Here: set icon on tree is passed on to renderer always. */ @Test public void testIconSetOnTreeTrueOverwrite() { JXTree tree = new JXTree(); tree.setOverwriteRendererIcons(true); DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer(); assertNotNull(renderer.getLeafIcon()); tree.setCellRenderer(renderer); tree.setLeafIcon(null); assertEquals("renderer must have null leaf icon", null, renderer.getLeafIcon()); } /** * Issue #769-swingx: setXXIcon on renderer vs setXXIcon on Tree/Table. * Characterize tree behaviour. * * Here: default overwriteOnRenderer is false. */ @Test public void testIconOverwriteInitial() { JXTree tree = new JXTree(); assertFalse("initial overwriteRendererIcons must be false", tree.isOverwriteRendererIcons()); } /** * focus issues with popup in editors: tweak with * custom cellEditorListener. * */ @Test public void testEditorListenerRemovedOnEditorStopped() { JXTree tree = createEditingTree(); DefaultTreeCellEditor cellEditor = (DefaultTreeCellEditor) tree.getCellEditor(); // core doesn't remove the listener ... dooh cellEditor.stopCellEditing(); // but we do ... assertEquals(1, cellEditor.getCellEditorListeners().length); } /** * focus issues with popup in editors: tweak with * custom cellEditorListener. * */ @Test public void testEditorListenerRemovedOnEditorCancel() { JXTree tree = createEditingTree(); DefaultTreeCellEditor cellEditor = (DefaultTreeCellEditor) tree.getCellEditor(); // core doesn't remove the listener ... dooh cellEditor.cancelCellEditing(); // but we do ... assertEquals(1, cellEditor.getCellEditorListeners().length); } /** * focus issues with popup in editors: tweak with * custom cellEditorListener. * */ @Test public void testEditorListenerRemovedOnTreeCancel() { JXTree tree = createEditingTree(); DefaultTreeCellEditor cellEditor = (DefaultTreeCellEditor) tree.getCellEditor(); // core doesn't remove the listener ... dooh tree.cancelEditing(); // but we do ... assertEquals(1, cellEditor.getCellEditorListeners().length); } /** * focus issues with popup in editors: tweak with * custom cellEditorListener. * */ @Test public void testEditorListenerRemovedOnTreeStop() { JXTree tree = createEditingTree(); DefaultTreeCellEditor cellEditor = (DefaultTreeCellEditor) tree.getCellEditor(); // core doesn't remove the listener ... dooh tree.stopEditing(); // but we do ... assertEquals(1, cellEditor.getCellEditorListeners().length); } /** * focus issues with popup in editors: tweak with * custom cellEditorListener. * */ @Test public void testEditorListenerOnXTree() { JTree core = new JTree(); int coreCount = getListenerCountAfterStartEditing(core); JXTree tree = createEditingTree(); DefaultTreeCellEditor cellEditor = (DefaultTreeCellEditor) tree.getCellEditor(); assertEquals("need one more listener than core", coreCount + 1, cellEditor.getCellEditorListeners().length); } /** * @return a tree with default model and editing started on row 2 */ private JXTree createEditingTree() { JXTree tree = new JXTree(); tree.setEditable(true); // sanity assertTrue(tree.getRowCount() > 2); TreePath path = tree.getPathForRow(2); tree.startEditingAtPath(path); return tree; } /** * characterization: listeners in core tree. * */ @Test public void testEditorListenerOnCoreTree() { JTree tree = new JTree(); int listenerCount = getListenerCountAfterStartEditing(tree); assertEquals(1, listenerCount); tree.stopEditing(); // doesn't remove the listener ... dooh assertEquals(1, ((DefaultTreeCellEditor) tree.getCellEditor()).getCellEditorListeners().length); } /** * Starts editing on row 2 and returns the cell editor listener count after. * * @param tree * @return */ private int getListenerCountAfterStartEditing(JTree tree) { tree.setEditable(true); // sanity assertTrue(tree.getRowCount() > 2); TreePath path = tree.getPathForRow(2); tree.startEditingAtPath(path); DefaultTreeCellEditor cellEditor = (DefaultTreeCellEditor) tree.getCellEditor(); int listenerCount = cellEditor.getCellEditorListeners().length; return listenerCount; } /** * Issue #473-swingx: NPE in JXTree with highlighter.

* * Renderers are doc'ed to cope with invalid input values. * Highlighters can rely on valid ComponentAdapter state. * JXTree delegatingRenderer is the culprit which does set * invalid ComponentAdapter state. Negative invalid index. * */ @Test public void testIllegalNegativeTreeRowIndex() { JXTree tree = new JXTree(); tree.expandAll(); assertTrue(tree.getRowCount() > 0); TreeCellRenderer renderer = tree.getCellRenderer(); renderer.getTreeCellRendererComponent(tree, "dummy", false, false, false, -1, false); SearchPredicate predicate = new SearchPredicate("\\QNode\\E"); Highlighter searchHighlighter = new ColorHighlighter(predicate, null, Color.RED); tree.addHighlighter(searchHighlighter); renderer.getTreeCellRendererComponent(tree, "dummy", false, false, false, -1, false); } /** * Issue #473-swingx: NPE in JXTree with highlighter.

* * Renderers are doc'ed to cope with invalid input values. * Highlighters can rely on valid ComponentAdapter state. * JXTree delegatingRenderer is the culprit which does set * invalid ComponentAdapter state. Invalid index > valid range. * */ @Test public void testIllegalExceedingTreeRowIndex() { JXTree tree = new JXTree(); tree.expandAll(); assertTrue(tree.getRowCount() > 0); TreeCellRenderer renderer = tree.getCellRenderer(); renderer.getTreeCellRendererComponent(tree, "dummy", false, false, false, tree.getRowCount(), false); SearchPredicate predicate = new SearchPredicate("\\QNode\\E"); Highlighter searchHighlighter = new ColorHighlighter(predicate, null, Color.RED); tree.addHighlighter(searchHighlighter); renderer.getTreeCellRendererComponent(tree, "dummy", false, false, false, tree.getRowCount(), false); } /** * test convenience method accessing the configured adapter. * */ @Test public void testConfiguredComponentAdapter() { JXTree list = new JXTree(); list.expandAll(); assertTrue(list.getRowCount() > 0); ComponentAdapter adapter = list.getComponentAdapter(); assertEquals(0, adapter.column); assertEquals(0, adapter.row); assertTrue(adapter.isHierarchical()); adapter.row = 1; // corrupt adapter adapter.column = 1; adapter = list.getComponentAdapter(0); assertEquals(0, adapter.column); assertEquals(0, adapter.row); } /** * Issue #254-swingx: expandAll doesn't expand if root not shown? * */ @Test public void testExpandAllWithInvisible() { final DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode(); final InsertTreeTableModel model = new InsertTreeTableModel(root); int childCount = 5; for (int i = 0; i < childCount; i++) { model.addChild(root); } final JXTree treeTable = new JXTree(model); // sanity... assertTrue(treeTable.isRootVisible()); assertEquals("all children visible", childCount + 1, treeTable.getRowCount()); treeTable.collapseAll(); assertEquals(" all children invisible", 1, treeTable.getRowCount()); treeTable.setRootVisible(false); assertEquals("no rows with invisible root", 0, treeTable.getRowCount()); treeTable.expandAll(); assertTrue(treeTable.getRowCount() > 0); } /** * test enhanced getSelectedRows contract: returned * array != null * */ @Test public void testNotNullGetSelectedRows() { JXTree tree = new JXTree(treeTableModel); // sanity: no selection assertEquals(0, tree.getSelectionCount()); assertNotNull("getSelectedRows guarantees not null array", tree.getSelectionRows()); } /** * test enhanced getSelectedRows contract: returned * array != null * */ @Test public void testNotNullGetSelectedPaths() { JXTree tree = new JXTree(treeTableModel); // sanity: no selection assertEquals(0, tree.getSelectionCount()); assertNotNull("getSelectedPaths guarantees not null array", tree.getSelectionPaths()); } /** * Issue #221-swingx: actionMap not initialized in JXTreeNode constructor. * Issue #231-swingx: icons lost in editor, enhanced default editor not installed. * * PENDING: test all constructors! * */ @Test public void testInitInConstructors() { assertXTreeInit(new JXTree()); assertXTreeInit(new JXTree(new Object[] {})); assertXTreeInit(new JXTree(new Vector())); assertXTreeInit(new JXTree(new Hashtable())); assertXTreeInit(new JXTree(new DefaultMutableTreeNode("dummy"), false)); assertXTreeInit(new JXTree(new DefaultMutableTreeNode("dummy"))); assertXTreeInit(new JXTree(new DefaultTreeModel(new DefaultMutableTreeNode("dummy")))); } /** * @param tree */ private void assertXTreeInit(JXTree tree) { assertNotNull("Actions must be initialized", tree.getActionMap().get("find")); assertTrue("Editor must be DefaultXTreeCellEditor", tree.getCellEditor() instanceof DefaultXTreeCellEditor); // JW: wrong assumption, available for TreeTableModel impl only? // assertNotNull("conversionMethod must be initialized", // tree.getValueConversionMethod(tree.getModel())); // tree.getValueConversionMethod(tree.getModel()); } /** * JTree allows null model. * learning something new every day :-) * */ @Test public void testNullModel() { JXTree tree = new JXTree(); assertNotNull(tree.getModel()); tree.setModel(null); assertEquals(0, tree.getRowCount()); // tree.getComponentAdapter().isLeaf(); } @Override protected void setUp() throws Exception { super.setUp(); treeTableModel = new FileSystemModel(); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXLabelVisualCheck.java0000644000175000017500000000623211210401722024160 0ustar tonytony/* * $Id: JXLabelVisualCheck.java,v 1.1 2009/01/26 22:51:25 rah003 Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx; import java.awt.event.ActionEvent; import java.util.logging.Logger; import javax.swing.Action; import javax.swing.Box; import javax.swing.JComponent; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.painter.AlphaPainter; import org.jdesktop.swingx.painter.CompoundPainter; import org.jdesktop.swingx.painter.ShapePainter; /** * Base test class for JXLabel related code and issues. * * @author rah003 */ public class JXLabelVisualCheck extends InteractiveTestCase { static Logger log = Logger.getAnonymousLogger(); /** * Issue #??-swingx: default foreground painter not guaranteed after change. * * JXLabel restore default foreground painter. * Sequence: * compose the default with a transparent overlay * try to reset to default * try to compose the overlay again. */ public void interactiveRestoreDefaultForegroundPainter() { JComponent box = Box.createVerticalBox(); final JXLabel foreground = new JXLabel( "setup: compound - default and overlay "); ShapePainter shapePainter = new ShapePainter(); final AlphaPainter alpha = new AlphaPainter(); alpha.setAlpha(0.2f); alpha.setPainters(shapePainter); CompoundPainter compound = new CompoundPainter(foreground .getForegroundPainter(), alpha); foreground.setForegroundPainter(compound); box.add(foreground); Action action = new AbstractActionExt("reset default foreground") { boolean reset; public void actionPerformed(ActionEvent e) { if (reset) { CompoundPainter painter = new CompoundPainter(alpha, foreground.getForegroundPainter()); foreground.setForegroundPainter(painter); } else { // try to reset to default foreground.setForegroundPainter(null); } reset = !reset; } }; JXFrame frame = wrapInFrame(box, "foreground painters"); addAction(frame, action); frame.pack(); frame.setVisible(true); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXHeaderTest.java0000644000175000017500000005002111210401722023042 0ustar tonytony/* * $Id: JXHeaderTest.java,v 1.11 2009/01/27 22:53:23 rah003 Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx; import java.awt.Color; import java.awt.Font; import java.net.URL; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.FontUIResource; import javax.swing.plaf.IconUIResource; import junit.framework.TestCase; import org.jdesktop.swingx.test.XTestUtils; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; /** * Unit test for JXHeader. *

* * All test methods in this class are expected to pass. * * PENDING JW: some of the tests are dirty in that they rely on hidden (from the * perspective of the JXHeader) implementation * details of BasicHeaderUI (like how the different parts are implemented). * What/How else to test that? A minor improvement could be reached by testing * the ui delegate directly, as the children are visible to subclasses. So we * would end up testing its contract to extension. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class JXHeaderTest extends TestCase { //---------------- testing icon property, similar to #925 // except that it's not a property normally controlled by the ui defaults. /** * Test that header's icon property set to default value, if any. */ @Test public void testIconDefaultA() { Icon icon = XTestUtils.loadDefaultIcon(); assertNotNull("sanity: default icon loaded", icon); UIManager.put("Header.defaultIcon", icon); JXHeader header = new JXHeader(); try { assertSame(icon, header.getIcon()); } finally { UIManager.put("Header.defaultIcon", null); } } /** * Test that header's icon property set to default value, if any. */ @Test public void testIconLabelDefaultB() { Icon icon = XTestUtils.loadDefaultIcon(); assertNotNull("sanity: default icon loaded", icon); UIManager.put("Header.defaultIcon", icon); JXHeader header = new JXHeader(); try { assertSame(icon, getIconLabel(header).getIcon()); } finally { UIManager.put("Header.defaultIcon", null); } } /** * Test that header's icon property set to default value, if any. */ @Test public void testIconLabelCustomC() { Icon icon = XTestUtils.loadDefaultIcon(); assertNotNull("sanity: default icon loaded", icon); JXHeader header = new JXHeader(); header.setIcon(icon); SwingUtilities.updateComponentTreeUI(header); assertSame(icon, header.getIcon()); assertSame(icon, getIconLabel(header).getIcon()); } /** * Test that header's icon property set to default value, if any. */ @Test public void testIconLabelDefaultUpdateD() { Icon uiDefault = UIManager.getIcon("Header.defaultIcon"); Icon icon = new IconUIResource(XTestUtils.loadDefaultIcon()); assertNotNull("sanity: default icon loaded", icon); JXHeader header = new JXHeader(); header.setIcon(icon); assertSame(icon, getIconLabel(header).getIcon()); SwingUtilities.updateComponentTreeUI(header); assertSame(uiDefault, header.getIcon()); assertSame(uiDefault, getIconLabel(header).getIcon()); } /* * ----------- start testing #925-swingx * * there are several sub-issues: A - property on JXHeader must be set to * defaults B - corresponding property on the appropriate child must be set C - * (sanity) custom property must be kept on both header and child after laf * change D - property on both header and child must be updated to defaults on * laf change if not custom * * The critical (child) properties are those which have default ui properties * controlled by the header, that is font and foreground of description and * title label. So we have one group comprised of tests A-D for each of them, * denoted by the respective postfix. * * PENDING JW: any way to auto-create this tests? The groups are created by c&p * and replace ... error-prone and in fact, introduced testing errors. Which * passed accidentally because the tested properties had the same default value * (f.i. Color.BLACK or so). * */ //-------- property: description font /** * Issue #925-swingx: custom properties lost on updateUI. * Header property set to uimanager setting. */ @Test public void testUpdateUIDescriptionFontA() { Font color = UIManager.getFont("JXHeader.descriptionFont"); assertNotNull("sanity: description font available", color); JXHeader header = new JXHeader(); assertEquals(color, header.getDescriptionFont()); } /** * Issue #925-swingx: custom properties lost on updateUI. * Description label property set to uimanager setting. */ @Test public void testUpdateUIDescriptionLabelFontB() { Font color = UIManager.getFont("JXHeader.descriptionFont"); assertNotNull("sanity: description font available", color); JXHeader header = new JXHeader(); assertEquals(color, getDescriptionLabel(header).getFont()); } /** * Issue #925-swingx: custom properties lost on updateUI. * Description label custom property kept on LAF change. */ @Test public void testUpdateUICustomDescriptionLabelFontC() { Font color = new Font("serif", Font.BOLD, 36); JXHeader header = new JXHeader(); header.setDescriptionFont(color); assertEquals("sanity: description color taken", color, getDescriptionLabel(header).getFont()); SwingUtilities.updateComponentTreeUI(header); assertEquals(color, header.getDescriptionFont()); assertEquals(color, getDescriptionLabel(header).getFont()); } /** * Issue #925-swingx: custom properties lost on updateUI. * Title label property updated to ui default on laf change. */ @Test public void testUpdateUIDefaultDescriptionLabelFontD() { Font uiDefault = new FontUIResource("serif", Font.PLAIN, 36); UIManager.put("JXHeader.descriptionFont", uiDefault); Font color = new FontUIResource("serif", Font.ITALIC, 20); JXHeader header = new JXHeader(); header.setDescriptionFont(color); try { assertEquals(color, header.getDescriptionFont()); assertEquals(color, getDescriptionLabel(header).getFont()); SwingUtilities.updateComponentTreeUI(header); assertEquals(uiDefault, header.getDescriptionFont()); assertEquals(uiDefault, getDescriptionLabel(header).getFont()); } finally { // reset custom property UIManager.put("JXHeader.descriptionFont", null); } } //-------------- property: description foreground /** * Issue #925-swingx: custom properties lost on updateUI. * Header property set to uimanager setting. */ @Test public void testUpdateUIDescriptionForegroundA() { Color color = UIManager.getColor("JXHeader.descriptionForeground"); assertNotNull("sanity: description font available", color); JXHeader header = new JXHeader(); assertEquals(color, header.getDescriptionForeground()); } /** * Issue #925-swingx: custom properties lost on updateUI. * Description label property set to uimanager setting. */ @Test public void testUpdateUIDescriptionLabelForegroundB() { Color color = UIManager.getColor("JXHeader.descriptionForeground"); assertNotNull("sanity: description font available", color); JXHeader header = new JXHeader(); assertEquals(color, getDescriptionLabel(header).getForeground()); } /** * Issue #925-swingx: custom properties lost on updateUI. * Description label custom property kept on LAF change. */ @Test public void testUpdateUICustomDescriptionLabelForegroundC() { Color color = Color.PINK; JXHeader header = new JXHeader(); header.setDescriptionForeground(color); assertEquals("sanity: description color taken", color, getDescriptionLabel(header).getForeground()); SwingUtilities.updateComponentTreeUI(header); assertEquals(color, header.getDescriptionForeground()); assertEquals(color, getDescriptionLabel(header).getForeground()); } /** * Issue #925-swingx: custom properties lost on updateUI. * Description label property updated to ui default on laf change. */ @Test public void testUpdateUIDefaultDescriptionLabelForegroundD() { Color uiDefault = new ColorUIResource(Color.BLUE); UIManager.put("JXHeader.descriptionForeground", uiDefault); Color color = new ColorUIResource(Color.PINK); JXHeader header = new JXHeader(); header.setDescriptionForeground(color); SwingUtilities.updateComponentTreeUI(header); try { assertEquals(uiDefault, header.getDescriptionForeground()); assertEquals(uiDefault, getDescriptionLabel(header).getForeground()); } finally { // reset custom property UIManager.put("JXHeader.descriptionForeground", null); } } //----------- property title foreground /** * Issue #925-swingx: custom properties lost on updateUI. * Header property set to uimanager setting. */ @Test public void testUpdateUITitleForegroundA() { Color color = UIManager.getColor("JXHeader.titleForeground"); assertNotNull("sanity: title foreground available", color); JXHeader header = new JXHeader(); assertEquals(color, header.getTitleForeground()); } /** * Issue #925-swingx: custom properties lost on updateUI. * Title label property set to uimanager setting. */ @Test public void testUpdateUITitleLabelForegroundB() { Color color = UIManager.getColor("JXHeader.titleForeground"); assertNotNull("sanity: title foreground available", color); JXHeader header = new JXHeader(); assertEquals(color, getTitleLabel(header).getForeground()); } /** * Issue #925-swingx: custom properties lost on updateUI. * Title label custom property kept on LAF change. */ @Test public void testUpdateUICustomTitleLabelForegroundC() { Color color = Color.PINK; JXHeader header = new JXHeader(); header.setTitleForeground(color); assertEquals("sanity: title foreground taken", color, getTitleLabel(header).getForeground()); SwingUtilities.updateComponentTreeUI(header); assertEquals(color, header.getTitleForeground()); assertEquals(color, getTitleLabel(header).getForeground()); } /** * Issue #925-swingx: custom properties lost on updateUI. * Title label property updated to ui default on laf change. */ @Test public void testUpdateUIDefaultTitleLabelForegroundD() { Color uiDefault = new ColorUIResource(Color.BLUE); UIManager.put("JXHeader.titleForeground", uiDefault); Color color = new ColorUIResource(Color.PINK); JXHeader header = new JXHeader(); header.setTitleForeground(color); SwingUtilities.updateComponentTreeUI(header); try { assertEquals(uiDefault, header.getTitleForeground()); assertEquals(uiDefault, getTitleLabel(header).getForeground()); } finally { // reset custom property UIManager.put("JXHeader.titleForeground", null); } } //---------- property: title font /** * Issue #925-swingx: custom properties lost on updateUI. * Header property set to uimanager setting. */ @Test public void testUpdateUITitleFontA() { Font font = UIManager.getFont("JXHeader.titleFont"); assertNotNull("sanity: title font available", font); JXHeader header = new JXHeader(); assertEquals(font, header.getTitleFont()); } /** * Issue #925-swingx: custom properties lost on updateUI. * Test title label property set to UIManager prop */ @Test public void testUpdateUITitleLabelFontB() { Font font = UIManager.getFont("JXHeader.titleFont"); assertNotNull("sanity: title font available", font); JXHeader header = new JXHeader(); assertEquals(font, getTitleLabel(header).getFont()); } /** * Issue #925-swingx: custom properties lost on updateUI. * Title label custom property kept on LAF change. */ @Test public void testUpdateUICustomTitleLabelFontC() { Font color = new Font("serif", Font.BOLD, 36); JXHeader header = new JXHeader(); header.setTitleFont(color); assertEquals("sanity: title color taken", color, getTitleLabel(header).getFont()); SwingUtilities.updateComponentTreeUI(header); assertEquals(color, header.getTitleFont()); assertEquals(color, getTitleLabel(header).getFont()); } /** * Issue #925-swingx: custom properties lost on updateUI. * Title label property updated to ui default on laf change. */ @Test public void testUpdateUIDefaultTitleLabelFontD() { Font uiDefault = new FontUIResource("serif", Font.PLAIN, 36); UIManager.put("JXHeader.titleFont", uiDefault); Font color = new FontUIResource("serif", Font.ITALIC, 20); JXHeader header = new JXHeader(); header.setTitleFont(color); try { assertEquals(color, header.getTitleFont()); assertEquals(color, getTitleLabel(header).getFont()); SwingUtilities.updateComponentTreeUI(header); assertEquals(uiDefault, header.getTitleFont()); assertEquals(uiDefault, getTitleLabel(header).getFont()); } finally { // reset custom property UIManager.put("JXHeader.titleFont", null); } } //--------- end testing #925 /** * Issue #695-swingx: not-null default values break class invariant. * Here initial empty constructor. */ @Test public void testTitleSynchInitialEmpty() { JXHeader header = new JXHeader(); assertEquals(header.getTitle(), getTitleLabel(header).getText()); } /** * Issue #695-swingx: not-null default values break invariant. * Here: initial not-null explicitly set to null and updateUI (to * simulate LF toggle). */ @Test public void testTitleSynchUpdateUI() { JXHeader header = new JXHeader("dummy", null); header.setTitle(null); header.updateUI(); assertEquals(header.getTitle(), getTitleLabel(header).getText()); } /** * Issue #695-swingx: not-null default values break invariant. * Here: initial null params constructor. */ @Test public void testTitleSynchInitialNull() { JXHeader header = new JXHeader(null, null); header.setTitle(null); assertEquals(header.getTitle(), getTitleLabel(header).getText()); } /** * Issue #403-swingx: JXHeader doesn't show custom values. * */ @Test public void testIconSet() { URL url = getClass().getResource("resources/images/wellTop.gif"); Icon icon = new ImageIcon(url); assertNotNull(url); JXHeader header = new JXHeader(); header.setIcon(icon); // sanity: the property is set assertEquals(icon, header.getIcon()); // fishing in the internals ... not really safe, there are 2 labels and 1 jxlabel ... indeed not safe! assertEquals("the label's text must be equal to the headers title", header.getIcon(), getIconLabel(header).getIcon()); } /** * Issue #403-swingx: JXHeader doesn't show custom values. * */ @Test public void testTitleSet() { JXHeader header = new JXHeader(); String title = "customTitle"; header.setTitle(title); // sanity: the property is set assertEquals(title, header.getTitle()); assertEquals("the label's text must be equal to the headers title", header.getTitle(), getTitleLabel(header).getText()); } /** * Issue #403-swingx: JXHeader doesn't show custom values. *

* * Breaking if values are passed in the constructor. */ @Test public void testTitleInContructor() { String title = "customTitle"; JXHeader header = new JXHeader(title, null); // sanity: the property is set assertEquals(title, header.getTitle()); assertEquals("the label's text must be equal to the headers title", header.getTitle(), getTitleLabel(header).getText()); } /** * Issue swingx-900 NPE when top level ancestor is not available, while "some" ancestor is. */ @Test public void testNPE() { JXHeader header = new JXHeader(); JPanel panel = new JPanel(); panel.add( header ); panel.setBounds( 0, 0, 200, 200 ); } // ----------------- private helpers (dirty!) /** * Returns the label used for painting the title. Implemented to * return the first child of type JLabel.

* * NOTE: this is fishing in implementation details of BasicHeaderUI! * * @return the label used for painting the title. */ private JLabel getTitleLabel(JXHeader header) { for (int i = 0; i < header.getComponentCount(); i++) { if (header.getComponent(i) instanceof JLabel) { return (JLabel) header.getComponent(i); } } return null; } /** * Returns the label used for painting the description. Implemented to * return the first child of type JXLabel.

* * NOTE: this is fishing in implementation details of BasicHeaderUI! * * @return the label used for painting the description. */ private JLabel getDescriptionLabel(JXHeader header) { for (int i = 0; i < header.getComponentCount(); i++) { if (header.getComponent(i) instanceof JXLabel) { return (JLabel) header.getComponent(i); } } return null; } /** * Returns the label used for painting the icon. Implemented to * return the second child of type JLabel and not of type JXLabel.

* * NOTE: this is fishing in implementation details of BasicHeaderUI! * * @return the label used for painting the icon. */ private JLabel getIconLabel(JXHeader header) { JLabel label = null; for (int i = 0; i < header.getComponentCount(); i++) { if (header.getComponent(i) instanceof JLabel && !(header.getComponent(i) instanceof JXLabel)) { boolean second = label != null; label = (JLabel) header.getComponent(i); if (second) { return label; } } } return null; } @Override protected void setUp() throws Exception { // forcing load of headerAddon new JXHeader(); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXHyperlinkTest.java0000644000175000017500000002063111210401722023623 0ustar tonytony/* * $Id: JXHyperlinkTest.java,v 1.40 2009/03/16 11:37:49 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx; import java.awt.event.ActionEvent; import java.awt.event.MouseListener; import java.util.logging.Logger; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import javax.swing.plaf.UIResource; import junit.framework.TestCase; import org.jdesktop.swingx.hyperlink.AbstractHyperlinkAction; import org.jdesktop.swingx.plaf.basic.BasicHyperlinkUI.BasicHyperlinkListener; import org.jdesktop.test.PropertyChangeReport; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Test of JXHyperlink. Raw usage and as hyperlinkRenderer. *

* * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class JXHyperlinkTest extends TestCase { @SuppressWarnings("all") private static final Logger LOG = Logger.getLogger(JXHyperlinkTest.class .getName()); private PropertyChangeReport report; @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } @Test public void testBorderUIResource() { JXHyperlink hyperlink = new JXHyperlink(); if (!(hyperlink.getBorder() instanceof UIResource)) { LOG.info("not running test, LAF doesn't install hyperlink border"); return; } Border border = new EmptyBorder(1, 2, 3, 4); hyperlink.setBorder(border); hyperlink.updateUI(); assertSame("border untouched in updateUI ", border, hyperlink.getBorder()); } @Test public void testHyperlinkButtonListener() { JXHyperlink hyperlink = new JXHyperlink(); MouseListener[] listeners = hyperlink.getMouseListeners(); for (MouseListener mouseListener : listeners) { if(mouseListener instanceof BasicHyperlinkListener) return; } fail("hyperlink must have installed a BasicHyperlinkListener"); } /** * test control of the clicked property. * * Default behaviour * * */ @Test public void testAutoClicked() { // no action JXHyperlink hyperlink = new JXHyperlink(); hyperlink.doClick(); assertTrue("hyperlink autoClicks if it has no action", hyperlink.isClicked()); AbstractHyperlinkAction emptyAction = createEmptyLinkAction(); JXHyperlink hyperlink2 = new JXHyperlink(emptyAction); hyperlink2.doClick(); assertFalse(emptyAction.isVisited()); assertFalse("hyperlink does nothing if has action", hyperlink2.isClicked()); AbstractHyperlinkAction emptyAction3 = createEmptyLinkAction(); JXHyperlink hyperlink3 = new JXHyperlink(emptyAction3); hyperlink3.setOverrulesActionOnClick(true); hyperlink3.doClick(); assertFalse(emptyAction.isVisited()); assertTrue("hyperlink overrules action", hyperlink3.isClicked()); } @Test public void testOverrulesActionOnClick() { JXHyperlink hyperlink = new JXHyperlink(); assertFalse(hyperlink.getOverrulesActionOnClick()); hyperlink.addPropertyChangeListener(report); hyperlink.setOverrulesActionOnClick(true); assertTrue(hyperlink.getOverrulesActionOnClick()); assertEquals(1, report.getEventCount("overrulesActionOnClick")); } /** * sanity (duplicate of LinkActionTest method) to * guarantee that hyperlink is updated as expected. * */ @Test public void testLinkActionSetTarget() { AbstractHyperlinkAction linkAction = createEmptyLinkAction(); linkAction.setVisited(true); JXHyperlink hyperlink = new JXHyperlink(linkAction); Object target = new Object(); linkAction.setTarget(target); assertEquals(linkAction.getName(), hyperlink.getText()); assertFalse(hyperlink.isClicked()); } /** * test that hyperlink.setClicked doesn't change action.isVisited(); * */ @Test public void testSetClickedActionUnchanged() { AbstractHyperlinkAction linkAction = createEmptyLinkAction(); linkAction.setVisited(true); JXHyperlink hyperlink = new JXHyperlink(linkAction); // sanity assert.. assertTrue(hyperlink.isClicked()); hyperlink.setClicked(false); // action state must be unchanged; assertTrue(linkAction.isVisited()); } /** * test hyperlink's clicked property. * */ @Test public void testClicked() { JXHyperlink hyperlink = new JXHyperlink(); boolean isClicked = hyperlink.isClicked(); assertFalse(isClicked); hyperlink.addPropertyChangeListener(report); hyperlink.setClicked(!isClicked); assertEquals(1, report.getEventCount("clicked")); } /** * JXHyperlink must handle null action gracefully. * * Was NPE in configureFromAction * */ @Test public void testInitNullAction() { JXHyperlink hyperlink = new JXHyperlink(); assertNull(hyperlink.getAction()); } /** * JXHyperlink must handle null action gracefully. * * Was NPE in configureFromAction * */ @Test public void testSetNullAction() { AbstractHyperlinkAction action = createEmptyLinkAction(); JXHyperlink hyperlink = new JXHyperlink(action); assertEquals("hyperlink action must be equal to linkAction", action, hyperlink.getAction()); hyperlink.setAction(null); assertNull(hyperlink.getAction()); } /** * JXHyperlink must handle null action gracefully. * * Was NPE in configureFromAction * */ @Test public void testSetAction() { JXHyperlink hyperlink = new JXHyperlink(); AbstractHyperlinkAction action = createEmptyLinkAction(); hyperlink.setAction(action); assertEquals("hyperlink action must be equal to linkAction", action, hyperlink.getAction()); } /** * test that JXHyperlink visited state keeps synched * to LinkAction. * */ @Test public void testListeningVisited() { AbstractHyperlinkAction linkAction = createEmptyLinkAction(); JXHyperlink hyperlink = new JXHyperlink(linkAction); // sanity: both are expected to be false assertEquals(linkAction.isVisited(), hyperlink.isClicked()); assertFalse(linkAction.isVisited()); linkAction.setVisited(!linkAction.isVisited()); assertEquals(linkAction.isVisited(), hyperlink.isClicked()); } /** * test initial visited state in JXHyperlink is synched to * linkAction given in constructor. * * There was the usual "init" problem with the constructor. * Solved by chaining. * */ @Test public void testInitialVisitedSynched() { AbstractHyperlinkAction linkAction = createEmptyLinkAction(); linkAction.setVisited(true); // sanity: linkAction is changed to true assertTrue(linkAction.isVisited()); JXHyperlink hyperlink = new JXHyperlink(linkAction); assertEquals(linkAction.isVisited(), hyperlink.isClicked()); } public static class Player { String name; int score; public Player(String name, int score) { this.name = name; this.score = score; } @Override public String toString() { return name + " has score: " + score; } } protected AbstractHyperlinkAction createEmptyLinkAction() { AbstractHyperlinkAction linkAction = new AbstractHyperlinkAction(null) { public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } }; return linkAction; } protected AbstractHyperlinkAction createEmptyLinkAction(String name) { AbstractHyperlinkAction linkAction = createEmptyLinkAction(); linkAction.setName(name); return linkAction; } @Override protected void setUp() throws Exception { super.setUp(); report = new PropertyChangeReport(); } } swingx-1.0-src/src/test/org/jdesktop/swingx/SwingXUtilitiesTest.java0000644000175000017500000001431611210401722024532 0ustar tonytony/* * $Id: SwingXUtilitiesTest.java,v 1.4 2009/04/02 20:35:54 kschaefe Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx; import java.awt.Color; import java.awt.GraphicsEnvironment; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import javax.swing.JDialog; import javax.swing.JRootPane; import javax.swing.JWindow; import javax.swing.RepaintManager; import javax.swing.RootPaneContainer; import javax.swing.UIManager; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.UIResource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Contains tests for SwingXUtilities. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class SwingXUtilitiesTest extends InteractiveTestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger .getLogger(SwingXUtilitiesTest.class.getName()); public static void main(String args[]) { setSystemLF(true); // Locale.setDefault(new Locale("es")); SwingXUtilitiesTest test = new SwingXUtilitiesTest(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Compare.*"); // test.runInteractiveTests("interactive.*Tree.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Test doc'ed contract of isUIInstallable. */ @Test public void testUIInstallable() { assertEquals("null must be uiInstallable ", true, SwingXUtilities.isUIInstallable(null)); assertUIInstallable(new Color(10, 10, 10)); assertUIInstallable(new ColorUIResource(10, 10, 10)); } /** * @param color */ private void assertUIInstallable(Object color) { assertEquals("uiInstallabe must be same ", color instanceof UIResource, SwingXUtilities.isUIInstallable(color)); } @Test public void testUpdateAllComponentTreeUIs() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } if (isCrossPlatformLFSameAsSystem()) { LOG.info("cannot run test - no safe LFs to toggle"); return; } List toplevels = new ArrayList(); for (int i = 0; i < 10; i++) { JXFrame frame = new JXFrame(); toplevels.add(frame); toplevels.add(new JDialog(frame)); toplevels.add(new JWindow(frame)); } // sanity if (!UIManager.getLookAndFeel().isNativeLookAndFeel()) { LOG.warning("Assumption is to start with native LaF. Found " + UIManager.getLookAndFeel() + " instead."); } setSystemLF(false); SwingXUtilities.updateAllComponentTreeUIs(); // sanity for (RootPaneContainer window : toplevels) { JRootPane rootPane = window.getRootPane(); assertEquals(UIManager.get(rootPane.getUIClassID()), rootPane.getUI().getClass().getName()); } } /** * @return boolean indicating if system and * cross platform LF are different. */ private boolean isCrossPlatformLFSameAsSystem() { return UIManager.getCrossPlatformLookAndFeelClassName().equals( UIManager.getSystemLookAndFeelClassName()); } @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } @Override protected void setUp() throws Exception { setSystemLF(true); } @Test(expected = NullPointerException.class) public void testGetTranslucentRepaintManagerWithNull() { SwingXUtilities.getTranslucentRepaintManager(null); } @Test public void testGetTranslucentRepaintManagerWithTranslucent() { RepaintManagerX rmx = new RepaintManagerX(new RepaintManager()); RepaintManager rm = SwingXUtilities.getTranslucentRepaintManager(rmx); assertSame(rmx, rm); } @Test public void testGetTranslucentRepaintManagerWithNonTranslucent() { RepaintManager rm = new RepaintManager(); RepaintManager rmx = SwingXUtilities.getTranslucentRepaintManager(rm); assertNotSame(rm, rmx); assertTrue(rmx.getClass().isAnnotationPresent(TranslucentRepaintManager.class)); } @Test public void testGetTranslucentRepaintManagerWithForwardingAndTranslucent() { RepaintManagerX rmx = new RepaintManagerX(new RepaintManager()); ForwardingRepaintManager frm = new ForwardingRepaintManager(rmx); RepaintManager rm = SwingXUtilities.getTranslucentRepaintManager(frm); assertSame(frm, rm); } @Test public void testGetTranslucentRepaintManagerWithForwardingAndNonTranslucent() { ForwardingRepaintManager frm = new ForwardingRepaintManager(new RepaintManager()); RepaintManager rm = SwingXUtilities.getTranslucentRepaintManager(frm); assertNotSame(frm, rm); assertTrue(rm.getClass().isAnnotationPresent(TranslucentRepaintManager.class)); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXDatePickerTest.java0000644000175000017500000017234311210401722023701 0ustar tonytony/* * $Id: JXDatePickerTest.java,v 1.73 2009/03/16 11:37:49 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.GraphicsEnvironment; import java.awt.event.ActionListener; import java.text.DateFormat; import java.text.Format; import java.text.MessageFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import java.util.logging.Logger; import javax.swing.Action; import javax.swing.InputMap; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFormattedTextField; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.plaf.UIResource; import javax.swing.text.DefaultFormatterFactory; import org.jdesktop.swingx.calendar.CalendarUtils; import org.jdesktop.swingx.calendar.DatePickerFormatter; import org.jdesktop.swingx.calendar.DateSelectionModel; import org.jdesktop.swingx.calendar.DefaultDateSelectionModel; import org.jdesktop.swingx.calendar.SingleDaySelectionModel; import org.jdesktop.swingx.plaf.UIManagerExt; import org.jdesktop.swingx.plaf.basic.BasicDatePickerUI.EditorCancelAction; import org.jdesktop.swingx.test.XTestUtils; import org.jdesktop.test.ActionReport; import org.jdesktop.test.PropertyChangeReport; import org.jdesktop.test.TestUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for JXDatePicker. */ @RunWith(JUnit4.class) public class JXDatePickerTest extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(JXDatePickerTest.class .getName()); private Calendar calendar; @Override @Before public void setUp() { calendar = Calendar.getInstance(); } @Override @After public void tearDown() { } /** * Issue #910-swingx: home commit must be disabled if picker not editable. * */ @Test public void testNotEditableNullHomeNavigate() { JXDatePicker picker = new JXDatePicker(); picker.getActionMap().remove(JXDatePicker.HOME_NAVIGATE_KEY); picker.setEditable(!picker.isEditable()); } /** * Issue #910-swingx: home commit must be disabled if picker not editable. * */ @Test public void testNotEditableDisabledHomeNavigate() { JXDatePicker picker = new JXDatePicker(); Action delegate = picker.getActionMap().get(JXDatePicker.HOME_NAVIGATE_KEY); assertEquals(picker.isEditable(), delegate.isEnabled()); picker.setEditable(!picker.isEditable()); assertEquals(picker.isEditable(), delegate.isEnabled()); } /** * Issue #910-swingx: home commit must be disabled if picker not editable. * */ @Test public void testNotEditableNullHomeCommit() { JXDatePicker picker = new JXDatePicker(); picker.getActionMap().remove(JXDatePicker.HOME_COMMIT_KEY); picker.setEditable(!picker.isEditable()); } /** * Issue #910-swingx: home commit must be disabled if picker not editable. * */ @Test public void testNotEditableDisabledHomeCommit() { JXDatePicker picker = new JXDatePicker(); Action delegate = picker.getActionMap().get(JXDatePicker.HOME_COMMIT_KEY); assertEquals(picker.isEditable(), delegate.isEnabled()); picker.setEditable(!picker.isEditable()); assertEquals(picker.isEditable(), delegate.isEnabled()); } /** * Sanity: report in forum that editor not disabled if picker disabled. * Looks okay. */ @Test public void testEnabled() { JXDatePicker picker = new JXDatePicker(); picker.setEnabled(false); assertFalse("sanity: picker disabled", picker.isEnabled()); assertEquals("editor enabled must follow picker enabled", picker.isEnabled(), picker.getEditor().isEnabled()); } /** * Issue #764-swingx: JXDatePicker sizing * * editor must respect columns. */ @Test public void testDatePickerColumns50() { JXDatePicker picker = new JXDatePicker(); picker.getEditor().setColumns(50); JXDatePicker other = new JXDatePicker(new Date()); other.getEditor().setColumns(50); assertEquals(other.getEditor().getPreferredSize(), picker.getEditor().getPreferredSize()); } /** * Issue #764-swingx: JXDatePicker sizing * * editor must respect columns. */ @Test public void testDatePickerColumns5() { JXDatePicker picker = new JXDatePicker(); picker.getEditor().setColumns(5); JXDatePicker other = new JXDatePicker(new Date()); other.getEditor().setColumns(5); assertEquals(other.getEditor().getPreferredSize(), picker.getEditor().getPreferredSize()); } /** * Issue #667-swingx: don't install the datepicker border for gtk. * * Here we are testing that the BasicPickerUI doesn't touch the * editors border if it finds a null. * */ @Test public void testPickerBorder() { // force loading of addon new JXDatePicker(); Border pickerBorder = UIManager.getBorder("JXDatePicker.border"); if (pickerBorder == null) { LOG.info("cant run test - no pickerborder"); return; } try { UIManager.put("JXDatePicker.border", "none"); assertNull(UIManager.getBorder("JXDatePicker.border")); JXDatePicker picker = new JXDatePicker(); JTextField field = new JFormattedTextField(); assertEquals(field.getBorder(), picker.getEditor().getBorder()); } finally { // restore LAF border UIManager.put("JXDatePicker.border", null); assertEquals(pickerBorder, UIManager.getBorder("JXDatePicker.border")); } } /** * Issue #724-swingx: picker must notify about timezone changes. * Here: change the timezone on the monthView - can't guarantee the notification. * At least not without hacks... */ @Test public void testTimeZoneChangeNotificationChangeOnMonthView() { JXDatePicker picker = new JXDatePicker(); TimeZone timeZone = picker.getTimeZone(); TimeZone alternative = getSafeAlternativeTimeZone(timeZone); PropertyChangeReport report = new PropertyChangeReport(); picker.addPropertyChangeListener(report); picker.getMonthView().setTimeZone(alternative); TestUtils.assertPropertyChangeEvent(report, "timeZone", timeZone, alternative, false); } /** * Issue #724-swingx: picker must notify about timezone changes. * Here: change the timezon on the picker - can guarantee the notification. */ @Test public void testTimeZoneChangeNotification() { JXDatePicker picker = new JXDatePicker(); TimeZone timeZone = picker.getTimeZone(); TimeZone alternative = getSafeAlternativeTimeZone(timeZone); PropertyChangeReport report = new PropertyChangeReport(); picker.addPropertyChangeListener(report); picker.setTimeZone(alternative); TestUtils.assertPropertyChangeEvent(report, "timeZone", timeZone, alternative, false); } /** * Issue #724-swingx: picker must notify about timezone changes. * Here: setMonthView must update the picker's timezone if different and * fire a notification. */ @Test public void testTimeZoneSetMonthView() { JXDatePicker picker = new JXDatePicker(); TimeZone timeZone = picker.getTimeZone(); TimeZone alternative = getSafeAlternativeTimeZone(timeZone); // prepare a new monthView with different TimeZone JXMonthView monthView = new JXMonthView(); monthView.setTimeZone(alternative); PropertyChangeReport report = new PropertyChangeReport(); picker.addPropertyChangeListener(report); picker.setMonthView(monthView); TestUtils.assertPropertyChangeEvent(report, "timeZone", timeZone, alternative, false); report.clear(); TimeZone another = getSafeAlternativeTimeZone(alternative); monthView.setTimeZone(another); TestUtils.assertPropertyChangeEvent(report, "timeZone", alternative, another, false); } /** * Issue #568-swingx: picker must respect selection model (as of time fields). * * Behaviour defined by selection model of monthView. While the default * (DaySelectionModel) normalizes the dates to the start of the day in the * model's calendar coordinates, a SingleDaySelectionModel keeps the date as-is. * For now, need to explicitly set. */ @Test public void testSetDateKeepsTime() { JXDatePicker picker = new JXDatePicker(); DateSelectionModel selectionModel = new SingleDaySelectionModel(); picker.getMonthView().setSelectionModel(selectionModel); Date date = new Date(); selectionModel.setSelectionInterval(date, date); Date first = selectionModel.getFirstSelectionDate(); assertEquals("formats diff: " + (date.getTime() - first.getTime()) , date, first); } /** * Issue #??-swingx: JXDatePicker must keep monthView's firstDisplayedDate * in synch with selection/today. * Issue #705-swingx: JXMonthView must not scroll in layoutContainer. * * The implication is that client code (such as JXDatePicker/UI) is * responsible to do the scrolling. */ @Test public void testVisibleMonthContainsSelectionOpenSet() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run testLinkPanelNull - headless"); return; } calendar.set(2008, Calendar.JULY, 15); JXDatePicker picker = new JXDatePicker(); picker.setDate(calendar.getTime()); JXFrame frame = new JXFrame("showing", false); frame.add(picker); frame.pack(); frame.setVisible(true); Action togglePopup = picker.getActionMap().get("TOGGLE_POPUP"); togglePopup.actionPerformed(null); CalendarUtils.startOfMonth(calendar); assertEquals(calendar.getTime(), picker.getMonthView().getFirstDisplayedDay()); frame.dispose(); } /** * Issue #??-swingx: JXDatePicker must keep monthView's firstDisplayedDate * in synch with selection/today. * Issue #705-swingx: JXMonthView must not scroll in layoutContainer. * * The implication is that client code (such as JXDatePicker/UI) is * responsible to do the scrolling. */ @Test public void testVisibleMonthContainsSelectionOpenInitial() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run testLinkPanelNull - headless"); return; } calendar.set(2008, Calendar.JULY, 15); JXDatePicker picker = new JXDatePicker(calendar.getTime()); JXFrame frame = new JXFrame("showing", false); frame.add(picker); frame.setVisible(true); Action togglePopup = picker.getActionMap().get("TOGGLE_POPUP"); togglePopup.actionPerformed(null); CalendarUtils.startOfMonth(calendar); assertEquals(calendar.getTime(), picker.getMonthView().getFirstDisplayedDay()); frame.dispose(); } /** * Issue #??-swingx: JXDatePicker must keep monthView's firstDisplayedDate * in synch with selection/today. * Issue #705-swingx: JXMonthView must not scroll in layoutContainer. * * The implication is that client code (such as JXDatePicker/UI) is * responsible to do the scrolling. */ @Test public void testVisibleMonthContainsSelectionIinitial() { calendar.set(2008, Calendar.JULY, 15); JXDatePicker picker = new JXDatePicker(calendar.getTime()); CalendarUtils.startOfMonth(calendar); assertEquals(calendar.getTime(), picker.getMonthView().getFirstDisplayedDay()); } /** * Issue #??-swingx: JXDatePicker must keep monthView's firstDisplayedDate * in synch with selection/today. * Issue #705-swingx: JXMonthView must not scroll in layoutContainer. * * The implication is that client code (such as JXDatePicker/UI) is * responsible to do the scrolling. */ @Test public void testVisibleMonthContainsSelectionSet() { JXDatePicker picker = new JXDatePicker(); calendar.set(2008, Calendar.JULY, 15); picker.setDate(calendar.getTime()); CalendarUtils.startOfMonth(calendar); assertEquals(calendar.getTime(), picker.getMonthView().getFirstDisplayedDay()); } /** * Issue #693-swingx: format of custom locale. * Here: test constructor with locale parameter. */ @Test public void testCustomLocaleConstructor() { Locale german = Locale.GERMAN; JXDatePicker picker = new JXDatePicker(german); SimpleDateFormat format = (SimpleDateFormat) picker.getFormats()[0]; String pattern = UIManagerExt.getString("JXDatePicker.longFormat", german); assertEquals(pattern , format.toPattern()); } /** * Issue #693-swingx: format of custom locale. * Here: test setLocale. */ @Test public void testCustomLocaleSet() { Locale german = Locale.GERMAN; JXDatePicker picker = new JXDatePicker(); picker.setLocale(german); SimpleDateFormat format = (SimpleDateFormat) picker.getFormats()[0]; String pattern = UIManagerExt.getString("JXDatePicker.longFormat", german); assertEquals(pattern , format.toPattern()); } /** * Issue #690-swingx: custom dateformats lost on switching LF. * * Here: default formats re-set. */ @Test public void testDefaultFormats() { JXDatePicker picker = new JXDatePicker(); DateFormat[] formats = picker.getFormats(); assertEquals(formats.length, picker.getFormats().length); picker.updateUI(); assertNotSame(formats[0], picker.getFormats()[0]); } /** * Issue #690-swingx: custom dateformats lost on switching LF. * * Sanity test: custom format set as expected. */ @Test public void testCustomFormatsSet() { JXDatePicker picker = new JXDatePicker(); DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM,Locale.UK); picker.setFormats(format); DateFormat[] formats = picker.getFormats(); // sanity assertEquals(1, formats.length); assertSame(format, formats[0]); } /** * Issue #690-swingx: custom dateformats lost on switching LF. * * Here: test that custom format is unchanged after updateUI */ @Test public void testCustomFormatsKept() { JXDatePicker picker = new JXDatePicker(); DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM,Locale.UK); picker.setFormats(format); picker.updateUI(); DateFormat[] formats = picker.getFormats(); assertEquals(1, formats.length); assertSame(format, formats[0]); } /** * Issue #542-swingx: NPE in init if linkFormat not set. * * After plaf cleanup no longer as virulent as earlier: with * addResourceBundle, there's always at least the fall-back value in the * bundle, so as long as the bundle is loaded at all, we have a not-null * value (and no way to remove which is okay). * */ @Test public void testLinkFormatStringNull() { // force loading new JXDatePicker(); String key = "JXDatePicker.linkFormat"; String oldLinkFormat = UIManagerExt.getString(key); // sanity: the addon was loaded assertNotNull(oldLinkFormat); UIManager.put(key, null); assertEquals("no null overwrite", oldLinkFormat, UIManagerExt.getString(key)); UIManager.getLookAndFeelDefaults().remove(key); assertEquals("no remove", oldLinkFormat, UIManagerExt.getString(key)); new JXDatePicker(); } /** * Issue #584-swingx: need to clarify null handling. * * Forum report: NPE under certain initial conditions. * */ @Test public void testPickerFormatSetFormats() { JXDatePicker picker = new JXDatePicker(); picker.setFormats((DateFormat[])null); } /** * Issue #584-swingx: need to clarify null handling. * * Forum report: NPE under certain initial conditions. * */ @Test public void testPickerFormatSetFormatsNullElements() { JXDatePicker picker = new JXDatePicker(); try { picker.setFormats(new DateFormat[] { null}); fail("must not accept null elements in format array"); } catch (NullPointerException e) { // doc'ed behaviour } } /** * Issue #584-swingx: need to clarify null handling. * * Forum report: NPE under certain initial conditions. * */ @Test public void testPickerFormatSetFormatStrings() { JXDatePicker picker = new JXDatePicker(); picker.setFormats((String[])null); } /** * Issue #584-swingx: need to clarify null handling. * * Forum report: NPE under certain initial conditions. * */ @Test public void testPickerFormatSetFormatStringsNullElements() { JXDatePicker picker = new JXDatePicker(); try { picker.setFormats(new String[] {null}); fail("must not accept null elements in format array"); } catch (NullPointerException e) { // doc'ed behaviour } } /** * Issue #584-swingx: need to clarify null handling. * * Forum report: NPE under certain initial conditions. * This produced exactly the stacktrace as reported. * */ @Test public void testPickerFormatsNotNull() { JXDatePicker picker = new JXDatePicker(); // trick the picker - no formats picker.getEditor().setFormatterFactory(new DefaultFormatterFactory( new DatePickerFormatter((DateFormat[]) null))); assertNotNull("picker format array must not be null", picker.getFormats()); } /** * Issue #584-swingx: need to clarify null handling. * * */ @Test public void testPickerFormatsNotNullUnknownFormatter() { JXDatePicker picker = new JXDatePicker(); // trick the picker - no formats picker.getEditor().setFormatterFactory(new DefaultFormatterFactory()); assertNotNull("picker format array must not be null", picker.getFormats()); } /** * Issue #565-swingx: popup not closed when focus moved to Combo * Issue #573-swingx: datePicker editor not focused on F2 (in table) * * testing internals: need focus listener add/remove * */ @Test public void testFocusListenerOnPicker() { JXDatePicker picker = new JXDatePicker(); assertEquals(1, picker.getFocusListeners().length); picker.getUI().uninstallUI(picker); assertEquals(0, picker.getFocusListeners().length); } /** * Issue #565-swingx: popup not closed when focus moved to Combo * Issue #573-swingx: datePicker editor not focused on F2 (in table) * * testing internals: need focus listener add/remove * */ @Test public void testFocusListenerOnEditor() { JFormattedTextField field = new JFormattedTextField(new DatePickerFormatter()); int listenerCount = field.getFocusListeners().length; JXDatePicker picker = new JXDatePicker(); assertEquals(listenerCount + 1, picker.getEditor().getFocusListeners().length); picker.getUI().uninstallUI(picker); assertEquals(listenerCount, picker.getEditor().getFocusListeners().length); } /** * tests LinkPanel set to null after showing. * Was: NPE. */ @Test public void testLinkPanelSetNull() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run testLinkPanelNull - headless"); return; } JXDatePicker picker = new JXDatePicker(); JXFrame frame = new JXFrame("showing", false); frame.add(picker); frame.setVisible(true); Action togglePopup = picker.getActionMap().get("TOGGLE_POPUP"); togglePopup.actionPerformed(null); picker.setLinkPanel(null); frame.dispose(); } /** * tests initial null linkPanel. * */ @Test public void testLinkPanelInitalNull() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run testLinkPanelNull - headless"); return; } JXDatePicker picker = new JXDatePicker(); picker.setLinkPanel(null); JXFrame frame = new JXFrame("showing", false); frame.add(picker); frame.setVisible(true); Action togglePopup = picker.getActionMap().get("TOGGLE_POPUP"); togglePopup.actionPerformed(null); frame.dispose(); } /** * Test install/uninstall of LinkPanel when popup is showing. * - removed/added from parent * - bindings initially installed/uninstalled/re-installed */ @Test public void testLinkPanelRemovedAdded() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run testLinkPanelNull - headless"); return; } JXDatePicker picker = new JXDatePicker(); JXFrame frame = new JXFrame("showing", false); frame.add(picker); frame.setVisible(true); // show the popup ... PENDING: need api on picker. Action togglePopup = picker.getActionMap().get("TOGGLE_POPUP"); togglePopup.actionPerformed(null); JPanel linkPanel = picker.getLinkPanel(); // assert the bindings are installed assertLinkPanelBindings(linkPanel, true); Container oldParent = linkPanel.getParent(); // sanity assertNotNull(oldParent); // remove picker.setLinkPanel(null); // assert it is removed assertNull("linkPanel must be removed", linkPanel.getParent()); // assert bindings removed assertLinkPanelBindings(linkPanel, false); // set again picker.setLinkPanel(linkPanel); // assert the bindings are installed again assertLinkPanelBindings(linkPanel, true); assertSame("linkPanel must be added to same parent", oldParent, linkPanel.getParent()); frame.dispose(); } /** * Tests that the linkPanel bindings and actions * are removed (no popup) * */ @Test public void testLinkPanelBindingUninstalled() { JXDatePicker picker = new JXDatePicker(); JComponent linkPanel = picker.getLinkPanel(); picker.setLinkPanel(null); assertLinkPanelBindings(linkPanel, false); } /** * Tests that the linkPanel has actions and keybindings * for homeCommit/-Cancel (initially, no popup) * */ @Test public void testLinkPanelAction() { JXDatePicker picker = new JXDatePicker(); JComponent linkPanel = picker.getLinkPanel(); assertLinkPanelBindings(linkPanel, true); } /** * @param linkPanel */ private void assertLinkPanelBindings(JComponent linkPanel, boolean bound) { if (bound) { assertNotNull("home commit action must be registered", linkPanel.getActionMap().get(JXDatePicker.HOME_COMMIT_KEY)); assertNotNull("home navigate action must be registered", linkPanel.getActionMap().get(JXDatePicker.HOME_NAVIGATE_KEY)); } else { assertNull("home commit action must not be registered", linkPanel.getActionMap().get(JXDatePicker.HOME_COMMIT_KEY)); assertNull("home navigate action must not be registered", linkPanel.getActionMap().get(JXDatePicker.HOME_NAVIGATE_KEY)); } assertKeyBindings(linkPanel, JXDatePicker.HOME_COMMIT_KEY, bound); assertKeyBindings(linkPanel, JXDatePicker.HOME_NAVIGATE_KEY, bound); } /** * PENDING: move to testUtils. * @param comp * @param actionKey */ public void assertKeyBindings(JComponent comp, Object actionKey, boolean bound) { boolean hasAncestorBinding = hasBinding( comp.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT), actionKey); boolean hasFocusedBinding = hasBinding( comp.getInputMap(JComponent.WHEN_FOCUSED), actionKey); boolean hasInFocusedBinding = hasBinding( comp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW), actionKey); boolean hasBinding = hasAncestorBinding || hasFocusedBinding || hasInFocusedBinding; assertEquals("component has keybinding for " + actionKey, bound, hasBinding); } /** * * PENDING: move to testutils. * @param map * @param actionKey */ public boolean hasBinding(InputMap map, Object actionKey) { KeyStroke[] keyStrokes = map.keys(); if (keyStrokes != null) { for (KeyStroke stroke : keyStrokes) { if (actionKey.equals(map.get(stroke))) { return true; } } } return false; } /** * test that the toggle popup is registered in the * picker's actionMap. * * Issue #596-swingx: don't use space to open popup. */ @Test public void testTogglePopupAction() { JXDatePicker picker = new JXDatePicker(); Action togglePopup = picker.getActionMap().get("TOGGLE_POPUP"); assertNotNull(togglePopup); KeyStroke space = KeyStroke.getKeyStroke("alt DOWN"); Object actionKey = picker.getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) .get(space); assertEquals(actionKey, "TOGGLE_POPUP"); } /** * Characterization: when does picker fire action events? * * Test that set date programmatically (directly or indirectly) * does not fire an actionEvent. */ @Test public void testSetDateSilently() { JXDatePicker picker = new JXDatePicker(); ActionReport report = new ActionReport(); picker.addActionListener(report); // via editor Date value = XTestUtils.getStartOfToday(3); picker.getEditor().setValue(value); assertEquals(value, picker.getDate()); // via selection Date selected = XTestUtils.getStartOfToday(4); picker.getMonthView().setSelectionInterval(selected, selected); assertEquals(selected, picker.getDate()); Date date = XTestUtils.getStartOfToday(5); // directly picker.setDate(date); assertEquals(date, picker.getDate()); assertEquals(0, report.getEventCount()); } /** * Enhanced commit/cancel. * * test the cancel produced by the monthview trigger * cancel in the picker. * */ @Test public void testCommitCancelFromMonthViewCancel() { JXDatePicker picker = new JXDatePicker(); final ActionReport report = new ActionReport(); picker.addActionListener(report); Action cancelAction = picker.getMonthView().getActionMap().get(JXMonthView.CANCEL_KEY); cancelAction.actionPerformed(null); assertEquals("must have receive 1 event after monthView cancel", 1, report.getEventCount()); assertEquals(JXDatePicker.CANCEL_KEY, report.getLastActionCommand()); } /** * Enhanced commit/cancel. * * test the commit produced by the monthview trigger * commit in the picker. * */ @Test public void testCommitCancelFromMonthViewCommit() { JXDatePicker picker = new JXDatePicker(); Action commitAction = picker.getMonthView().getActionMap().get(JXMonthView.COMMIT_KEY); final ActionReport report = new ActionReport(); picker.addActionListener(report); commitAction.actionPerformed(null); assertEquals("must have receive 1 event after monthView commit", 1, report.getEventCount()); assertEquals(JXDatePicker.COMMIT_KEY, report.getLastActionCommand()); } /** * Enhanced commit/cancel. * * test that the ui installed a listener. */ @Test public void testCommitCancelListeningToMonthView() { JXMonthView monthView = new JXMonthView(); int standalone = monthView.getListeners(ActionListener.class).length; assertEquals(0, standalone); JXDatePicker picker = new JXDatePicker(); int contained = picker.getMonthView().getListeners(ActionListener.class).length; assertEquals(standalone + 1, contained); } /** * test wrapping and resetting the editors cancel action. * internals ... mostly to be sure about cleanup and re-wire. */ @Test public void testCancelEditorAction() { JFormattedTextField field = new JFormattedTextField(new DatePickerFormatter()); // original action Action original = field.getActionMap().get(EditorCancelAction.TEXT_CANCEL_KEY); assertNotNull(original); JXDatePicker picker = new JXDatePicker(); JFormattedTextField editor = picker.getEditor(); Action wrapper = editor.getActionMap().get(EditorCancelAction.TEXT_CANCEL_KEY); // wrapper installed assertTrue("PickerUI installed the wrapper action", wrapper instanceof EditorCancelAction); // set editor to field picker.setEditor(field); // old editor back to original assertSame("original action must be reset on setEditor", original, editor.getActionMap().get(EditorCancelAction.TEXT_CANCEL_KEY)); Action otherWrapper = field.getActionMap().get(EditorCancelAction.TEXT_CANCEL_KEY); assertTrue(otherWrapper instanceof EditorCancelAction); // created a new one assertNotSame(wrapper, otherWrapper); // uninstall picker.getUI().uninstallUI(picker); assertSame("original action must be reset on uninstall", original, field.getActionMap().get(EditorCancelAction.TEXT_CANCEL_KEY)); } /** * Enhanced commit/cancel. * * test that cancel action reverts silently: date related * state unchanged and no events fired (except the actionEvent). * */ @Test public void testCancelEditRevertsSilently() { JXDatePicker picker = new JXDatePicker(new Date()); String text = picker.getEditor().getText(); // manipulate the text, not entirely safe ... String changed = text.replace('0', '1'); picker.getEditor().setText(changed); final ActionReport actionReport = new ActionReport(); picker.addActionListener(actionReport); picker.getEditor().addActionListener(actionReport); picker.getMonthView().addActionListener(actionReport); final PropertyChangeReport propertyReport = new PropertyChangeReport(); picker.addPropertyChangeListener(propertyReport); picker.getEditor().addPropertyChangeListener(propertyReport); picker.cancelEdit(); assertEquals(0, propertyReport.getEventCount()); assertEquals(1, actionReport.getEventCount()); } /** * Enhanced commit/cancel. * * test that cancel fires as expected. * PENDING: need to invoke ... safe test? * */ @Test public void testCommitCancelActionsFireCancel() { JXDatePicker picker = new JXDatePicker(); final ActionReport report = new ActionReport(); picker.addActionListener(report); Action cancelAction = picker.getActionMap().get(JXDatePicker.CANCEL_KEY); cancelAction.actionPerformed(null); assertEquals(1, report.getEventCount()); assertEquals(JXDatePicker.CANCEL_KEY, report.getLastActionCommand()); } /** * Enhanced commit/cancel. * * test that commit fires as expected. * PENDING: need to invoke ... safe test? */ @Test public void testCommitCancelActionsFireCommit() { JXDatePicker picker = new JXDatePicker(); Action commitAction = picker.getActionMap().get(JXDatePicker.COMMIT_KEY); final ActionReport report = new ActionReport(); picker.addActionListener(report); commitAction.actionPerformed(null); assertEquals(1, report.getEventCount()); assertEquals(JXDatePicker.COMMIT_KEY, report.getLastActionCommand()); } /** * Enhanced commit/cancel. * * test that actions are registered. * */ @Test public void testCommitCancelActionExist() { JXDatePicker picker = new JXDatePicker(); assertNotNull(picker.getActionMap().get(JXDatePicker.CANCEL_KEY)); assertNotNull(picker.getActionMap().get(JXDatePicker.COMMIT_KEY)); } /** * Issue #658-swingx: timezone in linkformat updated. * * linkDate synced with monthView's today after setting. */ @Test public void testLinkDateSetToday() { JXDatePicker picker = new JXDatePicker(); Calendar cal = picker.getMonthView().getCalendar(); cal.setTime(picker.getMonthView().getToday()); cal.add(Calendar.MONTH, 1); CalendarUtils.endOfDay(cal); // NOTE: no public api, testing to guarantee the synch in all cases picker.getMonthView().setToday(cal.getTime()); assertEquals(picker.getMonthView().getToday(), picker.getLinkDay()); } /** * Issue #658-swingx: timezone in linkformat updated. * * Initial linkDate synced with monthView's today. */ @Test public void testLinkDateInitial() { JXDatePicker picker = new JXDatePicker(); assertEquals(picker.getMonthView().getToday(), picker.getLinkDay()); } /** * Issue #658-swingx: timezone in linkformat updated. * * Here: set timezone in picker. */ @Test public void testSynchTimeZoneLinkFormatOnModified() { JXDatePicker picker = new JXDatePicker(); TimeZone alternative = getSafeAlternativeTimeZone(picker.getTimeZone()); picker.setTimeZone(alternative); assertTimeZoneLinkFormat(picker, alternative); } /** * Issue #554-swingx: timezone of formats and picker must be synched. * Here: set monthView with alternative timezone */ @Test public void testSynchTimeZoneLinkFormatOnSetMonthView() { JXDatePicker picker = new JXDatePicker(); TimeZone defaultZone = picker.getTimeZone(); TimeZone alternative = getSafeAlternativeTimeZone(defaultZone); JXMonthView monthView = new JXMonthView(); monthView.setTimeZone(alternative); picker.setMonthView(monthView); assertTimeZoneLinkFormat(picker, alternative); } /** * Assert that all DateFormats in the picker's linkFormat have the same * timezone as the picker. * * @param picker the JXDatePicker to test * @param alternative the expected timeZone of the picker (for sanity only) */ private void assertTimeZoneLinkFormat(JXDatePicker picker, TimeZone alternative) { // sanity: picker has timezone as expected assertEquals("expected timezone in picker", alternative, picker.getTimeZone()); MessageFormat format = picker.getLinkFormat(); for (Format subFormat : format.getFormats()) { if (subFormat instanceof DateFormat) { assertEquals(picker.getTimeZone(), ((DateFormat) subFormat).getTimeZone()); } } } /** * Issue #554-swingx: timezone of formats and picker must be synched. * Here: set the timezone in the monthView. */ @Test public void testSynchTimeZoneModifiedInMonthView() { JXDatePicker picker = new JXDatePicker(); TimeZone defaultZone = picker.getTimeZone(); TimeZone alternative = getSafeAlternativeTimeZone(defaultZone); picker.getMonthView().setTimeZone(alternative); assertTimeZoneDateFormats(picker, alternative); } /** * Issue #554-swingx: timezone of formats and picker must be synched. * * Here: set the timezone in the picker. */ @Test public void testSynchTimeZoneModifiedInPicker() { JXDatePicker picker = new JXDatePicker(); TimeZone defaultZone = picker.getTimeZone(); TimeZone alternative = getSafeAlternativeTimeZone(defaultZone); picker.setTimeZone(alternative); assertTimeZoneDateFormats(picker, alternative); } /** * Issue #554-swingx: timezone of formats and picker must be synched. * Here: set the timezone in the picker. */ @Test public void testSynchTimeZoneOnSetMonthView() { JXDatePicker picker = new JXDatePicker(); TimeZone defaultZone = picker.getTimeZone(); TimeZone alternative = getSafeAlternativeTimeZone(defaultZone); JXMonthView monthView = new JXMonthView(); monthView.setTimeZone(alternative); picker.setMonthView(monthView); assertTimeZoneDateFormats(picker, alternative); } /** * Issue #554-swingx: timezone of formats and picker must be synched. * * Here: initialize the formats with the pickers timezone on setting. */ @Test public void testSynchTimeZoneOnSetFormats() { JXDatePicker picker = new JXDatePicker(); TimeZone defaultZone = picker.getTimeZone(); TimeZone alternative = getSafeAlternativeTimeZone(defaultZone); picker.setTimeZone(alternative); picker.setFormats(DateFormat.getDateInstance()); assertTimeZoneDateFormats(picker, alternative); } /** * Assert that all DateFormats in the picker's linkFormat have the same * timezone as the picker. * * @param picker the JXDatePicker to test * @param alternative the expected timeZone of the picker (for sanity only) */ private void assertTimeZoneDateFormats(JXDatePicker picker, TimeZone alternative) { assertEquals(alternative, picker.getTimeZone()); for (DateFormat format : picker.getFormats()) { assertEquals("timezone must be synched", picker.getTimeZone(), format.getTimeZone()); } } /** * Issue #554-swingx: timezone of formats and picker must be synched. */ @Test public void testSynchTimeZoneInitial() { JXDatePicker picker = new JXDatePicker(); assertNotNull(picker.getTimeZone()); for (DateFormat format : picker.getFormats()) { assertEquals("timezone must be synched", picker.getTimeZone(), format.getTimeZone()); } } /** * setFormats should fire a propertyChange. * */ @Test public void testFormatsProperty() { JXDatePicker picker = new JXDatePicker(); PropertyChangeReport report = new PropertyChangeReport(); picker.addPropertyChangeListener(report); DateFormat[] oldFormats = picker.getFormats(); DateFormat[] newFormats = new DateFormat[] {DateFormat.getDateInstance()}; picker.setFormats(newFormats); TestUtils.assertPropertyChangeEvent(report, "formats", oldFormats, newFormats); } /** * Test doc'ed behaviour: editor must not be null. */ @Test public void testEditorNull() { JXDatePicker picker = new JXDatePicker(); assertNotNull(picker.getEditor()); try { picker.setEditor(null); fail("picker must throw NPE if editor is null"); } catch (NullPointerException e) { // nothing to do - doc'ed behaviour } } /** * Test doc'ed behaviour: editor must not be null. */ @Test public void testMonthViewNull() { JXDatePicker picker = new JXDatePicker(); assertNotNull(picker.getMonthView()); try { picker.setMonthView(null); fail("picker must throw NPE if monthView is null"); } catch (NullPointerException e) { // nothing to do - doc'ed behaviour } } /** * picker has cleaned date, clarified doc. * The test is not exactly true, the details * are up for the DatePickerUI to decide. * */ @Test public void testSetDateCleansDate() { JXDatePicker picker = new JXDatePicker(); Date date = calendar.getTime(); picker.setDate(date); assertEquals(CalendarUtils.startOfDay(calendar, date), picker.getDate()); } /** * Regression testing: make sure the passed-in date is not changed. * */ @Test public void testSetDateDoesNotChangeOriginal() { JXDatePicker picker = new JXDatePicker(); Date date = calendar.getTime(); Date copy = new Date(date.getTime()); picker.setDate(date); assertEquals(copy, date); } /** * date is a bound property of DatePicker. */ @Test public void testDateProperty() { JXDatePicker picker = new JXDatePicker(); Date date = XTestUtils.getStartOfToday(5); PropertyChangeReport report = new PropertyChangeReport(); picker.addPropertyChangeListener("date", report); picker.setDate(date); TestUtils.assertPropertyChangeEvent(report, "date", null, date); } /** * date is a bound property of DatePicker. * test indirect event firing: changed editor value */ @Test public void testDatePropertyThroughEditor() { JXDatePicker picker = new JXDatePicker(); Date date = XTestUtils.getStartOfToday(5); PropertyChangeReport report = new PropertyChangeReport(); picker.addPropertyChangeListener("date", report); picker.getEditor().setValue(date); TestUtils.assertPropertyChangeEvent(report, "date", null, date); } /** * date is a bound property of DatePicker. * test indirect event firing: changed monthView selection */ @Test public void testDatePropertyThroughSelection() { JXDatePicker picker = new JXDatePicker(); Date date = XTestUtils.getStartOfToday(5); PropertyChangeReport report = new PropertyChangeReport(); picker.addPropertyChangeListener("date", report); picker.getMonthView().setSelectionInterval(date, date); TestUtils.assertPropertyChangeEvent(report, "date", null, date); } /** * date is a bound property of DatePicker. * test indirect event firing: commit edited value * @throws ParseException * */ @Test public void testDatePropertyThroughCommit() throws ParseException { JXDatePicker picker = new JXDatePicker(new Date()); Date initialDate = picker.getDate(); String text = picker.getEditor().getText(); Format[] formats = picker.getFormats(); assertEquals(picker.getDate(), formats[0].parseObject(text)); // manipulate the text, not entirely safe ... String changed = text.replace('0', '1'); picker.getEditor().setText(changed); Date date; try { date = (Date) formats[0].parseObject(changed); } catch (ParseException e) { LOG.info("cannot run DatePropertyThroughCommit - parseException in manipulated text"); return; } // sanity ... assertFalse("", date.equals(picker.getDate())); PropertyChangeReport report = new PropertyChangeReport(); picker.addPropertyChangeListener("date", report); picker.commitEdit(); TestUtils.assertPropertyChangeEvent(report, "date", initialDate, date); } /** * last piece: removed synch control from picker.commit. * @throws ParseException * */ @Test public void testSynchAllAfterCommit() throws ParseException { JXDatePicker picker = new JXDatePicker(new Date()); String text = picker.getEditor().getText(); Format[] formats = picker.getFormats(); assertEquals(picker.getDate(), formats[0].parseObject(text)); // manipulate the text, not entirely safe ... String changed = text.replace('0', '1'); picker.getEditor().setText(changed); Date date; try { date = (Date) formats[0].parseObject(changed); } catch (ParseException e) { LOG.info("cannot run testSynchAllAfterCommit - parseException in manipulated text"); return; } // sanity ... assertFalse("", date.equals(picker.getDate())); picker.commitEdit(); assertSynchAll(picker, date); } /** * Issue #559-swingX: date must be synched in all parts. * here: initial. * */ @Test public void testSynchAllInitialDate() { Date date = XTestUtils.getStartOfToday(5); JXDatePicker picker = new JXDatePicker(date); assertSynchAll(picker, date); } /** * Issue #559-swingX: date must be synched in all parts. * here: set date in picker * * Note: test uses a cleaned date, do same with uncleaned. */ @Test public void testSynchAllOnDateModified() { JXDatePicker picker = new JXDatePicker(); Date date = XTestUtils.getStartOfToday(5); picker.setDate(date); assertSynchAll(picker, date); } /** * Issue #559-swingX: date must be synched in all parts. * here: set selected date in monthview * Note: test uses a cleaned date, do same with uncleaned. */ @Test public void testSynchAllOnSelectionChange() { JXDatePicker picker = new JXDatePicker(); Date date = XTestUtils.getStartOfToday(5); picker.getMonthView().setSelectionInterval(date, date); assertSynchAll(picker, date); } /** * Issue #559-swingX: date must be synched in all parts. * here: set value in editor. * * Note: test uses a cleaned date, do same with uncleaned. */ @Test public void testSynchAllOnEditorSetValue() { JXDatePicker picker = new JXDatePicker(); Date date = XTestUtils.getStartOfToday(5); picker.getEditor().setValue(date); assertSynchAll(picker, date); } /** * Issue #559-swingX: date must be synched in all parts. * here: modify value must work after changing the editor. * * Note: this started to fail during listener cleanup. */ @Test public void testSynchAllOnEditorSetValueAfterSetEditor() { JXDatePicker picker = new JXDatePicker(); picker.setEditor(new JFormattedTextField(DateFormat.getInstance())); Date date = XTestUtils.getStartOfToday(5); picker.getEditor().setValue(date); assertSynchAll(picker, date); } /** * Issue #559-swingX: date must be synched in all parts. * here: set selection must work after changing the monthView. * * Note: this started to fail during listener cleanup. */ @Test public void testSynchAllOnSelectionChangeAfterSetMonthView() { JXDatePicker picker = new JXDatePicker(); picker.setMonthView(new JXMonthView()); Date date = XTestUtils.getStartOfToday(5); picker.getMonthView().setSelectionInterval(date, date); assertSynchAll(picker, date); } /** * Issue #559-swingX: date must be synched in all parts. *

* * here: set selection must work after changing the monthView's selection * model. * * Note: this started to fail during listener cleanup. */ @Test public void testSynchAllOnSelectionChangeAfterSetSelectionModel() { JXDatePicker picker = new JXDatePicker(); picker.getMonthView().setSelectionModel(new DefaultDateSelectionModel()); Date date = XTestUtils.getStartOfToday(5); picker.getMonthView().setSelectionInterval(date, date); assertSynchAll(picker, date); } /** * Asserts that all date related values in the picker are synched. * * @param picker the picker to * @param date the common date */ private void assertSynchAll(JXDatePicker picker, Date date) { assertEquals(date, picker.getEditor().getValue()); assertEquals(date, picker.getDate()); assertEquals(date, picker.getMonthView().getSelectionDate()); // @KEEP JW - currently unused, not yet sure if it's the right place // for checking against ripples produced by fixing #705-swingx Calendar cal = picker.getMonthView().getCalendar(); if (date == null) { cal.setTime(picker.getLinkDay()); CalendarUtils.startOfMonth(cal); } else { cal.setTime(date); CalendarUtils.startOfMonth(cal); } assertEquals(cal.getTime(), picker.getMonthView().getFirstDisplayedDay()); } /** * test that input of unselectable dates reverts editors value. */ @Test public void testRejectSetValueUnselectable() { JXDatePicker picker = new JXDatePicker(); Date upperBound = XTestUtils.getStartOfToday(1); picker.getMonthView().setUpperBound(upperBound); Date future = XTestUtils.getStartOfToday(2); // sanity assertTrue(picker.getMonthView().isUnselectableDate(future)); Date current = picker.getDate(); // sanity: assertEquals(current, picker.getEditor().getValue()); // set the editors value to something invalid picker.getEditor().setValue(future); // ui must not allow an invalid value in the editor assertEquals(current, picker.getEditor().getValue()); // okay .. assertEquals(current, picker.getDate()); } /** * PickerUI listened to editable (meant: datePicker) and resets * the editors property. Accidentally? Even if meant to, it's * brittle because done during the notification. * Changed to use dedicated listener. */ @Test public void testSpuriousEditableListening() { JXDatePicker picker = new JXDatePicker(); picker.getEditor().setEditable(false); // sanity - that at least the other views are uneffected assertTrue(picker.isEditable()); assertTrue(picker.getMonthView().isEnabled()); assertFalse("Do not change the state of the sender during notification processing", picker.getEditor().isEditable()); } /** * PickerUI listened to enabled of button (meant: datePicker) and resets * the buttons property. */ @Test public void testSpuriousEnabledListening() { JXDatePicker picker = new JXDatePicker(); Component button = null; for (int i = 0; i < picker.getComponentCount(); i++) { if (picker.getComponent(i) instanceof JButton) { button = picker.getComponent(i); } } if (button == null) { LOG.info("cannot run testEnabledListening - no button found"); return; } button.setEnabled(false); // sanity - that at least the other views are uneffected assertTrue(picker.isEnabled()); assertTrue(picker.getEditor().isEnabled()); assertFalse("Do not change the state of the sender during notification processing", button.isEnabled()); } /** * Sanity during revision: be sure we don't loose the * ui listening to picker property changes. * */ @Test public void testDatePickerPropertyListening() { JXDatePicker picker = new JXDatePicker(); picker.setEnabled(false); assertFalse(picker.getEditor().isEnabled()); picker.setEditable(false); assertFalse(picker.getEditor().isEditable()); picker.setToolTipText("dummy"); assertEquals("dummy", picker.getEditor().getToolTipText()); } /** * Issue ??-swingx: uninstallUI does not release propertyChangeListener * to editor. Reason is that the de-install was not done in * uninstallListeners but later in uninstallComponents - at that time * the handler is already nulled, removing will actually create a new one. */ @Test public void testEditorListeners() { JFormattedTextField field = new JFormattedTextField(DateFormat.getInstance()); JXDatePicker picker = new JXDatePicker(); int defaultListenerCount = field.getPropertyChangeListeners().length; // sanity: we added one listener ... assertEquals(defaultListenerCount + 1, picker.getEditor().getPropertyChangeListeners().length); picker.getUI().uninstallUI(picker); assertEquals("the ui installe listener must be removed", defaultListenerCount, // right now we can access the editor even after uninstall // because the picker keeps a reference // TODO: after cleanup, this will be done through the ui picker.getEditor().getPropertyChangeListeners().length); } /** * Issue #551-swingX: editor value not updated after setMonthView. * * quick&dirty fix: let the picker manually update. * */ @Test public void testEditorValueOnSetMonthView() { JXDatePicker picker = new JXDatePicker(new Date()); // set unselected monthView picker.setMonthView(new JXMonthView()); // sanity: picker takes it assertNull(picker.getDate()); assertEquals(picker.getDate(), picker.getEditor().getValue()); } /** * Issue #551-swingx: editor value not updated after setEditor. * * quick&dirty fix: let the picker manually update. * * who should set it? ui-delegate when listening to editor property change? * or picker in setEditor? * * Compare to JComboBox: BasicComboUI listens to editor change, does internal * wiring to editor and call's comboBox configureEditor with the value of the * old editor. * * */ @Test public void testEditorValueOnSetEditor() { JXDatePicker picker = new JXDatePicker(); Object value = picker.getEditor().getValue(); picker.setEditor(new JFormattedTextField(new DatePickerFormatter())); assertEquals(value, picker.getEditor().getValue()); } /** * Issue #551-swingx: editor value must preserve value on LF switch. * * This is a side-effect of picker not updating the editor's value * on setEditor. * * @see #testEditorValueOnSetEditor */ @Test public void testEditorUpdateOnLF() { JXDatePicker picker = new JXDatePicker(); Object date = picker.getEditor().getValue(); picker.updateUI(); assertEquals(date, picker.getEditor().getValue()); } @Test public void testEditorUIResource() { JXDatePicker picker = new JXDatePicker(); // this is safe: ui must install an editor and it must be of type UIResource assertEquals("default editor is UIResource ", true, picker.getEditor() instanceof UIResource); JFormattedTextField editor = new JFormattedTextField(); picker.setEditor(editor); assertEquals("sanity: custom editor not UIResource ", false, picker.getEditor() instanceof UIResource); picker.updateUI(); assertSame("updateUI must not touch custom editor", editor, picker.getEditor()); } /** * Characterization: setting the monthview's selection model updates * the datePicker's date to the monthView's current * selection. * * Here: model with selection. * */ @Test public void testSynchAllAfterSetSelectionModelNotEmpty() { JXDatePicker picker = new JXDatePicker(); Date date = XTestUtils.getStartOfToday(5); DateSelectionModel model = new DefaultDateSelectionModel(); model.setSelectionInterval(date, date); // sanity assertFalse(date.equals(picker.getDate())); picker.getMonthView().setSelectionModel(model); assertSynchAll(picker, date); } /** * Characterization: setting the monthview's selection model updates * the datePicker's date to the monthView's current * selection. * * Here: model with empty selection. * */ @Test public void testSynchAllAfterSetSelectionModelEmpty() { JXDatePicker picker = new JXDatePicker(new Date()); assertNotNull(picker.getDate()); DateSelectionModel model = new DefaultDateSelectionModel(); assertTrue(model.isSelectionEmpty()); picker.getMonthView().setSelectionModel(model); assertSynchAll(picker, null); } /** * Characterization: setting the monthview updates * the datePicker's date to the monthView's current * selection. * Here: monthview with selection. * */ @Test public void testSynchAllSetMonthViewWithSelection() { JXDatePicker picker = new JXDatePicker(); JXMonthView monthView = new JXMonthView(); Date date = XTestUtils.getStartOfToday(5); monthView.setSelectionInterval(date, date); // sanity assertFalse(date.equals(picker.getDate())); picker.setMonthView(monthView); assertSynchAll(picker, date); } /** * Characterization: setting the monthview updates * the datePicker's date to the monthView's current * selection. * Here: monthview with empty selection. * */ @Test public void testSynchAllSetMonthViewWithEmptySelection() { JXDatePicker picker = new JXDatePicker(new Date()); // sanity assertNotNull(picker.getDate()); JXMonthView monthView = new JXMonthView(); Date selectedDate = monthView.getSelectionDate(); assertNull(selectedDate); picker.setMonthView(monthView); assertSynchAll(picker, selectedDate); } /** * PrefSize should be independent of empty/filled picker. * If not, the initial size might appear kind of collapsed. * */ @Test public void testPrefSizeEmptyEditor() { JXDatePicker picker = new JXDatePicker(new Date()); // sanity assertNotNull(picker.getDate()); Dimension filled = picker.getPreferredSize(); picker.setDate(null); Dimension empty = picker.getPreferredSize(); assertEquals("pref width must be same for empty/filled", filled.width, empty.width); } @Test public void testDefaultConstructor() { JXDatePicker datePicker = new JXDatePicker(); assertNull(datePicker.getDate()); } @Test public void testConstructor() { calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.DAY_OF_MONTH, 5); Date expectedDate = cleanupDate(calendar); JXDatePicker datePicker = new JXDatePicker(calendar.getTime()); assertTrue(expectedDate.equals(datePicker.getDate())); } @Test public void testNullSelection() { JXDatePicker datePicker = new JXDatePicker(); assertTrue(null == datePicker.getDate()); } @Test public void testSetDate() { calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.DAY_OF_MONTH, 5); Date expectedDate = cleanupDate(calendar); JXDatePicker datePicker = new JXDatePicker(); datePicker.setDate(calendar.getTime()); assertTrue(expectedDate.equals(datePicker.getDate())); assertTrue(expectedDate.equals(datePicker.getEditor().getValue())); datePicker.setDate(null); assertTrue(null == datePicker.getDate()); assertTrue(null == datePicker.getEditor().getValue()); } //------------------ test helpers /** * Returns a timezone different from the given. * @param defaultZone * @return */ private TimeZone getSafeAlternativeTimeZone(TimeZone defaultZone) { TimeZone alternative = TimeZone.getTimeZone("GMT-6"); // sanity assertNotNull(alternative); if (alternative.equals(defaultZone)) { alternative = TimeZone.getTimeZone("GMT-7"); // paranoid ... but shit happens assertNotNull(alternative); assertFalse(alternative.equals(defaultZone)); } return alternative; } private Date cleanupDate(Calendar cal) { cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } }swingx-1.0-src/src/test/org/jdesktop/swingx/SandboxTest.java0000644000175000017500000000642611210401722023020 0ustar tonytony/* * Created on 31.07.2006 * */ package org.jdesktop.swingx; import java.util.logging.Logger; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import junit.framework.TestCase; /** * "hand test" sandbox restrictions * (here: around Utilities.initNamesAndValue, #353-swingx). * * JW: Need to investigate further. Running the test via the * build test-target lets this TestCase fail. Eclipse only? * Setting the securityManager has side-effects on the TestRunner. * * */ @RunWith(JUnit4.class) public class SandboxTest extends TestCase { private static final Logger LOG = Logger.getLogger(SandboxTest.class .getName()); /** * quick test if table doesn't throw securityExceptions. * * */ @Test public void testSecurityManager() { if (System.getSecurityManager() == null) { LOG.info("cannot run testSecurityManager - no SecurityManager installed"); return; } JXTable table = new JXTable(); try { System.getProperty("user.home", "not specified"); fail("Sandbox without security priviledges"); } catch (SecurityException e) { // nothing to do - that's what we expect } } /** * Sanity: make sure the second-time-around is reached! * */ @Test public void testSecurityManagerAgain() { if (System.getSecurityManager() == null) { LOG.info("cannot run testSecurityManagerAgain - no SecurityManager installed"); return; } try { System.getProperty("user.home", "not specified"); fail("Sandbox without security priviledges"); } catch (SecurityException e) { // nothing to do - that's what we expect } } @Override protected void setUp() throws Exception { super.setUp(); // A - install the default SecurityManager. // Doing so we are not allowed to reverse the install - // which makes this testCase to a manual-run-only affair // (the securityManager is not uninstalled when running // other test cases - in Eclipse, when running the // bulk "all tests" of a projects. // if (System.getSecurityManager() == null) { // System.setSecurityManager(new SecurityManager()); // } // B- if we install a SecurityManager we need to be sure // that we are allowed to uninstall it. // BUT: with this custom manager on, JXTable instantiation // fails with a rather weird stack-trace. Gave up for now... // if (System.getSecurityManager() == null) { // System.setSecurityManager(new SecurityManager() { // // @Override // public void checkPermission(Permission perm) { // if ("setSecurityManager".equals(perm.getName())) return; // super.checkPermission(perm); // } // // }); // } } @Override protected void tearDown() throws Exception { super.tearDown(); // be sure to uninstall the manager // System.setSecurityManager(null); } } swingx-1.0-src/src/test/org/jdesktop/swingx/FindIssues.java0000644000175000017500000000576311210401722022641 0ustar tonytony/* * $Id: FindIssues.java,v 1.22 2009/01/16 14:26:56 kleopatra Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx; import java.util.TreeMap; import javax.swing.AbstractListModel; import org.jdesktop.swingx.search.FindTest; import org.jdesktop.swingx.search.PatternModel; import org.jdesktop.swingx.search.Searchable; /** * Exposing open issues in Searchable implementations. * PENDING JW: should be in package search - but references swingx package internals. * * @author Jeanette Winzenburg */ public class FindIssues extends FindTest { public static void main(String args[]) { setSystemLF(true); // Locale.setDefault(new Locale("es")); FindIssues test = new FindIssues(); try { // test.runInteractiveTests(); test.runInteractiveTests("interactive.*Mark.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #487-swingx: NPE if setting a not-null Searchable before * showing. Hack around ... */ public void testFindBarNPEComponents() { TreeMap map; Searchable searchable = new JXTable().getSearchable(); JXFindBar findBar = new JXFindBar(); // old hack // findBar.addNotify(); findBar.setSearchable(searchable); fail("quick hack ... remove me if really fixed"); } /** * Issue #236-swingx: backwards match in first row shows not-found-message. * Trackdown from Nicfagn - findPanel.doSearch always returns the next startIndex * in backwards search that's -1 which is interpreted as "not-found" * */ public void testFindPanelFirstRowBackwards() { JXList list = new JXList( new AbstractListModel() { private String[] data = { "a", "b", "c" }; public Object getElementAt(int index) { return data[ index ]; } public int getSize() { return data.length; } }); JXFindPanel findPanel = new JXFindPanel(list.getSearchable()); findPanel.init(); PatternModel patternModel = findPanel.getPatternModel(); patternModel.setBackwards(true); patternModel.setRawText("a"); int matchIndex = list.getSearchable().search(patternModel.getPattern(), patternModel.getFoundIndex(), patternModel.isBackwards()); assertEquals("found match", matchIndex, findPanel.doSearch()); } // -------------------- interactive tests /** * #463-swingx: batch find and cellSelection don't play nicely. * */ public void interactiveTableBatchWithCellSelectionIssue() { JXTable table = new JXTable(new TestTableModel()); table.setCellSelectionEnabled(true); showWithScrollingInFrame(table, "batch find with cell selection"); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXBusyLabelVisualCheck.java0000644000175000017500000001173311210401722025025 0ustar tonytony/* * $Id: JXBusyLabelVisualCheck.java,v 1.3 2008/03/03 17:23:29 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.List; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; import org.jdesktop.swingx.JXHeader; /** * Visual tests of JXBusyLabel issues. * @author had * */ public class JXBusyLabelVisualCheck extends InteractiveTestCase { private static JDialog createDialog(JFrame owner) { JDialog d = new JDialog(owner, "Dialog"); d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); JXBusyLabel bl = new JXBusyLabel(); d.add(bl); bl.setBusy(true); d.setVisible(true); return d; } /** * Test for issue #795 - size is set to 0 using default const. */ public void interactiveNoArgConst() { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); final JXBusyLabel label = new JXBusyLabel(); label.setText("hi there"); f.add(label); f.add(new JButton(new AbstractAction("click me") { public void actionPerformed(ActionEvent e) { label.setBusy(!label.isBusy()); } }), BorderLayout.SOUTH); f.pack(); f.setVisible(true); } /** * Test for memory leak issue #626. */ public void interactiveMemoryLeak() { final JFrame f = new JFrame(); JXHeader header = new JXHeader(); header.setTitle("JXBusyLabelIssue #626"); header.setDescription("Memory leak test. By clicking 'start' button, creation of 100 " + "new dialogs will be triggered. Similarly 'Stop' button will then destroy all " + "created dialogs. It should be possible to see memory consumption on the " + "System.out as well as change in speed of busy label rotation when all dialogs " + "are created/destroyed."); f.add(header, BorderLayout.NORTH); JXBusyLabel bl = new JXBusyLabel(); f.add(bl); bl.setBusy(true); final List l = new ArrayList(); JPanel control = new JPanel(); JButton b = new JButton(new AbstractAction("Start") { public void actionPerformed(ActionEvent e) { System.gc(); System.out.println("Start mem(u):" + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); // just reset the model for (int i = 0; i < 100; i++) { l.add(createDialog(f)); } System.gc(); System.out.println("alloc mem(u):" + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); } }); control.add(b); b = new JButton(new AbstractAction("Stop") { public void actionPerformed(ActionEvent e) { // just reset the model for (int i = 0; i < 100; i++) { if (l.size() > 0) { JDialog d = l.remove(0); d.dispose(); } } System.gc(); System.out.println("Stop mem(u):" + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); } }); control.add(b); f.add(control, BorderLayout.SOUTH); f.setPreferredSize(new Dimension(400, 400)); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.pack(); f.setVisible(true); } /** * @param args */ public static void main(String[] args) { JXBusyLabelVisualCheck test = new JXBusyLabelVisualCheck(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * do nothing test - keep the testrunner happy. */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/plaf/0000755000175000017500000000000011210401736020636 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/plaf/DefaultsListTest.java0000644000175000017500000000346011210401724024744 0ustar tonytony/* * $Id: DefaultsListTest.java,v 1.2 2008/10/11 20:42:32 rah003 Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.plaf; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; import junit.framework.TestCase; /** * This test ensures that all values that should be {@code UIResouce}s are. * * @author Karl George Schaefer */ @RunWith(JUnit4.class) public class DefaultsListTest extends TestCase { /** * Ensure that "adding" a key with a {@code null} value removes the value * from the list. */ @Test public void testRemoval() { DefaultsList kvList = new DefaultsList(); kvList.add("a", "b"); Object[] arr = kvList.toArray(); assertEquals(2, arr.length); assertEquals("a", arr[0]); assertEquals("b", arr[1]); kvList.add("a", null); assertEquals(0, kvList.toArray().length); } } swingx-1.0-src/src/test/org/jdesktop/swingx/plaf/LookAndFeelAddonsTest.java0000644000175000017500000002033611210401722025614 0ustar tonytony/* * $Id: LookAndFeelAddonsTest.java,v 1.8 2008/12/05 21:40:37 kschaefe Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.plaf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.awt.Color; import javax.swing.JPanel; import javax.swing.LookAndFeel; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import javax.swing.plaf.BorderUIResource; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.basic.BasicLookAndFeel; import org.jdesktop.swingx.JXMonthView; import org.jdesktop.swingx.JXPanel; import org.jdesktop.swingx.painter.MattePainter; import org.jdesktop.swingx.painter.Painter; import org.jdesktop.swingx.plaf.basic.BasicLookAndFeelAddons; import org.jdesktop.test.EDTRunner; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(EDTRunner.class) public class LookAndFeelAddonsTest { /** * Ensure that an exception is thrown when a component is passed in that does * not contain get/setBackgroundPainter. */ @Test(expected = IllegalArgumentException.class) public void testInstallBackgroundPainterWithoutPainterCapable() { LookAndFeelAddons.installBackgroundPainter(new JPanel(), null); } /** * Ensure that an exception is thrown when a {@code null} key is passed in. */ @Test(expected = NullPointerException.class) public void testInstallBackgroundPainterWithNullComponent() { LookAndFeelAddons.installBackgroundPainter(null, "test.painter"); } /** * Ensure that an exception is thrown when a {@code null} key is passed in. */ @Test(expected = NullPointerException.class) public void testInstallBackgroundPainterWithNullPainterKey() { LookAndFeelAddons.installBackgroundPainter(new JXPanel(), null); } /** * Ensure that installBackgroundPainter does not overwrite a user-specified * painter. */ @Test @SuppressWarnings("unchecked") public void testInstallBackgroundPainter() { Painter plafPainter = new PainterUIResource(null); UIManager.put("test.painter", plafPainter); JXPanel panel = new JXPanel(); //overwrite null painter LookAndFeelAddons.installBackgroundPainter(panel, "test.painter"); assertThat(panel.getBackgroundPainter(), is(sameInstance(plafPainter))); panel.setBackgroundPainter(new PainterUIResource(null)); //overwrite uiresource painter LookAndFeelAddons.installBackgroundPainter(panel, "test.painter"); assertThat(panel.getBackgroundPainter(), is(sameInstance(plafPainter))); Painter userPainter = new MattePainter(); panel.setBackgroundPainter(userPainter); //do not overwrite user painter LookAndFeelAddons.installBackgroundPainter(panel, "test.painter"); assertThat(panel.getBackgroundPainter(), is(sameInstance(userPainter))); } /** * Issue #784-swingx: Frequent NPE in getUI of (new) SwingX components. * * Here: test reload if same instance of LAF is set (example from * bug report) * @throws UnsupportedLookAndFeelException */ @Test public void testReloadAddons() throws UnsupportedLookAndFeelException { // load the addon for a new component new JXMonthView(); // reset laf UIManager.setLookAndFeel(UIManager.getLookAndFeel()); // check that the addon is still available new JXMonthView(); } /** * A look and feel can't override SwingX defaults */ @Test public void testIssue293() throws Exception { class CustomLF extends BasicLookAndFeel { @Override public String getDescription() { return "custom"; } @Override public String getID() { return "custom"; } @Override public String getName() { return "custom"; } @Override public boolean isNativeLookAndFeel() { return false; } @Override public boolean isSupportedLookAndFeel() { return true; } @Override protected void initComponentDefaults(UIDefaults table) { super.initComponentDefaults(table); table.put("CustomProperty", "CustomValue"); } }; LookAndFeelAddons.setTrackingLookAndFeelChanges(true); // without addons, the prop is not overriden LookAndFeel lf = new CustomLF(); UIManager.setLookAndFeel(lf); assertEquals("CustomValue", UIManager.get("CustomProperty")); // with an addon, the prop is overriden ComponentAddon myAddon = new AbstractComponentAddon("myAddon") { @Override protected void addBasicDefaults(LookAndFeelAddons addon, DefaultsList defaults) { defaults.add("CustomProperty", "customAddonValue"); defaults.add("AddonProperty", "addonValue"); } }; LookAndFeelAddons.contribute(myAddon); // the addon property was not registered as overriden by the l&f assertEquals("CustomValue", UIManager.get("CustomProperty")); assertEquals("addonValue", UIManager.get("AddonProperty")); // now revert to a standard look and feel UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); // now the addon properties are used assertEquals("customAddonValue", UIManager.get("CustomProperty")); assertEquals("addonValue", UIManager.get("AddonProperty")); } /** * LookAndFeelAddons override entries manually added to UIManager */ @Test public void testIssue144() throws Exception { UIManager.put("Addon.title", "customized"); UIManager.put("Addon.border", new LineBorder(Color.blue)); Addon addon = new Addon(); LookAndFeelAddons.contribute(addon); assertEquals("customized", UIManager.get("Addon.title")); assertEquals("my subtitle", UIManager.get("Addon.subtitle")); assertTrue(UIManager.get("Addon.border") instanceof LineBorder); UIManager.put("Addon.title", null); assertEquals("my title", UIManager.get("Addon.title")); } @Test public void testContribute() throws Exception { Addon addon = new Addon(); LookAndFeelAddons.contribute(addon); // a ComponentAddon is initialized when it is contributed assertTrue(addon.initialized); // and uninitialized when "uncontributed" LookAndFeelAddons.uncontribute(addon); assertTrue(addon.uninitialized); // re-contribute the ComponentAddon LookAndFeelAddons.contribute(addon); // reset its state addon.initialized = false; addon.uninitialized = false; // when addon is changed, the ComponentAddon is uninitialized with the // previous addon, then initialized with the new LookAndFeelAddons oldLFAddon = LookAndFeelAddons.getAddon(); LookAndFeelAddons.setAddon(BasicLookAndFeelAddons.class); LookAndFeelAddons newLFAddon = LookAndFeelAddons.getAddon(); assertTrue(addon.uninitialized); assertEquals(oldLFAddon, addon.uninitializedWith); assertTrue(addon.initialized); assertEquals(newLFAddon, addon.initializedWith); } static class Addon extends AbstractComponentAddon { boolean initialized; LookAndFeelAddons initializedWith; boolean uninitialized; LookAndFeelAddons uninitializedWith; public Addon() { super("Addon"); } @Override public void initialize(LookAndFeelAddons addon) { initialized = true; initializedWith = addon; addon.loadDefaults(getDefaults()); } @Override public void uninitialize(LookAndFeelAddons addon) { uninitialized = true; uninitializedWith = addon; addon.unloadDefaults(getDefaults()); } protected Object[] getDefaults() { return new Object[] { "Addon.title", "my title", "Addon.subtitle", "my subtitle", "Addon.border", new BorderUIResource(new EmptyBorder(0, 0, 0, 0)), "Addon.color", new ColorUIResource(Color.blue)}; } } } swingx-1.0-src/src/test/org/jdesktop/swingx/plaf/UIResourcesTest.java0000644000175000017500000001342711210401722024553 0ustar tonytony/* * $Id: UIResourcesTest.java,v 1.6 2008/10/11 20:42:32 rah003 Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.plaf; import java.util.logging.Logger; import junit.framework.TestCase; import org.jdesktop.swingx.plaf.basic.BasicLookAndFeelAddons; import org.jdesktop.swingx.plaf.linux.LinuxLookAndFeelAddons; import org.jdesktop.swingx.plaf.macosx.MacOSXLookAndFeelAddons; import org.jdesktop.swingx.plaf.metal.MetalLookAndFeelAddons; import org.jdesktop.swingx.plaf.motif.MotifLookAndFeelAddons; import org.jdesktop.swingx.plaf.nimbus.NimbusLookAndFeelAddons; import org.jdesktop.swingx.plaf.windows.WindowsClassicLookAndFeelAddons; import org.jdesktop.swingx.plaf.windows.WindowsLookAndFeelAddons; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * This test ensures that all values that should be {@code UIResouce}s are. * * @author Karl George Schaefer */ @RunWith(JUnit4.class) public class UIResourcesTest extends TestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger.getLogger(UIResourcesTest.class .getName()); /** * {@inheritDoc} */ protected void setUp() { System.setProperty("swingx.enableStrictResourceChecking", "true"); LookAndFeelAddons.contribute(new BusyLabelAddon()); LookAndFeelAddons.contribute(new ColumnControlButtonAddon()); LookAndFeelAddons.contribute(new ColumnHeaderRendererAddon()); LookAndFeelAddons.contribute(new DatePickerAddon()); LookAndFeelAddons.contribute(new ErrorPaneAddon()); LookAndFeelAddons.contribute(new HeaderAddon()); LookAndFeelAddons.contribute(new HyperlinkAddon()); LookAndFeelAddons.contribute(new LoginPaneAddon()); LookAndFeelAddons.contribute(new MonthViewAddon()); LookAndFeelAddons.contribute(new MultiThumbSliderAddon()); LookAndFeelAddons.contribute(new StatusBarAddon()); LookAndFeelAddons.contribute(new TaskPaneAddon()); LookAndFeelAddons.contribute(new TaskPaneContainerAddon()); LookAndFeelAddons.contribute(new TipOfTheDayAddon()); LookAndFeelAddons.contribute(new TitledPanelAddon()); LookAndFeelAddons.contribute(new UIColorHighlighterAddon()); } /** * Ensures that all basic values are {@code UIResource}s where appropriate. * * @throws Exception * if an error occurs */ @Test public void testBasicLookAndFeelAddonsForUIResources() throws Exception { LookAndFeelAddons.setAddon(BasicLookAndFeelAddons.class); } /** * Ensures that all linux values are {@code UIResource}s where appropriate. * * @throws Exception * if an error occurs */ @Test public void testLinuxLookAndFeelAddonsForUIResources() throws Exception { LookAndFeelAddons.setAddon(LinuxLookAndFeelAddons.class); } /** * Ensures that all Mac OSX values are {@code UIResource}s where appropriate. * * @throws Exception * if an error occurs */ @Test public void testMacOSXLookAndFeelAddonsForUIResources() throws Exception { LookAndFeelAddons.setAddon(MacOSXLookAndFeelAddons.class); } /** * Ensures that all metal values are {@code UIResource}s where appropriate. * * @throws Exception * if an error occurs */ @Test public void testMetalLookAndFeelAddonsForUIResources() throws Exception { LookAndFeelAddons.setAddon(MetalLookAndFeelAddons.class); } /** * Ensures that all Motif values are {@code UIResource}s where appropriate. * * @throws Exception * if an error occurs */ @Test public void testMotifLookAndFeelAddonsForUIResources() throws Exception { LookAndFeelAddons.setAddon(MotifLookAndFeelAddons.class); } /** * Ensures that all Nimbus values are {@code UIResource}s where appropriate. * * @throws Exception * if an error occurs */ @Test public void testNimbusLookAndFeelAddonsForUIResources() throws Exception { LookAndFeelAddons.setAddon(NimbusLookAndFeelAddons.class); } /** * Ensures that all Windows values are {@code UIResource}s where appropriate. * * @throws Exception * if an error occurs */ @Test public void testWindowsLookAndFeelAddonsForUIResources() throws Exception { LookAndFeelAddons.setAddon(WindowsLookAndFeelAddons.class); } /** * Ensures that all Windows classic values are {@code UIResource}s where appropriate. * * @throws Exception * if an error occurs */ @Test public void testWindowsClassicLookAndFeelAddonsForUIResources() throws Exception { LookAndFeelAddons.setAddon(WindowsClassicLookAndFeelAddons.class); } } swingx-1.0-src/src/test/org/jdesktop/swingx/plaf/basic/0000755000175000017500000000000011210401734021715 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/plaf/basic/BasicMonthViewVisualCheck.java0000644000175000017500000003575611210401722027601 0ustar tonytony/* * $Id: BasicMonthViewVisualCheck.java,v 1.1 2009/04/23 12:21:22 kleopatra Exp $ * * Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.plaf.basic; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXDatePicker; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXMonthView; import org.jdesktop.swingx.SwingXUtilities; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.calendar.DateSelectionModel.SelectionMode; import org.jdesktop.swingx.plaf.basic.BasicMonthViewUI.RenderingHandler; import org.jdesktop.swingx.renderer.FormatStringValue; import org.jdesktop.swingx.renderer.StringValue; /** * TODO add type doc * * @author Jeanette Winzenburg */ public class BasicMonthViewVisualCheck extends InteractiveTestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger .getLogger(BasicMonthViewVisualCheck.class.getName()); public static void main(String[] args) { BasicMonthViewVisualCheck test = new BasicMonthViewVisualCheck(); try { // test.runInteractiveTests(); test.runInteractiveTests(".*Rendering.*"); } catch (Exception e) { e.printStackTrace(); } } public static class MyMonthViewUI extends BasicMonthViewUI { @SuppressWarnings({"UnusedDeclaration"}) public static ComponentUI createUI(JComponent c) { return new MyMonthViewUI(); } @Override protected CalendarRenderingHandler createRenderingHandler() { return new MyCalendarRenderingHandler(); } } /** * Issue #1062-swingx: core formats don't use arabic digits. Opened rendering */ public static class MyCalendarRenderingHandler extends RenderingHandler { @Override protected StringValue createDayStringValue(Locale locale) { if (locale == null) { locale = Locale.getDefault(); } SimpleDateFormat dateFormat = new SimpleDateFormat("d", locale); LOG.info("got here? " + locale.getCountry() + "-" + locale.getLanguage()); adjustFormatSymbols(locale, (DecimalFormat) dateFormat.getNumberFormat()); FormatStringValue sv = new FormatStringValue(dateFormat) { @Override public String getString(Object value) { if (value instanceof Calendar) { ((DateFormat) getFormat()).setTimeZone(((Calendar) value).getTimeZone()); value = ((Calendar) value).getTime(); } return super.getString(value); } }; return sv; } /** * @param locale * @param df */ private void adjustFormatSymbols(Locale locale, DecimalFormat df) { if ("ar".equals(locale.getLanguage())) { DecimalFormatSymbols dfs = df.getDecimalFormatSymbols(); // set the beginning of the range to Arabic digits dfs.setZeroDigit('\u0660'); df.setDecimalFormatSymbols(dfs); } } @Override protected StringValue createWeekOfYearStringValue(Locale locale) { if (locale == null) { locale = Locale.getDefault(); } DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(locale); adjustFormatSymbols(locale, format); StringValue wsv = new FormatStringValue(format) { @Override public String getString(Object value) { if (value instanceof Calendar) { value = ((Calendar) value).get(Calendar.WEEK_OF_YEAR); } return super.getString(value); } }; return wsv; } } /** * Issue #750-swingx: use rendering to side-step antialiase probs. * * Debugging ... */ public void interactiveRenderingOn() { new JXMonthView(); // KEEP this is global state - uncomment for debug painting completely // // use spinning navigation header if zoomable // UIManager.put(CalendarHeaderHandler.uiControllerID, "org.jdesktop.swingx.plaf.basic.SpinningCalendarHeaderHandler"); // // configure header: arrows around month text // UIManager.put(SpinningCalendarHeaderHandler.ARROWS_SURROUND_MONTH, Boolean.TRUE); // // configuter header: allow focus in spinner text (== editable) // UIManager.put(SpinningCalendarHeaderHandler.FOCUSABLE_SPINNER_TEXT, Boolean.TRUE); // // custom ui delegate for arabic digits in formats // UIManager.put(JXMonthView.uiClassID, "org.jdesktop.swingx.plaf.basic.BasicMonthViewUIVisualCheck$MyMonthViewUI"); // // force picker to use a zoomable monthView by default // UIManager.put("JXDatePicker.forceZoomable", Boolean.TRUE); // KEEP this is global state - uncomment for debug painting completely UIManager.put("JXMonthView.trailingDayForeground", Color.YELLOW); UIManager.put("JXMonthView.leadingDayForeground", Color.ORANGE); UIManager.put("JXMonthView.weekOfTheYearForeground", Color.GREEN); UIManager.put("JXMonthView.unselectableDayForeground", Color.MAGENTA); String frameTitle = "Debug painting: rendering on"; showDebugMonthView(frameTitle); } /** * @param frameTitle * @param disableRendering */ private void showDebugMonthView(String frameTitle) { final JXMonthView monthView = new JXMonthView(); // monthView.setZoomable(true); monthView.setDayForeground(Calendar.SUNDAY, Color.BLUE); monthView.setDaysOfTheWeekForeground(Color.RED); monthView.setFlaggedDayForeground(Color.CYAN); monthView.setSelectionBackground(Color.GRAY); monthView.setSelectionForeground(Color.GREEN); monthView.setTodayBackground(Color.PINK); monthView.setTraversable(true); monthView.setShowingWeekNumber(true); monthView.setShowingLeadingDays(true); monthView.setShowingTrailingDays(true); monthView.setSelectionMode(SelectionMode.SINGLE_INTERVAL_SELECTION); monthView.setPreferredColumnCount(2); monthView.setPreferredRowCount(2); final JXFrame frame = wrapInFrame(monthView, frameTitle); addComponentOrientationToggle(frame); Action toggleTraversable = new AbstractAction("toggle zoomable") { public void actionPerformed(ActionEvent e) { monthView.setZoomable(!monthView.isZoomable()); } }; addAction(frame, toggleTraversable); final JXDatePicker picker = new JXDatePicker(); picker.getMonthView().setShowingWeekNumber(monthView.isShowingWeekNumber()); picker.getMonthView().setZoomable(true); Action toggleShowingWeekNumbers = new AbstractAction("toggle weekNumbers") { public void actionPerformed(ActionEvent e) { monthView.setShowingWeekNumber(!monthView.isShowingWeekNumber()); picker.getMonthView().setShowingWeekNumber(monthView.isShowingWeekNumber()); } }; addAction(frame, toggleShowingWeekNumbers); picker.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals(JXDatePicker.CANCEL_KEY)) return; if (picker.getDate() == null) return; monthView.setFlaggedDates(picker.getDate()); } }); final JXDatePicker unselectable = new JXDatePicker(); unselectable.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals(JXDatePicker.CANCEL_KEY)) return; if (unselectable.getDate() == null) return; monthView.setUnselectableDates(unselectable.getDate()); } }); final JComboBox zoneSelector = new JComboBox(Locale.getAvailableLocales()); // Synchronize the monthView's and selector's zones. zoneSelector.setSelectedItem(monthView.getLocale()); // Set the monthView's time zone based on the selected time zone. zoneSelector.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { Locale zone = (Locale) zoneSelector.getSelectedItem(); SwingXUtilities.setComponentTreeLocale(frame, zone); // monthView.setLocale(zone); // monthView.revalidate(); } }); JComponent pickers = Box.createHorizontalBox(); pickers.add(new JLabel("Flagged: ")); pickers.add(picker); pickers.add(new JLabel("Unselectable: ")); pickers.add(unselectable); pickers.add(new JLabel("Locale: ")); pickers.add(zoneSelector); frame.add(pickers, BorderLayout.SOUTH); show(frame); } /** * Issue #736-swingx: monthView cannot cope with minimalDaysInFirstWeek. * * Debugging ... */ public void interactiveDayAt() { final JXMonthView monthView = new JXMonthView(); monthView.setTraversable(true); monthView.setShowingWeekNumber(true); monthView.setShowingLeadingDays(true); monthView.setShowingTrailingDays(true); monthView.setSelectionMode(SelectionMode.SINGLE_INTERVAL_SELECTION); monthView.setPreferredColumnCount(2); monthView.setPreferredRowCount(2); final BasicMonthViewUI ui = ((BasicMonthViewUI) monthView.getUI()); monthView.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { // LOG.info("calendar grid" + ui.calendarGrid); // LOG.info("dayAt " + e.getPoint() + ": " // + "\n" + monthView.getDayAtLocation(e.getX(), e.getY())); // Calendar monthAtLocation = ui.getMonthAtLocation(e.getX(), e.getY()); // LOG.info("month start " + // (monthAtLocation != null ? monthAtLocation.getTime() : null)); // Point p = ui.getMonthGridPositionAtLocation(e.getX(), e.getY()); // LOG.info("month bounds from logical " + // p + " \n " + // ui.getMonthBounds(p.y, p.x)); // LOG.info("month bounds at location" + // ui.getMonthBoundsAtLocation(e.getX(), e.getY())); LOG.info("day grid position " + ui.getDayGridPositionAtLocation(e.getX(), e.getY()) + "\nday bounds " + ui.getDayBoundsAtLocation(e.getX(), e.getY())); } }); Action action = new AbstractActionExt("toggle minimal") { public void actionPerformed(ActionEvent e) { int minimal = monthView.getSelectionModel().getMinimalDaysInFirstWeek(); monthView.getSelectionModel().setMinimalDaysInFirstWeek(minimal > 1 ? 1 : 4); } }; final JXFrame frame = wrapInFrame(monthView, "test mapping: printed on mouse release"); addAction(frame, action); addComponentOrientationToggle(frame); frame.pack(); frame.setVisible(true); } /** * Issue #736-swingx: monthView cannot cope with minimalDaysInFirstWeek. * * Here: look at impact of forcing the minimalDays to a value different * from the calendar. Days must be displayed in starting from the * first row under the days-of-week. * * Not yet completely fixed: for very late firstDayOfWeek, the Jan is incompletely * painted for mininalDays > 1. Rare enough to ignore for now? */ public void interactiveMinimalDaysInFirstWeek() { final JXMonthView monthView = new JXMonthView(); monthView.setTraversable(true); monthView.setShowingWeekNumber(true); monthView.setShowingLeadingDays(true); monthView.setShowingTrailingDays(true); monthView.setSelectionMode(SelectionMode.SINGLE_INTERVAL_SELECTION); Action action = new AbstractActionExt("toggle minimal") { public void actionPerformed(ActionEvent e) { int minimal = monthView.getSelectionModel().getMinimalDaysInFirstWeek(); monthView.getSelectionModel().setMinimalDaysInFirstWeek(minimal > 1 ? 1 : 4); } }; final JXFrame frame = wrapInFrame(monthView, "click unselectable fires ActionEvent"); addAction(frame, action); addComponentOrientationToggle(frame); final JComboBox dayOfWeekComboBox = new JComboBox(new String[]{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}); dayOfWeekComboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int selected = dayOfWeekComboBox.getSelectedIndex(); monthView.setFirstDayOfWeek(selected + Calendar.SUNDAY); } }); dayOfWeekComboBox.setSelectedIndex(monthView.getFirstDayOfWeek() - Calendar.SUNDAY); addStatusComponent(frame, dayOfWeekComboBox); frame.pack(); frame.setVisible(true); } } swingx-1.0-src/src/test/org/jdesktop/swingx/plaf/basic/BasicErrorPaneUITest.java0000644000175000017500000001437511210401724026526 0ustar tonytonypackage org.jdesktop.swingx.plaf.basic; import static org.junit.Assert.*; import java.applet.Applet; import java.awt.GraphicsEnvironment; import java.util.logging.Logger; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JWindow; import org.jdesktop.swingx.JXErrorPane; import org.junit.Before; import org.junit.Test; public class BasicErrorPaneUITest { private static final Logger LOG = Logger.getLogger(BasicErrorPaneUITest.class.getName()); private BasicErrorPaneUI ui; @Before public void setup() { JXErrorPane pane = new JXErrorPane(); assertTrue(pane.getUI().getClass().getName().equals(BasicErrorPaneUI.class.getName())); ui = (BasicErrorPaneUI) pane.getUI(); } @Test public void testGetErrorFrameNull() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } assertNotNull(ui.getErrorFrame(null)); } @Test public void testGetErrorFrameFrame() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } assertNotNull(ui.getErrorFrame(new JFrame())); } @Test public void testGetErrorFrameDialog() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } assertNotNull(ui.getErrorFrame(new JDialog())); } @Test public void testGetErrorFrameContentPane() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } JFrame frame = new JFrame(); assertNotNull(ui.getErrorFrame(frame.getContentPane())); } @Test public void testGetErrorFrameJPanel() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } assertNotNull(ui.getErrorFrame(new JPanel())); } @Test public void testGetErrorFrameApplet() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } assertNotNull(ui.getErrorFrame(new Applet())); } @Test public void testGetErrorFrameJWindow() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } assertNotNull(ui.getErrorFrame(new JWindow())); } @Test public void testGetErrorDialogNull() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } assertNotNull(ui.getErrorDialog(null)); } @Test public void testGetErrorDialogFrame() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } assertNotNull(ui.getErrorDialog(new JFrame())); } @Test public void testGetErrorDialogDialog() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } assertNotNull(ui.getErrorDialog(new JDialog())); } @Test public void testGetErrorDialogContentPane() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } JFrame frame = new JFrame(); assertNotNull(ui.getErrorDialog(frame.getContentPane())); } @Test public void testGetErrorDialogJPanel() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } assertNotNull(ui.getErrorDialog(new JPanel())); } @Test public void testGetErrorDialogApplet() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } assertNotNull(ui.getErrorDialog(new Applet())); } /** * swingx-854 - NPE when owner is JWindow */ @Test public void testGetErrorDialogJWindow() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } assertNotNull(ui.getErrorDialog(new JWindow())); } @Test public void testGetErrorInternalFrameNull() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } assertNotNull(ui.getErrorInternalFrame(null)); } @Test public void testGetErrorInternalFrameFrame() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } assertNotNull(ui.getErrorInternalFrame(new JFrame())); } @Test public void testGetErrorInternalFrameDialog() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } assertNotNull(ui.getErrorInternalFrame(new JDialog())); } @Test public void testGetErrorInternalFrameContentPane() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } JFrame frame = new JFrame(); assertNotNull(ui.getErrorInternalFrame(frame.getContentPane())); } @Test public void testGetErrorInternalFrameJPanel() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } assertNotNull(ui.getErrorInternalFrame(new JPanel())); } @Test public void testGetErrorInternalFrameApplet() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } assertNotNull(ui.getErrorInternalFrame(new Applet())); } @Test public void testGetErrorInternalFrameJWindow() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run - headless environment"); return; } assertNotNull(ui.getErrorInternalFrame(new JWindow())); } } swingx-1.0-src/src/test/org/jdesktop/swingx/plaf/basic/BasicMonthViewUIIssues.java0000644000175000017500000001375111210401722027100 0ustar tonytony/* * $Id: BasicMonthViewUIIssues.java,v 1.13 2009/04/03 12:59:29 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.plaf.basic; import java.awt.ComponentOrientation; import java.awt.GraphicsEnvironment; import java.util.Calendar; import java.util.TimeZone; import java.util.logging.Logger; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXMonthView; import org.jdesktop.swingx.calendar.CalendarUtils; /** * Tests to expose known issues of BasicMonthViewUI. * * @author Jeanette Winzenburg */ public class BasicMonthViewUIIssues extends InteractiveTestCase { @SuppressWarnings("all") private static final Logger LOG = Logger .getLogger(BasicMonthViewUIIssues.class.getName()); public static void main(String[] args) { // setSystemLF(true); BasicMonthViewUIIssues test = new BasicMonthViewUIIssues(); try { test.runInteractiveTests(); // test.runInteractiveTests(".*Simple.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #786-swingx: IllegalStateException when paintDays of April 2008. * * Set the default timezone and get the default calendar. * */ public void testTimeZoneCairoCalendarUtils() { TimeZone cairo = TimeZone.getTimeZone("Africa/Cairo"); Calendar calendar = Calendar.getInstance(cairo); assertEquals(cairo, calendar.getTimeZone()); calendar.set(2008, Calendar.MARCH, 31); CalendarUtils.startOfMonth(calendar); calendar.add(Calendar.MONTH, 1); assertTrue(CalendarUtils.isStartOfMonth(calendar)); CalendarUtils.startOfWeek(calendar); // simulate the painting loop for (int week = 0; week < 6; week++) { for (int day = 0; day < 7; day++) { calendar.add(Calendar.DAY_OF_MONTH, 1); assertTrue("must be start of day " + calendar.getTime(), CalendarUtils.isStartOfDay(calendar)); } assertTrue("must be start of week " + calendar.getTime(), CalendarUtils.isStartOfWeek(calendar)); } } /** * Test getDayBounds(Date) for leading dates are null. The assumption is * wrong for a leading date in the second month - it's contained in the * first! */ public void testDayBoundsLeadingDatesNull() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); // the ui's calendar is configured to the first displayed day Calendar calendar = ui.getCalendar(); calendar.add(Calendar.MONTH, 1); int month = calendar.get(Calendar.MONTH); CalendarUtils.startOfWeek(calendar); assertFalse("sanity - we have leading dates in the month", month == calendar.get(Calendar.MONTH)); assertEquals("leading dates must return null bounds", null, ui.getDayBounds(calendar.getTime())); } /** * Returns the ui of a realized JXMonthView with 2 columns and the * given componentOrientation without showingWeekNumbers. * * NOTE: this must not be used in a headless environment. * * @param co * @return */ private BasicMonthViewUI getRealizedMonthViewUI(ComponentOrientation co) { return getRealizedMonthViewUI(co, false); } /** * Returns the ui of a realized JXMonthView with * given componentOrientation and showingWeekNumbers flag. * It's prefColumns/Rows are set to 2. The first displayedDate is * 20. Feb. 2008 (to have fixed leading/trailing dates) * * The frame is packed and it's size extended by 40, 40 to * give a slight off-position (!= 0) of the months shown. * * * * NOTE: this must not be used in a headless environment. * * @param co the componentOrientation to use * @return */ private BasicMonthViewUI getRealizedMonthViewUI(ComponentOrientation co, boolean isShowingWeekNumbers) { JXMonthView monthView = new JXMonthView(); monthView.setPreferredColumnCount(2); monthView.setPreferredRowCount(2); monthView.setComponentOrientation(co); monthView.setShowingWeekNumber(isShowingWeekNumbers); Calendar calendar = monthView.getCalendar(); calendar.set(2008, Calendar.FEBRUARY, 20); monthView.setFirstDisplayedDay(calendar.getTime()); JXFrame frame = new JXFrame(); frame.add(monthView); frame.pack(); frame.setSize(frame.getWidth() + 40, frame.getHeight() + 40); frame.setVisible(true); BasicMonthViewUI ui = (BasicMonthViewUI) monthView.getUI(); return ui; } /** * Do nothing - just to keep the test runner from complaining * if there are no issues. * */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/plaf/basic/BasicMonthViewUITest.java0000644000175000017500000016717311210401722026554 0ustar tonytony/* * $Id: BasicMonthViewUITest.java,v 1.44 2009/04/23 12:21:22 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.plaf.basic; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Container; import java.awt.Dimension; import java.awt.GraphicsEnvironment; import java.awt.Point; import java.awt.Rectangle; import java.text.DateFormatSymbols; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.logging.Logger; import javax.swing.CellRendererPane; import javax.swing.SwingUtilities; import javax.swing.UIManager; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXMonthView; import org.jdesktop.swingx.calendar.CalendarUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests to expose known issues of BasicMonthViewUI. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class BasicMonthViewUITest extends InteractiveTestCase { @SuppressWarnings("all") private static final Logger LOG = Logger .getLogger(BasicMonthViewUITest.class.getName()); // duplicate hard-coded monthViewUI values @SuppressWarnings("unused") private static final int CALENDAR_SPACING = 10; /** * Issue #1068-swingx: week numbering broken for some years and locales * * f.i. Jan, 2011 in de: first of Jan is week 52 */ @Test public void testWeekNumbersWrapBack() { assertWeekNumbers(Locale.GERMAN, 2011, Calendar.JANUARY, Calendar.SATURDAY, 52, 6); } /** * Issue #1068-swingx: week numbering broken for some years and locales * * f.i. Dec, 2008 in de: last of dec is first week of next year */ @Test public void testWeekNumbersWrapForward() { assertWeekNumbers(Locale.GERMAN, 2008, Calendar.DECEMBER, Calendar.MONDAY, 49, 5); } /** * Issue #1068-swingx: week numbering broken for some years and locales * * f.i. Oct, 2008 in de: must frequent case, days spread across 5 weeks */ @Test public void testWeekNumbersNormal() { assertWeekNumbers(Locale.GERMAN, 2008, Calendar.OCTOBER, Calendar.WEDNESDAY, 40, 5); } /** * Creates a monthView with the given locale, sets the firstDisplayedDate to the * first of the given year and month (sanity asserts dayOfWeek and weekofYear) and * asserts the number of weeks in that month. * * @param locale * @param year * @param month * @param expectedDay day of week (sanity) * @param expectedWeek week of year of the day (sanity) * @param expectedWeekNumber number of weeks in the month */ private void assertWeekNumbers(Locale locale, int year, int month, int expectedDay, int expectedWeek, int expectedWeekNumber) { JXMonthView monthView = new JXMonthView(locale); Calendar calendar = monthView.getCalendar(); calendar.set(year, month, 1); assertEquals("sanity - day", expectedDay, calendar.get(Calendar.DAY_OF_WEEK)); assertEquals("sanity - weekOfYear", expectedWeek, calendar.get(Calendar.WEEK_OF_YEAR)); monthView.setFirstDisplayedDay(calendar.getTime()); assertEquals("number of weeks in month", expectedWeekNumber, ((BasicMonthViewUI) monthView.getUI()).getWeeks(monthView.getCalendar())); } /** * Issue #1068-swingx: week numbering broken for some years and locales * * month with fully six weeks: April 2010 */ @Test public void testWeekNumbersFull6() { assertWeekNumbers(Locale.GERMAN, 2012, Calendar.APRIL, Calendar.SUNDAY, 13, 6); } /** * Issue #1068-swingx: week numbering broken for some years and locales * * month with minimal 4 weeks: Feb 2010 */ @Test public void testWeekNumbersMinimum4() { assertWeekNumbers(Locale.GERMAN, 2010, Calendar.FEBRUARY, Calendar.MONDAY, 5, 4); } /** * Issue #1074-swingx: Regression - monthView header background lost on updateUI. */ @Test public void testZoomableKeepsMonthStringBackground() { JXMonthView monthView = new JXMonthView(); monthView.setZoomable(true); assertEquals(monthView.getMonthStringBackground(), ((BasicMonthViewUI) monthView.getUI()).getCalendarHeaderHandler().getHeaderComponent().getBackground()); SwingUtilities.updateComponentTreeUI(monthView); assertEquals(monthView.getMonthStringBackground(), ((BasicMonthViewUI) monthView.getUI()).getCalendarHeaderHandler().getHeaderComponent().getBackground()); } /** * Sanity during internal alias cleanup. */ @Test public void testFirstDisplayedInternal() { JXMonthView monthView = new JXMonthView(); BasicMonthViewUI ui = (BasicMonthViewUI) monthView.getUI(); assertEquals(monthView.getFirstDisplayedDay(), ui.getFirstDisplayedDay()); Calendar calendar = monthView.getCalendar(); assertEquals(calendar.get(Calendar.MONTH), ui.getFirstDisplayedMonth()); assertEquals(calendar.get(Calendar.YEAR), ui.getFirstDisplayedYear()); } /** * Issue #77-swingx: support year-wise navigation. * Alleviate the problem by allowing custom calendar headers. * * Here: test that the monthViewUI uses the custom header if available. */ @Test public void testZoomableCustomHeader() { UIManager.put(CalendarHeaderHandler.uiControllerID, "org.jdesktop.swingx.plaf.basic.SpinningCalendarHeaderHandler"); JXMonthView monthView = new JXMonthView(); monthView.setZoomable(true); // digging into internals Container header = (Container) monthView.getComponent(0); if (header instanceof CellRendererPane) { header = (Container) monthView.getComponent(1); } try { assertTrue("expected SpinningCalendarHeader but was " + header.getClass(), header instanceof SpinningCalendarHeaderHandler.SpinningCalendarHeader); } finally { UIManager.put(CalendarHeaderHandler.uiControllerID, null); } } /** * Sanity: uiClassID alike on CalendarHeaderHandler */ @Test public void testCalendarHeaderHandlerID() { assertEquals("CalendarHeaderHandler", CalendarHeaderHandler.uiControllerID); } /** * Issue #1046-swingx: month title not updated when traversing months * (programatically or by navigating in monthView) */ @Test public void testZoomableAddsCalendarHeader() { JXMonthView monthView = new JXMonthView(); monthView.setZoomable(true); // digging into internals Container header = (Container) monthView.getComponent(0); if (header instanceof CellRendererPane) { header = (Container) monthView.getComponent(1); } assertTrue("expected BasicCalendarHeader but was " + header.getClass(), header instanceof BasicCalendarHeaderHandler.BasicCalendarHeader); } /** * Issue #1046-swingx: month title not updated when traversing months * (programatically or by navigating in monthView) */ @Test public void testZoomableUpdateUIKeepsCalendarHeader() { JXMonthView monthView = new JXMonthView(); monthView.setZoomable(true); monthView.updateUI(); // digging into internals Component header = monthView.getComponent(0); if (header instanceof CellRendererPane) { header = (Container) monthView.getComponent(1); } assertTrue("expected BasicCalendarHeader but was " + header.getClass(), header instanceof BasicCalendarHeaderHandler.BasicCalendarHeader); } /** * Test that day position in details day-of-week header returns null date */ @Test public void testDayInMonthForDayOfWeekHeader() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); // get a date in the first month Date month = ui.getMonth(1, 0); assertEquals("header grid position must return null date", null, ui.getDayInMonth(month, BasicMonthViewUI.DAY_HEADER_ROW, BasicMonthViewUI.LAST_DAY_COLUMN)); } /** * Test that day position in details weekNumber header returns null date */ @Test public void testDayInMonthForWeekNumberHeader() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT, true); // get a date in the first month Date month = ui.getMonth(0, 0); assertEquals("header grid position must return null date", null, ui.getDayInMonth(month, BasicMonthViewUI.FIRST_WEEK_ROW + 3, BasicMonthViewUI.WEEK_HEADER_COLUMN)); } /** * Test contract of getDayInMonth: grid position of leading dates must be null. * Here: first month in grid. */ @Test public void testDayInMonthLeadingFirstMonth() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); // get a date in the first month Date month = ui.getMonth(0, 0); assertEquals("leading date grid position must return null date", null, ui.getDayInMonth(month, BasicMonthViewUI.FIRST_WEEK_ROW, BasicMonthViewUI.FIRST_DAY_COLUMN)); } /** * Test contract of getDayInMonth: grid position of leading dates must be null. * Here: second month in grid. */ @Test public void testDayInMonthLeadingSecondMonth() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); // get a date in the first month Date month = ui.getMonth(1, 0); // this fails because assertEquals("leading date grid position must return null date", null, ui.getDayInMonth(month, BasicMonthViewUI.FIRST_WEEK_ROW, BasicMonthViewUI.FIRST_DAY_COLUMN)); } /** * Issue #787-swingx: hit detection of leading/trailing days. * Sanity: get day bounds for leading dates (here: second month) must succeed. */ @Test public void testDayBoundsAtLocationLeadingSecondMonth() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); // second month - Mar 2008 has leading dates Rectangle monthBounds = ui.getMonthBoundsAtLocation(20 + ui.getMonthSize().width, 20); int firstDay = monthBounds.y + ui.getMonthHeaderHeight() + ui.getDaySize().height + 2; // second month should behave the same way as first // first is outside and returns null. int row = ui.getDayGridPositionAtLocation(monthBounds.x + 2, firstDay).y; assertEquals(BasicMonthViewUI.FIRST_WEEK_ROW, row); Rectangle dayBounds = ui.getDayBoundsAtLocation(monthBounds.x + 2, firstDay); assertNotNull(dayBounds); } /** * Issue #787-swingx: hit detection of leading/trailing days. * Sanity: get day bounds for leading dates (here: first month) must succeed. */ @Test public void testDayBoundsAtLocationLeadingFirstMonth() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); // first month - Feb 2008 has leading dates Rectangle monthBounds = ui.getMonthBoundsAtLocation(20, 20); int firstDayY = monthBounds.y + ui.getMonthHeaderHeight() + ui.getDaySize().height + 2; int row = ui.getDayGridPositionAtLocation(monthBounds.x + 2, firstDayY).y; assertEquals(BasicMonthViewUI.FIRST_WEEK_ROW, row); Rectangle dayBounds = ui.getDayBoundsAtLocation(monthBounds.x + 2, firstDayY); assertNotNull(dayBounds); } /** * Issue #787-swingx: hit detection of leading/trailing days. * Must be null (second month). */ @Test public void testDayAtLocationLeadingSecondMonth() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); // second month - Mar 2008 has leading dates Rectangle monthBounds = ui.getMonthBoundsAtLocation(20 + ui.getMonthSize().width, 20); int firstDay = monthBounds.y + ui.getMonthHeaderHeight() + ui.getDaySize().height + 2; assertEquals("hit detection in leading date must return null", null, ui.getDayAtLocation(monthBounds.x + 2, firstDay)); } /** * Issue #787-swingx: hit detection of leading/trailing days. * Must be null (first month). */ @Test public void testDayAtLocationLeadingFirstMonth() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); // first month - Feb 2008 has leading dates Rectangle monthBounds = ui.getMonthBoundsAtLocation(20, 20); int firstDayY = monthBounds.y + ui.getMonthHeaderHeight() + ui.getDaySize().height + 2; assertEquals("hit detection in leading date must return null", null, ui.getDayAtLocation(monthBounds.x + 2, firstDayY)); } /** * Test full circle: getDayBounds(Date) */ @Test public void testDayBoundsFromDate() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); // second non-header row // first day column Point location = getLocationInGrid(ui, 2, 0); Rectangle dayBounds = ui.getDayBoundsAtLocation(location.x, location.y); Date date = ui.getDayAtLocation(location.x, location.y); assertEquals(dayBounds, ui.getDayBounds(date)); } /** * Test getDayGridPosition(Date) - * here: had been incorrect calculation of first row. */ @Test public void testDateToGridPosition6Apr2008() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); Calendar cal = ui.getCalendar(); // 6th April was sunday ... it is a last day of the first week, but only at places where first day is Monday. // so using this obsure notation we get last day of first week depending on when the week really starts. cal.set(2008, Calendar.APRIL, 4 + cal.getFirstDayOfWeek()); assertEquals(BasicMonthViewUI.LAST_DAY_COLUMN, ui.getDayGridPosition(cal.getTime()).x); assertEquals(BasicMonthViewUI.FIRST_WEEK_ROW, ui.getDayGridPosition(cal.getTime()).y); } /** * Test getDayGridPosition(Date) - first complete row */ @Test public void testDateToGridPositionNonLeading() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); // get a date in the first month Date month = ui.getMonth(0, 0); // second row - cant be a leading date assertDateToDayGrid(ui, month, BasicMonthViewUI.FIRST_WEEK_ROW + 1, BasicMonthViewUI.FIRST_DAY_COLUMN); } /** * Test getDayGridPosition(Date) - somewhere in the middle (being paranoid ;-) */ @Test public void testDateToGridPositionMiddle() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); // get a date in the first month Date month = ui.getMonth(0, 0); assertDateToDayGrid(ui, month, BasicMonthViewUI.FIRST_WEEK_ROW + 3, BasicMonthViewUI.FIRST_DAY_COLUMN); } /** * Full cylce: use getDayInMonth(...) to get the day from the logical * grid position and assert that the reverse getDayGridPosition returns the same * logical coordinates. The given coordinates must map to a day contained in the * month, that is >= 0 and not representing leading/trailing dates. * * @param ui the ui to use (must be realized) * @param month the month containing the grid to test * @param dayRow the logical row coordinate of the day * @param dayColumn the logical column coordinate of the day */ private void assertDateToDayGrid(BasicMonthViewUI ui, Date month, int dayRow, int dayColumn) { Date day = ui.getDayInMonth(month, dayRow, dayColumn); assertEquals(dayRow, ui.getDayGridPosition(day).y); assertEquals(dayColumn, ui.getDayGridPosition(day).x); } /** * Test full circle: getMonthGridPosition(Date) - had problems with first row? */ @Test public void testMonthGridPositionFirstRowFromDate() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); assertDateToMonthGrid(ui, 0, 1); } /** * Full cylce: use getMonth(...) to get the month from the logical * grid position and assert that the reverse getMonthGridPosition returns the same * logical coordinates. * * @param ui the ui to use (must be realized) * @param row the row index of the month * @param column the column index of the month */ private void assertDateToMonthGrid(BasicMonthViewUI ui, int row, int column) { // date of start of month from logical position Date month = ui.getMonth(row, column); assertEquals(row, ui.getMonthGridPosition(month).y); assertEquals(column, ui.getMonthGridPosition(month).x); } /** * Test full circle: getMonthGridPosition(Date) - had problems with first row? */ @Test public void testDateToMonthGridPositionFirst() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); assertDateToMonthGrid(ui, BasicMonthViewUI.FIRST_WEEK_ROW, BasicMonthViewUI.FIRST_DAY_COLUMN); } /** * Test full circle: getMonthGridPosition(Date) - had problems with first row? */ @Test public void testDateToMonthGridPositionSecond() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); assertDateToMonthGrid(ui, 1, 0); } /** * Test full circle: getMonthGridPosition(Date) */ @Test public void testDateToMonthGridPositionLast() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); assertDateToMonthGrid(ui, 1, 1); } /** * Test full circle: getMonthBounds(Date) */ @Test public void testDateToMonthBounds() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); // month bounds from logical position in second row, second column Rectangle bounds = ui.getMonthBounds(1, 1); // date of start of month from logical position Date month = ui.getMonth(1, 1); assertEquals(bounds, ui.getMonthBounds(month)); } /** * Test getMonthBounds(Date) for not visible dates are null. */ @Test public void testDateToMonthBoundsNotVisible() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); // the ui's calendar is configured to the first displayed day Calendar uiCalendar = ui.getCalendar(); int month = uiCalendar.get(Calendar.MONTH); CalendarUtils.startOfWeek(uiCalendar); assertFalse("sanity - we have leading dates in the month", month == uiCalendar.get(Calendar.MONTH)); assertEquals("leading dates must return null bounds", null, ui.getMonthBounds(uiCalendar.getTime())); } /** * Test getDayBounds(Date) for null date must throw NPE. */ @Test public void testMonthBoundsNullDate() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); try { ui.getMonthBounds(null); fail("date param null is not allowed - must fire NPE"); } catch (NullPointerException ex) { // that's what we expect } } /** * Test getDayBounds(Date) for leading dates are null. */ @Test public void testDateToDayBoundsLeadingDate() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); // the ui's calendar is configured to the first displayed day Calendar uiCalendar = ui.getCalendar(); int month = uiCalendar.get(Calendar.MONTH); CalendarUtils.startOfWeek(uiCalendar); assertFalse("sanity - we have leading dates in the month", month == uiCalendar.get(Calendar.MONTH)); assertEquals("leading dates must return null bounds", null, ui.getDayBounds(uiCalendar.getTime())); } /** * Test getDayBounds(Date) for null date must fire NPE. */ @Test public void testDayBoundsNullDate() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); try { ui.getDayBounds(null); fail("date param null is not allowed - must fire NPE"); } catch (NullPointerException ex) { // that's what we expect } } /** * Issue #781-swingx: reverse coordinate transformation. * Here: expose sizes */ @Test public void testMonthSize() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.RIGHT_TO_LEFT); Rectangle monthBounds = ui.getMonthBoundsAtLocation(20, 20); assertEquals(monthBounds.width, ui.getMonthSize().width); assertEquals(monthBounds.height, ui.getMonthSize().height); } /** * Issue #781-swingx: reverse coordinate transformation. * Here: expose sizes */ @Test public void testDaySize() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.RIGHT_TO_LEFT); Rectangle monthBounds = ui.getMonthBoundsAtLocation(20, 20); Rectangle dayBounds = ui.getDayBoundsAtLocation( monthBounds.x + 2, monthBounds.y + ui.getMonthHeaderHeight() + 2); assertEquals(dayBounds.width, ui.getDaySize().width); assertEquals(dayBounds.height, ui.getDaySize().height); } @Test public void testMonthBoundsFromLogicalRToL() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.RIGHT_TO_LEFT); Rectangle monthBounds = ui.getMonthBoundsAtLocation(20, 20); // second row, first column in absolute coordinates Rectangle monthBounds11 = ui.getMonthBoundsAtLocation( 20, monthBounds.y + 20 + monthBounds.height); // second row, second column in logical coordinates assertEquals(monthBounds11, ui.getMonthBounds(1, 1)); } @Test public void testMonthBoundsFromLogicalLToR() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); Rectangle monthBounds = ui.getMonthBoundsAtLocation(20, 20); // second row, second column Rectangle monthBounds11 = ui.getMonthBoundsAtLocation( monthBounds.x + 20 + monthBounds.width, monthBounds.y + 20 + monthBounds.height); // second row, second column in logical coordinates assertEquals(monthBounds11, ui.getMonthBounds(1, 1)); } /** * Sanity test: inexpected pass if the realized frame isn't visible. */ @Test public void testFirstMonthLocation() { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); Rectangle monthBounds = ui.getMonthBoundsAtLocation(20, 20); assertEquals(monthBounds.getLocation(), ui.calendarGrid.getLocation()); assertNull("no hit - bounds must be null", ui.getMonthBoundsAtLocation(19, 20)); } /** * Test day at location */ @Test public void testDayAtLocationLToR() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); // first column in second non-header row Point location = getLocationInGrid(ui, 2, 0); Date date = ui.getDayAtLocation(location.x, location.y); // the ui's calendar is configured to the first displayed day Calendar uiCalendar = ui.getCalendar(); uiCalendar.add(Calendar.WEEK_OF_YEAR, 1); CalendarUtils.startOfWeek(uiCalendar); assertEquals("first logical column in LToR", uiCalendar.getTime(), date); } /** * Test day at location */ @Test public void testDayAtLocationRToL() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.RIGHT_TO_LEFT); // first column in second non-header row Point location = getLocationInGrid(ui, 2, 0); Date date = ui.getDayAtLocation(location.x, location.y); Date endOfWeek = CalendarUtils.endOfWeek(ui.getCalendar(), date); Calendar uiCalendar = ui.getCalendar(ui.getMonthAtLocation(20, 20)); uiCalendar.add(Calendar.WEEK_OF_YEAR, 1); CalendarUtils.endOfWeek(uiCalendar); assertEquals("first day in first week", uiCalendar.getTime(), endOfWeek); } /** * Test day at location: hitting days of week must return null. */ @Test public void testDayAtLocationDayHeaderNull() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); Rectangle monthBounds = ui.getMonthBoundsAtLocation(20, 20); // same for LToR Date date = ui.getDayAtLocation( monthBounds.x + 2, monthBounds.y + ui.getMonthHeaderHeight() + 2); assertNull("hitting days-of-week must return null calendar", date); } @Test public void testDayBounds() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI uiRToL = getRealizedMonthViewUI(ComponentOrientation.RIGHT_TO_LEFT); BasicMonthViewUI uiLToR = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); Rectangle monthBounds = uiRToL.getMonthBoundsAtLocation(20, 20); assertNull("hit in header must return null bounds", uiRToL.getDayBoundsAtLocation(monthBounds.x + 2, monthBounds.y + 2)); // first column first row Rectangle dayBoundsRToL = uiRToL.getDayBoundsAtLocation( monthBounds.x + 2, monthBounds.y + uiRToL.getMonthHeaderHeight()); // same for LToR Rectangle dayBoundsLToR = uiLToR.getDayBoundsAtLocation( monthBounds.x + 2, monthBounds.y + uiLToR.getMonthHeaderHeight()); assertEquals("day bounds must be independent of orientation", dayBoundsLToR, dayBoundsRToL); assertEquals(monthBounds.x, dayBoundsLToR.x); assertEquals(monthBounds.y + uiLToR.getMonthHeaderHeight(), dayBoundsLToR.y); } //------------------------ methods to test getDayGridPositionAtLocation (bulk) // PENDING JW: should we test the corner cases separatedly? Had been historical /** * Map pixel to logical grid, test rows. */ @Test public void testDayGridPositionAtLocationRows() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.RIGHT_TO_LEFT); int calendarRow = BasicMonthViewUI.DAY_HEADER_ROW; for (int row = 0; row <= BasicMonthViewUI.WEEKS_IN_MONTH; row++) { Point location = getLocationInRow(ui, row); // first row below month header == days of week header Point dayGridPosition = ui.getDayGridPositionAtLocation(location.x, location.y); assertEquals("calendarRow at absolute row " + row, calendarRow, dayGridPosition.y); calendarRow++; } } /** * Map pixel to logical grid, test columns in LToR. * */ @Test public void testDayGridPositionAtLocationColumnsLToR() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); int calendarColumn = BasicMonthViewUI.FIRST_DAY_COLUMN; for (int column = 0; column < BasicMonthViewUI.DAYS_IN_WEEK; column++) { Point location = getLocationInColumn(ui, column); // first row below month header == days of week header Point dayGridPosition = ui.getDayGridPositionAtLocation(location.x, location.y); assertEquals("calendarColumn at absolute column " + column, calendarColumn, dayGridPosition.x); calendarColumn++; } } /** * Map pixel to logical grid, test columns with weekNumbers in LToR. */ @Test public void testDayGridPositionAtLocationColumnsLToRWithWeekNumber() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT, true); int calendarColumn = BasicMonthViewUI.WEEK_HEADER_COLUMN; for (int column = 0; column <= BasicMonthViewUI.DAYS_IN_WEEK; column++) { Point location = getLocationInColumn(ui, column); // first row below month header == days of week header Point dayGridPosition = ui.getDayGridPositionAtLocation(location.x, location.y); assertEquals("calendarColumn at absolute column " + column, calendarColumn, dayGridPosition.x); calendarColumn++; } } /** * Map pixel to logical grid, test columns in RToL. */ @Test public void testDayGridPositionAtLocationColumnsRToL() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.RIGHT_TO_LEFT); int calendarColumn = BasicMonthViewUI.LAST_DAY_COLUMN; for (int column = 0; column < BasicMonthViewUI.DAYS_IN_WEEK; column++) { Point location = getLocationInColumn(ui, column); // first row below month header == days of week header Point dayGridPosition = ui.getDayGridPositionAtLocation(location.x, location.y); assertEquals("calendarColumn at absolute column " + column, calendarColumn, dayGridPosition.x); calendarColumn--; } } /** * Map pixel to logical grid, test columns with weekNubmers in RToL. */ @Test public void testDayGridPositionAtLocationColumnsRToLWithWeekNumber() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.RIGHT_TO_LEFT, true); int calendarColumn = BasicMonthViewUI.LAST_DAY_COLUMN; for (int column = 0; column <= BasicMonthViewUI.DAYS_IN_WEEK; column++) { Point location = getLocationInColumn(ui, column); // first row below month header == days of week header Point dayGridPosition = ui.getDayGridPositionAtLocation(location.x, location.y); assertEquals("calendarColumn at absolute column " + column, calendarColumn, dayGridPosition.x); calendarColumn--; } } //----------------- test get DayGridPositionAtLocation (special boundary points) /** * Map pixel to logical grid. * day grid row == DAY_HEADER_ROW. */ @Test public void testDayGridPositionAtLocationDayHeader() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.RIGHT_TO_LEFT); Point location = getLocationInRow(ui, 0); // first row below month header == days of week header Point dayGridPosition = ui.getDayGridPositionAtLocation(location.x, location.y); assertEquals("first row below header must be day column header", BasicMonthViewUI.DAY_HEADER_ROW, dayGridPosition.y); } /** * Map pixel to logical grid. * day grid rows == FIRST_WEEK_ROW */ @Test public void testDayGridPositionAtLocationFirstWeekRow() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.RIGHT_TO_LEFT); // location in second (geometrical, calculated from day size) grid row Point location = getLocationInRow(ui, 1); Point dayInGrid = ui.getDayGridPositionAtLocation(location.x, location.y); assertEquals("first row", BasicMonthViewUI.FIRST_WEEK_ROW, dayInGrid.y); } /** * Map pixel to logical grid. * day grid rows == LAST_WEEK_ROW */ @Test public void testDayGridPositionAtLocationLastWeekRow() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.RIGHT_TO_LEFT); Point location = getLocationInRow(ui, BasicMonthViewUI.WEEKS_IN_MONTH); Point dayInGrid = ui.getDayGridPositionAtLocation(location.x, location.y); assertEquals("first row", BasicMonthViewUI.LAST_WEEK_ROW, dayInGrid.y); } /** * Map pixel to logical grid. * day grid column == LAST_DAY_COLUMN in RToL and FIRST_DAY_COLUMN in LToR */ @Test public void testDayGridPositionAtLocationLastColumnRToL() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.RIGHT_TO_LEFT); Point location = getLocationInColumn(ui, 0); Point dayGridPosition = ui.getDayGridPositionAtLocation(location.x, location.y); assertEquals("last logical column in RToL", BasicMonthViewUI.LAST_DAY_COLUMN, dayGridPosition.x); } /** * Map pixel to logical grid. * day grid column == LAST_DAY_COLUMN in RToL and FIRST_DAY_COLUMN in LToR */ @Test public void testDayGridPositionAtLocationFirstColumnRToL() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.RIGHT_TO_LEFT); Point location = getLocationInColumn(ui, BasicMonthViewUI.DAYS_IN_WEEK - 1); Point dayGridPosition = ui.getDayGridPositionAtLocation(location.x, location.y); assertEquals("last logical column in RToL", BasicMonthViewUI.FIRST_DAY_COLUMN, dayGridPosition.x); } /** * Map pixel to logical grid. * day grid column == LAST_DAY_COLUMN in RToL and FIRST_DAY_COLUMN in LToR */ @Test public void testDayGridPositionAtLocationFirstColumnRToLWithWeekNumber() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.RIGHT_TO_LEFT, true); Point location = getLocationInColumn(ui, BasicMonthViewUI.DAYS_IN_WEEK - 1); Point dayGridPosition = ui.getDayGridPositionAtLocation(location.x, location.y); assertEquals("last logical column in RToL", BasicMonthViewUI.FIRST_DAY_COLUMN, dayGridPosition.x); } /** * Map pixel to logical grid. * day grid column == LAST_DAY_COLUMN in RToL and FIRST_DAY_COLUMN in LToR */ @Test public void testDayGridPositionAtLocationFirstColumnLToR() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); Point location = getLocationInColumn(ui, 0); Point dayGridPosition = ui.getDayGridPositionAtLocation(location.x, location.y); assertEquals("first logical column in LToR", BasicMonthViewUI.FIRST_DAY_COLUMN, dayGridPosition.x); } /** * Map pixel to logical grid. * day grid column == LAST_DAY_COLUMN in RToL and FIRST_DAY_COLUMN in LToR */ @Test public void testDayGridPositionAtLocationLastColumnLToR() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); Point location = getLocationInColumn(ui, BasicMonthViewUI.DAYS_IN_WEEK - 1); Point dayGridPosition = ui.getDayGridPositionAtLocation(location.x, location.y); assertEquals("first logical column in LToR", BasicMonthViewUI.LAST_DAY_COLUMN, dayGridPosition.x); } /** * Map pixel to logical grid. * day grid column == LAST_DAY_COLUMN in RToL and FIRST_DAY_COLUMN in LToR */ @Test public void testDayGridPositionAtLocationWeekHeaderRToL() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.RIGHT_TO_LEFT, true); // right == week header Point location = getLocationInColumn(ui, BasicMonthViewUI.DAYS_IN_WEEK); Point dayGridPosition = ui.getDayGridPositionAtLocation(location.x, location.y); assertEquals("weeks of year column in RTL", BasicMonthViewUI.WEEK_HEADER_COLUMN, dayGridPosition.x); } /** * Map pixel to logical grid. * day grid column == LAST_DAY_COLUMN in RToL and FIRST_DAY_COLUMN in LToR */ @Test public void testDayGridPositionAtLocationWeekHeaderLToR() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT, true); // left == week header Point location = getLocationInColumn(ui, 0); Point dayGridPosition = ui.getDayGridPositionAtLocation(location.x, location.y); assertEquals("first logical column in LToR", BasicMonthViewUI.WEEK_HEADER_COLUMN, dayGridPosition.x); } /** * day grid returns null for hitting month header. */ @Test public void testDayGridPositionAtLocationMonthHeaderHitLToR() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); Point location = getLocationInMonthHeader(ui); assertNull("hit in header must return null grid position", ui.getDayGridPositionAtLocation(location.x, location.y)); } /** * day grid returns null for hitting month header. */ @Test public void testDayGridPositionAtLocationMonthHeaderHitRToL() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.RIGHT_TO_LEFT); Point location = getLocationInMonthHeader(ui); assertNull("hit in header must return null grid position", ui.getDayGridPositionAtLocation(location.x, location.y)); } /** * coordinate mapping: get calendar from logical grid * coordinates. */ @Test public void testMonthFromGrid() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI uiRToL = getRealizedMonthViewUI(ComponentOrientation.RIGHT_TO_LEFT); BasicMonthViewUI uiLToR = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); Date month = uiLToR.getMonth(0, 0); Calendar first = uiLToR.getCalendar(); int monthField = first.get(Calendar.MONTH); first.setTime(month); assertEquals(monthField, first.get(Calendar.MONTH)); Date monthRL = uiRToL.getMonth(0, 0); first.setTime(monthRL); assertEquals("logical coordinates must be independent of orientation", monthField, first.get(Calendar.MONTH)); } /** * coordinate mapping: logical grid coordinates. */ @Test public void testMonthGridPositionAtLocation() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI uiRToL = getRealizedMonthViewUI(ComponentOrientation.RIGHT_TO_LEFT); BasicMonthViewUI uiLToR = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); Point gridPositionLToR = uiLToR.getMonthGridPositionAtLocation(20, 20); assertEquals(0, gridPositionLToR.x); Point gridPositionRToL = uiRToL.getMonthGridPositionAtLocation(20, 20); assertEquals(1, gridPositionRToL.x); } /** * coordinate mapping: monthBounds in pixel. * */ @Test public void testMonthBoundsAtLocation() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } BasicMonthViewUI uiRToL = getRealizedMonthViewUI(ComponentOrientation.RIGHT_TO_LEFT); BasicMonthViewUI uiLToR = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); Rectangle monthBoundsRToL = uiRToL.getMonthBoundsAtLocation(20, 20); Rectangle monthBoundsLToR = uiLToR.getMonthBoundsAtLocation(20, 20); // bounds of first assertEquals("bounds of left-most month must be equal", monthBoundsLToR, monthBoundsRToL); Rectangle monthBoundsTwoRToL = uiRToL.getMonthBoundsAtLocation( monthBoundsRToL.width + 20, 20); Rectangle monthBoundsTwoLToR = uiRToL.getMonthBoundsAtLocation( monthBoundsLToR.width + 20, 20); assertEquals("bounds of right-most month must be equal", monthBoundsTwoLToR, monthBoundsTwoRToL); } /** * coordinate mapping: monthBounds in pixel. * */ @Test public void testMonthHeaderBoundsAtLocation() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } JXMonthView monthView = new JXMonthView(); monthView.setTraversable(true); JXFrame frame = new JXFrame(); frame.add(monthView); frame.pack(); BasicMonthViewUI ui = (BasicMonthViewUI) monthView.getUI(); Rectangle monthBoundsLToR = ui.getMonthHeaderBoundsAtLocation(20, 20); assertEquals("", ui.getMonthHeaderHeight(), monthBoundsLToR.height); } /** * @param ui * @return */ private Point getLocationInMonthHeader(BasicMonthViewUI ui) { Rectangle monthBounds = ui.getMonthBoundsAtLocation(20, 20); return new Point(monthBounds.x + 2, monthBounds.y + 2); } /** * Returns a location in the given day grid row/column (absolute coordinates) * * @param ui the ui to get the location from * @param columnOfDayBoxes the absolute grid column * @return a location in pixel, calcualated from the month location and * day size. */ private Point getLocationInGrid(BasicMonthViewUI ui, int rowOfDayBoxes, int columnOfDayBoxes) { Rectangle monthBounds = ui.getMonthBoundsAtLocation(20, 20); Dimension dayBounds = ui.getDaySize(); Point location = new Point( monthBounds.x + columnOfDayBoxes * dayBounds.width + 2, monthBounds.y + ui.getMonthHeaderHeight() + rowOfDayBoxes * dayBounds.height + 2); return location; } /** * Returns a location in the given day grid column (absolute coordinates) * * @param ui the ui to get the location from * @param columnOfDayBoxes the absolute grid column * @return a location in pixel, calcualated from the month location and * day size. */ private Point getLocationInColumn(BasicMonthViewUI ui, int columnOfDayBoxes) { Rectangle monthBounds = ui.getMonthBoundsAtLocation(20, 20); Dimension dayBounds = ui.getDaySize(); Point location = new Point( monthBounds.x + columnOfDayBoxes * dayBounds.width + 2, monthBounds.y + ui.getMonthHeaderHeight() + 2); return location; } /** * Returns a location in the given day grid row (absolute coordinates) * * @param ui * @param rowOfDayBoxes the absolute grid row * @return a location in pixel, calcualated from the month location and * day size. */ private Point getLocationInRow(BasicMonthViewUI ui, int rowOfDayBoxes) { Rectangle monthBounds = ui.getMonthBoundsAtLocation(20, 20); Dimension dayBounds = ui.getDaySize(); Point location = new Point( monthBounds.x + 2, monthBounds.y + ui.getMonthHeaderHeight() + rowOfDayBoxes * dayBounds.height + 2); return location; } /** * Returns the ui of a realized JXMonthView with 2 columns and the * given componentOrientation without showingWeekNumbers. * * NOTE: this must not be used in a headless environment. * * @param co * @return */ private BasicMonthViewUI getRealizedMonthViewUI(ComponentOrientation co) { return getRealizedMonthViewUI(co, false); } /** * Returns the ui of a realized JXMonthView with * given componentOrientation and showingWeekNumbers flag. * It's prefColumns/Rows are set to 2. The first displayedDate is * 20. Feb. 2008 (to have fixed leading/trailing dates) * * The frame is packed and it's size extended by 40, 40 to * give a slight off-position (!= 0) of the months shown. * * NOTE: this must not be used in a headless environment. * * @param co the componentOrientation to use * @return */ private BasicMonthViewUI getRealizedMonthViewUI(ComponentOrientation co, boolean isShowingWeekNumbers) { JXMonthView monthView = new JXMonthView(); monthView.setPreferredColumnCount(2); monthView.setPreferredRowCount(2); monthView.setComponentOrientation(co); monthView.setShowingWeekNumber(isShowingWeekNumbers); Calendar calendar = monthView.getCalendar(); calendar.set(2008, Calendar.FEBRUARY, 20); monthView.setFirstDisplayedDay(calendar.getTime()); JXFrame frame = new JXFrame(); frame.add(monthView); frame.pack(); frame.setSize(frame.getWidth() + 40, frame.getHeight() + 40); frame.setVisible(true); BasicMonthViewUI ui = (BasicMonthViewUI) monthView.getUI(); return ui; } /** * cleanup date representation as long: new api getDayAtLocation. will * replace getDayAt which is deprecated as a first step. */ @Test public void testGetDayAtLocation() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } JXMonthView monthView = new JXMonthView(); monthView.getSelectionModel().setMinimalDaysInFirstWeek(1); JXFrame frame = new JXFrame(); frame.add(monthView); frame.pack(); Dimension pref = monthView.getPreferredSize(); pref.width = pref.width / 2; pref.height = pref.height / 2; Date date = monthView.getDayAtLocation(pref.width, pref.height); assertNotNull(date); } /** * Issue 711-swingx: today notify-only property. * Changed to read-only in monthView */ @Test public void testTodayUpdate() { JXMonthView monthView = new JXMonthView(); Date first = ((BasicMonthViewUI) monthView.getUI()).getToday(); monthView.updateUI(); assertEquals(first, ((BasicMonthViewUI) monthView.getUI()).getToday()); } /** * test localized month names. */ @Test public void testLocaleMonths() { Locale french = Locale.FRENCH; JXMonthView monthView = new JXMonthView(french); assertMonths(monthView, french); Locale german = Locale.GERMAN; monthView.setLocale(german); assertMonths(monthView, german); } private void assertMonths(JXMonthView monthView, Locale french) { // sanity assertEquals(french, monthView.getLocale()); BasicMonthViewUI ui = (BasicMonthViewUI) monthView.getUI(); String[] months = new DateFormatSymbols(french).getMonths(); for (int i = 0; i < months.length; i++) { assertEquals(months[i], ui.monthsOfTheYear[i]); } } @Test public void testCustomWeekdays() { String[] days = new String[] {"1", "2", "3", "4", "5", "6", "7"}; UIManager.put("JXMonthView.daysOfTheWeek", days); JXMonthView monthView = new JXMonthView(Locale.GERMAN); try { assertWeekdays(monthView, days); monthView.setLocale(Locale.FRENCH); assertWeekdays(monthView, days); } finally { UIManager.put("JXMonthView.daysOfTheWeek", null); } } private void assertWeekdays(JXMonthView monthView, String[] weekdays) { // sanity for (int i = 0; i < 7; i++) { assertEquals(weekdays[i], monthView.getDaysOfTheWeek()[i]); } } /** * test localized weekday names. */ @Test public void testLocaleWeekdays() { Locale french = Locale.FRENCH; JXMonthView monthView = new JXMonthView(french); assertWeekdays(monthView, french); Locale german = Locale.GERMAN; monthView.setLocale(german); assertWeekdays(monthView, german); } private void assertWeekdays(JXMonthView monthView, Locale french) { // sanity assertEquals(french, monthView.getLocale()); String[] weekdays = new DateFormatSymbols(french).getShortWeekdays(); for (int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++) { assertEquals(weekdays[i], monthView.getDaysOfTheWeek()[i-1]); } } /** * Issue ??-swingx: zero millis are valid. * * bad marker in ui-delegate ... but looks okay? */ @Test public void testZeroFirstDisplayedDate() { JXMonthView monthView = new JXMonthView(); Date first = monthView.getUI().getLastDisplayedDay(); monthView.updateUI(); assertEquals(first, monthView.getUI().getLastDisplayedDay()); } /** * Issue #708-swingx: updateUI changes state. * * Here: test that lastDisplayedDate is unchanged. */ @Test public void testUpdateUILast() { final JXMonthView monthView = new JXMonthView(); Date first = monthView.getUI().getLastDisplayedDay(); monthView.updateUI(); assertEquals(first, monthView.getUI().getLastDisplayedDay()); }; /** * Issue #708-swingx: updateUI changes state. * * Here: test that firstDisplayedYear is unchanged. */ @Test public void testUpdateUIFirstYear() { final JXMonthView monthView = new JXMonthView(); long first = ((BasicMonthViewUI) monthView.getUI()).getFirstDisplayedYear(); monthView.updateUI(); assertEquals(first, ((BasicMonthViewUI) monthView.getUI()).getFirstDisplayedYear()); }; /** * Issue #708-swingx: updateUI changes state. * * Here: test that firstDisplayedMonth is unchanged. */ @Test public void testUpdateUIFirstMonth() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.MONTH, 5); // need to instantiate with a month different from jan final JXMonthView monthView = new JXMonthView(cal.getTime()); long first = ((BasicMonthViewUI) monthView.getUI()).getFirstDisplayedMonth(); monthView.updateUI(); assertEquals(first, ((BasicMonthViewUI) monthView.getUI()).getFirstDisplayedMonth()); }; } swingx-1.0-src/src/test/org/jdesktop/swingx/plaf/UIManagerExtTest.properties0000644000175000017500000000031311210401722026075 0ustar tonytony#properties for UIManagerExtTest goodBoolean=true badBoolean=text #nullBoolean= goodColor=#FFFFFF badColor=text #nullColor= goodFont=Arial-BOLD-18 badFont=text #nullFont= goodInt=1 badInt=text #nullInt= swingx-1.0-src/src/test/org/jdesktop/swingx/plaf/UIManagerExtTest.java0000644000175000017500000002375611210401722024642 0ustar tonytony/* * $Id: UIManagerExtTest.java,v 1.2 2008/10/11 20:42:32 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.plaf; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Insets; import java.util.Locale; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.UIManager; import javax.swing.plaf.UIResource; import org.jdesktop.swingx.icon.EmptyIcon; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; import junit.framework.TestCase; /** * Tests the functionality of {@code UIManagerExt}. * * @author Karl George Schaefer */ @RunWith(JUnit4.class) public class UIManagerExtTest extends TestCase { private static final Logger LOG = Logger.getLogger(UIManagerExtTest.class .getName()); /** * {@inheritDoc} */ protected void setUp() { UIManagerExt.addResourceBundle("org.jdesktop.swingx.plaf.UIManagerExtTest"); } /** * Ensure that the {@code getSafeXXX} methods always return * {@code UIResource}. */ @Test public void testGetSafeMethodsReturnUIResource() { assertTrue(UIManagerExt.getSafeBorder("", BorderFactory .createEmptyBorder()) instanceof UIResource); assertTrue(UIManagerExt.getSafeColor("", Color.RED) instanceof UIResource); assertTrue(UIManagerExt.getSafeDimension("", new Dimension()) instanceof UIResource); assertTrue(UIManagerExt.getSafeFont("", new Font("Dialog", Font.BOLD, 12)) instanceof UIResource); assertTrue(UIManagerExt.getSafeIcon("", new EmptyIcon()) instanceof UIResource); assertTrue(UIManagerExt.getSafeInsets("", new Insets(0, 0, 0, 0)) instanceof UIResource); } /** * test that we get a boolean from the localized resource. */ @Test public void testGetBooleanFromResource() { String key = "goodBoolean"; Locale locale = JComponent.getDefaultLocale(); String columnString = UIManagerExt.getString(key, locale); if (columnString == null) { LOG.info("cant run test - no resource found for key: " + key); return; } Object value = UIManagerExt.getBoolean(key, locale); assertNotNull(value); assertEquals(Boolean.valueOf(columnString), value); } /** * test that a value in the UIManager is not overwritten. */ @Test public void testGetBooleanUIManagerFirst() { String key = "goodBoolean"; Locale locale = JComponent.getDefaultLocale(); String columnString = UIManagerExt.getString(key, locale); if (columnString == null) { LOG.info("cant run test - no resource found for key: " + key); return; } try { Boolean temp = true; UIManager.put(key, temp); Object value = UIManagerExt.getBoolean(key, locale); assertNotNull(value); assertEquals(temp, value); } finally { // restore uimanager UIManager.put(key, null); } } /** * test that the getBoolean doesn't choke on non-Booleans */ @Test public void testGetBooleanLenientWithUnparseable() { String key = "badBoolean"; Locale locale = JComponent.getDefaultLocale(); String columnString = UIManagerExt.getString(key, locale); if (columnString == null) { LOG.info("cant run test - no resource found for key: " + key); return; } UIManagerExt.getBoolean(key, locale); } /** * test that we get a boolean from the localized resource. */ @Test public void testGetColorFromResource() { String key = "goodColor"; Locale locale = JComponent.getDefaultLocale(); String columnString = UIManagerExt.getString(key, locale); if (columnString == null) { LOG.info("cant run test - no resource found for key: " + key); return; } Object value = UIManagerExt.getColor(key, locale); assertNotNull(value); assertEquals(Color.decode(columnString), value); } /** * test that a value in the UIManager is not overwritten. */ @Test public void testGetColorUIManagerFirst() { String key = "goodColor"; Locale locale = JComponent.getDefaultLocale(); String columnString = UIManagerExt.getString(key, locale); if (columnString == null) { LOG.info("cant run test - no resource found for key: " + key); return; } try { Color temp = Color.RED; UIManager.put(key, temp); Object value = UIManagerExt.getColor(key, locale); assertNotNull(value); assertEquals(temp, value); } finally { // restore uimanager UIManager.put(key, null); } } /** * test that the getBoolean doesn't choke on non-Booleans */ @Test public void testGetColorLenientWithUnparseable() { String key = "badColor"; Locale locale = JComponent.getDefaultLocale(); String columnString = UIManagerExt.getString(key, locale); if (columnString == null) { LOG.info("cant run test - no resource found for key: " + key); return; } try { Color.decode(columnString); LOG.info("cant run test - valid integer: " + columnString); } catch (Exception ex) { // must not bark UIManagerExt.getColor(key, locale); } } //TODO remove or reenable after getFont is finalized // /** // * test that we get a font from the localized resource. // */ // public void testGetFontFromResource() { // String key = "goodFont"; // Locale locale = JComponent.getDefaultLocale(); // String columnString = UIManagerExt.getString(key, locale); // if (columnString == null) { // LOG.info("cant run test - no resource found for key: " + key); // return; // } // Object value = UIManagerExt.getFont(key, locale); // assertNotNull(value); // assertEquals(Font.decode(columnString), value); // } // // /** // * test that a value in the UIManager is not overwritten. // */ // public void testGetFontUIManagerFirst() { // String key = "goodFont"; // Locale locale = JComponent.getDefaultLocale(); // String columnString = UIManagerExt.getString(key, locale); // if (columnString == null) { // LOG.info("cant run test - no resource found for key: " + key); // return; // } // // try { // Font temp = new Font("Dialog", Font.ITALIC, 11); // UIManager.put(key, temp); // Object value = UIManagerExt.getFont(key, locale); // assertNotNull(value); // assertEquals(temp, value); // } finally { // // restore uimanager // UIManager.put(key, null); // } // } // // /** // * test that the getFont doesn't choke on non-Fonts // */ // public void testGetFontLenientWithUnparseable() { // String key = "badFont"; // Locale locale = JComponent.getDefaultLocale(); // String columnString = UIManagerExt.getString(key, locale); // if (columnString == null) { // LOG.info("cant run test - no resource found for key: " + key); // return; // } // // try { // System.err.println(Font.decode(columnString)); // Font.decode(columnString); // LOG.info("cant run test - valid integer: " + columnString); // } catch (Exception ex) { // // must not bark // UIManagerExt.getFont(key, locale); // } // } /** * test that we get an int from the localized resource. */ @Test public void testGetIntFromResource() { String key = "goodInt"; Locale locale = JComponent.getDefaultLocale(); String columnString = UIManagerExt.getString(key, locale); if (columnString == null) { LOG.info("cant run test - no resource found for key: " + key); return; } Object value = UIManagerExt.getInt(key, locale); assertNotNull(value); assertEquals(Integer.decode(columnString), value); } /** * test that a value in the UIManager is not overwritten. */ @Test public void testGetIntUIManagerFirst() { String key = "goodInt"; Locale locale = JComponent.getDefaultLocale(); String columnString = UIManagerExt.getString(key, locale); if (columnString == null) { LOG.info("cant run test - no resource found for key: " + key); return; } try { Integer temp = 150; UIManager.put(key, temp); Object value = UIManagerExt.getInt(key, locale); assertNotNull(value); assertEquals(temp, value); } finally { // restore uimanager UIManager.put(key, null); } } /** * test that the getInt doesn't choke on non-numbers */ @Test public void testGetIntLenientWithUnparseable() { String key = "badInt"; Locale locale = JComponent.getDefaultLocale(); String columnString = UIManagerExt.getString(key, locale); if (columnString == null) { LOG.info("cant run test - no resource found for key: " + key); return; } try { Integer.decode(columnString); LOG.info("cant run test - valid integer: " + columnString); } catch (Exception ex) { // must not bark UIManagerExt.getInt(key, locale); } } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXRootPaneTest.java0000644000175000017500000002242411210401722023407 0ustar tonytony/* * Created on 22.07.2005 * */ package org.jdesktop.swingx; import java.awt.Dimension; import java.awt.GraphicsEnvironment; import java.awt.event.ActionEvent; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JRootPane; import javax.swing.JToolBar; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.table.DefaultTableModel; import org.jdesktop.swingx.JXRootPane.XRootLayout; import org.jdesktop.test.AncientSwingTeam; import org.jdesktop.test.PropertyChangeReport; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; /** * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class JXRootPaneTest extends InteractiveTestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger.getLogger(JXRootPaneTest.class .getName()); /** * Issue #936-swingx: JXRootPane cannot cope with default laf decoration. * * testing implementation detail: layout's delegate is null by default */ @Test public void testLayoutDelegateNull() { JXRootPane pane = new JXRootPane(); assertTrue(pane.getLayout() instanceof XRootLayout); assertNull(((XRootLayout) pane.getLayout()).delegate); } /** * Issue #936-swingx: JXRootPane cannot cope with default laf decoration. * * testing implementation detail: layout's delegate is not null with laf decoration * * How-to check if LAF supports laf decoration? Here we rely on default * laf is metal which does support it */ @Test public void testLayoutDelegateLAF() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } if (!UIManager.getLookAndFeel().getSupportsWindowDecorations()) { LOG.info("cannot run test - unsupported laf window decoration"); return; } JFrame.setDefaultLookAndFeelDecorated(true); JXFrame frame = new JXFrame(); JXRootPane pane = frame.getRootPaneExt(); try { assertTrue(pane.getLayout() instanceof XRootLayout); assertNotNull(((XRootLayout) pane.getLayout()).delegate); pane.setWindowDecorationStyle(JRootPane.NONE); assertNull(((XRootLayout) pane.getLayout()).delegate); } finally { JFrame.setDefaultLookAndFeelDecorated(false); } } /** * Issue #936-swingx: JXRootPane cannot cope with default laf decoration. * * here the actual test: pref size with laf decoration */ @Test public void testLayoutWithLAFDecoration() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run testLAFDecorationLayout - headless environment"); return; } if (!UIManager.getLookAndFeel().getSupportsWindowDecorations()) { LOG.info("cannot run test - unsupported laf window decoration"); return; } JFrame.setDefaultLookAndFeelDecorated(true); JXFrame frame = new JXFrame(); frame.add(new JXTable(new AncientSwingTeam())); frame.pack(); Dimension dim = frame.getSize(); assertEquals(dim, frame.getPreferredSize()); JXStatusBar bar = new JXStatusBar(); bar.add(new JLabel("need some content")); frame.setStatusBar(bar); frame.pack(); try { assertEquals(dim.height + bar.getPreferredSize().height, frame.getPreferredSize().height); } finally { JFrame.setDefaultLookAndFeelDecorated(false); } } /** * Issue #936-swingx: JXRootPane cannot cope with default laf decoration. * Compare: no laf decoration */ @Test public void testLayoutWithOut() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run testLAFDecorationLayout - headless environment"); return; } JXFrame frame = new JXFrame(); frame.add(new JXTable(new AncientSwingTeam())); frame.pack(); Dimension dim = frame.getSize(); assertEquals(dim, frame.getPreferredSize()); JXStatusBar bar = new JXStatusBar(); bar.add(new JLabel("need some content")); frame.setStatusBar(bar); frame.pack(); try { assertEquals(dim.height + bar.getPreferredSize().height, frame.getPreferredSize().height); } finally { JFrame.setDefaultLookAndFeelDecorated(false); } } /** * Issue #566: JXRootPane eats escape from popups (JXDatePicker). * */ @Test public void testDefaultCancel() { JXRootPane rootPane = new JXRootPane(); assertNull(rootPane.getCancelButton()); Action action = rootPane.getActionMap().get("esc-action"); assertFalse(action.isEnabled()); } /** * Test setStatusBar analogous to setToolBar * (triggered by * Issue #499-swingx: old toolbar not removed on setting new). * * had not been broken. */ @Test public void testStatusBarSet() { JXRootPane rootPane = new JXRootPane(); JXStatusBar toolBar = new JXStatusBar(); rootPane.setStatusBar(toolBar); assertTrue(SwingUtilities.isDescendingFrom(toolBar, rootPane)); rootPane.setStatusBar(new JXStatusBar()); assertFalse(SwingUtilities.isDescendingFrom(toolBar, rootPane)); } /** * Test setStatusBar analogous to setToolBar * (triggered by * Issue #499-swingx: old toolbar not removed on setting new). * * Additional fix: rootPane must fire property change event on * setStatusBar. * */ @Test public void testStatusBarFirePropertyChange() { JXRootPane rootPane = new JXRootPane(); JXStatusBar toolBar = new JXStatusBar(); rootPane.setStatusBar(toolBar); assertTrue(SwingUtilities.isDescendingFrom(toolBar, rootPane)); PropertyChangeReport report = new PropertyChangeReport(); rootPane.addPropertyChangeListener(report); rootPane.setStatusBar(new JXStatusBar()); assertEquals("set statusBar must have fire exactly one property change", 1, report.getEventCount()); assertTrue(report.hasEvents("statusBar")); } /** * Issue #499-swingx: old toolbar not removed on setting new. * */ @Test public void testToolBarSet() { JXRootPane rootPane = new JXRootPane(); JToolBar toolBar = new JToolBar(); rootPane.setToolBar(toolBar); assertTrue(SwingUtilities.isDescendingFrom(toolBar, rootPane)); rootPane.setToolBar(new JToolBar()); assertFalse(SwingUtilities.isDescendingFrom(toolBar, rootPane)); } /** * Issue #499-swingx: old toolbar not removed on setting new. * * Additional fix: rootPane must fire property change event on * setToolBar. * * PENDING: similar issue with statusbar? */ @Test public void testToolBarFirePropertyChange() { JXRootPane rootPane = new JXRootPane(); JToolBar toolBar = new JToolBar(); rootPane.setToolBar(toolBar); assertTrue(SwingUtilities.isDescendingFrom(toolBar, rootPane)); PropertyChangeReport report = new PropertyChangeReport(); rootPane.addPropertyChangeListener(report); rootPane.setToolBar(new JToolBar()); assertEquals(1, report.getEventCount()); assertTrue(report.hasEvents("toolBar")); } /** * Issue #66-swingx: setStatusBar(null) throws NPE. * */ @Test public void testStatusBarNPE() { JXRootPane rootPane = new JXRootPane(); rootPane.setStatusBar(null); } public void interactiveTestStatusBar() { JXTable table = new JXTable(new DefaultTableModel(10, 3)); final JXFrame frame = wrapWithScrollingInFrame(table, "Statusbar"); Action action = new AbstractAction("toggle StatusBar") { public void actionPerformed(ActionEvent e) { JXStatusBar bar = frame.getRootPaneExt().getStatusBar(); frame.getRootPaneExt().setStatusBar(bar != null ? null : new JXStatusBar()); frame.getRootPaneExt().revalidate(); } }; addAction(frame, action); frame.setVisible(true); } public static void main(String args[]) { setSystemLF(true); JXRootPaneTest test = new JXRootPaneTest(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*ColumnControlColumnModel.*"); // test.runInteractiveTests("interactive.*TableHeader.*"); // test.runInteractiveTests("interactive.*Sort.*"); // test.runInteractiveTests("interactive.*ColumnControlAndF.*"); // test.runInteractiveTests("interactive.*RowHeight.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXHeaderVisualCheck.java0000644000175000017500000002543611210401722024340 0ustar tonytony/* * $Id: JXHeaderVisualCheck.java,v 1.11 2008/12/30 22:39:42 rah003 Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.AWTEventListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.SwingUtilities; import org.jdesktop.swingx.JXHeader.IconPosition; import org.jdesktop.swingx.test.XTestUtils; /** * Tests previously created to expose known issues of JXHeader, now fixed. * Still need visual inspection from time to time. *

* * @author Jeanette Winzenburg */ public class JXHeaderVisualCheck extends InteractiveTestCase { @SuppressWarnings("unused") private static final Logger LOG = Logger .getLogger(JXHeaderVisualCheck.class.getName()); public static void main(String args[]) { JXHeaderVisualCheck test = new JXHeaderVisualCheck(); try { test.runInteractiveTests("interactiveHTMLTextWrapLong"); // test.runInteractiveTests("interactive.*Label.*"); // test.runInteractiveTests("interactive.*Font.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } @Override protected void setUp() throws Exception { setSystemLF(true); } // ------------------ interactive public void interactiveHeaderInTabbedPane() { // Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() { // // public void eventDispatched(AWTEvent event) { // System.out.println("e:" + event); // }}, Long.MAX_VALUE); JTabbedPane pane = new JTabbedPane(); pane.addTab("first", createHeader()); pane.addTab("second", createHeader()); JXFrame frame = wrapInFrame(pane, "NPE: header in tabbedPane?"); addComponentOrientationToggle(frame); show(frame); } private JXHeader createHeader() { JXHeader header = new JXHeader(); header.setTitle("AlbumManager"); String headerLong = "An adaption from JGoodies Binding Tutorial in the context" + " of BeansBinding/AppFramework. " + "The Tabs show different styles of typical interaction " + "setups (in-place editing vs. dialog-editing). "; header.setDescription(headerLong); header.setIcon(XTestUtils.loadDefaultIcon()); return header; } /** * #647-swingx JXLabel looses html rendering on font change. */ public void interactiveFontLayoutReset() { JFrame f = new JFrame("Header Test - html lost on font change"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final JXHeader header = new JXHeader("My Title", "My short description
some text"); f.add(header, BorderLayout.CENTER); JButton changeFont = new JButton("Font"); f.add(changeFont, BorderLayout.SOUTH); changeFont.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { header.setFont(new Font("Tahoma", Font.PLAIN, 18)); } }); } }); f.setSize(400, 200); f.setVisible(true); } /** * Short description in header produces unexpected line wraps in * footer. * * Note: the frame is not packed to simulate the appframework * context. */ public void interactiveHTMLTextWrapShort() { JXHeader header = new JXHeader(); header.setTitle("AlbumManager"); String headerShort = "An adaption from JGoodies Binding Tutorial in the context" + " of BeansBinding/AppFramework. "; header.setDescription(headerShort); header.setIcon(XTestUtils.loadDefaultIcon()); JXHeader footer = new JXHeader(); footer.setTitle("Notes:"); String footerDescription = "" + "

    " + "
  • code: in the jdnc-incubator, section kleopatra, package appframework." + "
  • technique: back the view by a shared presentation model " + "
  • technique: veto selection change until editing is completed " + "
  • issue: selection of tab should be vetoable " + "
  • issue: empty selection should disable editing pane " + "
" + " "; footer.setDescription(footerDescription); JComponent panel = new JPanel(new BorderLayout()); panel.add(header, BorderLayout.NORTH); panel.add(footer, BorderLayout.SOUTH); JXFrame frame = new JXFrame("html wrapping in SOUTh: short text in NORTH"); frame.add(panel); frame.setSize(800, 400); frame.setVisible(true); } /** * Long description in header produces expected line-wrap in footer. * * Note: the frame is not packed to simulate the appframework * context. */ public void interactiveHTMLTextWrapLong() { // Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() { // // public void eventDispatched(AWTEvent event) { // if (event.getID() != MouseEvent.MOUSE_MOVED) { // System.out.println("e:" + event); // } // }}, Long.MAX_VALUE); JXHeader header = createHeader(); JXHeader footer = new JXHeader(); footer.setTitle("Notes:"); String footerDescription = "" + "
    " + "
  • code: in the jdnc-incubator, section kleopatra, package appframework." + "
  • technique: back the view by a shared presentation model " + "
  • technique: veto selection change until editing is completed " + "
  • issue: selection of tab should be vetoable " + "
  • issue: empty selection should disable editing pane " + "
" + " "; footer.setDescription(footerDescription); JComponent panel = new JPanel(new BorderLayout()); panel.add(header, BorderLayout.NORTH); // panel.add(new JScrollPane(table)); panel.add(footer, BorderLayout.SOUTH); // JXFrame frame = new JXFrame("html wrapping in SOUTH: long text in NORTH"); // frame.add(panel); JXFrame frame = wrapInFrame(panel, "html wrapping in SOUTH: long text in NORTH"); // addComponentOrientationToggle(frame); frame.setSize(800, 600); // show(frame); frame.setVisible(true); } /** * Issue #403-swingx: JXHeader doesn't show custom values. *

* * All values are passed in the constructor. */ public void interactiveCustomProperties() { Icon icon = XTestUtils.loadDefaultIcon(); assertNotNull("sanity: default icon loaded", icon); JPanel p = new JPanel(new BorderLayout()); JXHeader header = new JXHeader("MyTitle", "MyDescription", icon); header.setIconPosition(IconPosition.LEFT); JPanel px = new JPanel(new GridLayout(2,1)); px.add(header); px.add(new JXHeader("MyTitle", "MyDescription", icon)); p.add(px); // added just to better visualize bkg gradient in the JXHeader. p.add(new JLabel("Reference component: JLabel"), BorderLayout.SOUTH); p.add(new JXLabel("Reference component: JXLabel"), BorderLayout.NORTH); showInFrame(p, "JXHeader with custom properties"); } /** * Issue #469-swingx: JXHeader doesn't wrap words in description.

* Issue #634-swingx: JXHeader uses incorrect font for description.

* * All values are passed in the constructor. */ public void interactiveWordWrapping() { Icon icon = XTestUtils.loadDefaultIcon(); assertNotNull("sanity: default icon loaded", icon); JPanel p = new JPanel(new BorderLayout()); JXHeader header = new JXHeader("MyTitle", "this is a long test with veeeeeeeeeeeeeery looooooong wooooooooooooords", icon); p.add(header); p.setPreferredSize(new Dimension(200,150)); showInFrame(p, "word wrapping JXHeader"); } /** * Test custom title font and color use. * * All values are passed in the constructor. */ public void interactiveCustomTitleFont() { Icon icon = XTestUtils.loadDefaultIcon(); assertNotNull("sanity: default icon loaded", icon); JPanel p = new JPanel(new BorderLayout()); final JXHeader header = new JXHeader("MyBigUglyTitle", "this is a long test with veeeeeeeeeeeeeery looooooong wooooooooooooords", icon); header.setTitleFont(new Font("serif", Font.BOLD, 36)); header.setTitleForeground(Color.GREEN); p.add(header); p.setPreferredSize(new Dimension(400,150)); JXFrame frame = wrapInFrame(p, "Titlefont lost on updateUI / word wrapping JXHeader"); Action action = new AbstractAction("updateUI") { public void actionPerformed(ActionEvent e) { header.updateUI(); }}; addAction(frame, action); Action tree = new AbstractAction("updateComponentTree") { public void actionPerformed(ActionEvent e) { SwingUtilities.updateComponentTreeUI(header); }}; addAction(frame, tree); addMessage(frame, "title font set on header"); show(frame); } /** * Empty test method to keep the testrunner happy. */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/geom/0000755000175000017500000000000011210401734020641 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/geom/Morphing2DTest.java0000644000175000017500000000477411210401722024326 0ustar tonytonypackage org.jdesktop.swingx.geom; import java.awt.Rectangle; import java.awt.geom.AffineTransform; import java.awt.geom.Ellipse2D; import java.awt.geom.FlatteningPathIterator; import java.awt.geom.Point2D; import static org.junit.Assert.*; import org.junit.Test; import org.junit.Before; /** * Basic tests for Morphing2D * @author had * */ public class Morphing2DTest { Morphing2D morph ; @Before public void setUp() { morph= new Morphing2D(new Rectangle(0,0,50,50), new Ellipse2D.Double(50,50,50,50)); } @Test public void testGetBounds() { assertEquals(new Rectangle(0,0,50,50), morph.getBounds()); morph.setMorphing(.5); assertEquals(new Rectangle(25,25,50,50), morph.getBounds()); morph.setMorphing(1); assertEquals(new Rectangle(50,50,50,50), morph.getBounds()); } @Test public void testContains() { try { morph.contains(new Point2D.Double(5,5)); fail("when you implement this method, don't forget to add tests as well"); } catch (InternalError e) { // expected } try { morph.contains(new Rectangle(5,5,10,10)); fail("when you implement this method, don't forget to add tests as well"); } catch (InternalError e) { // expected } try { morph.contains(5,5,10,10); fail("when you implement this method, don't forget to add tests as well"); } catch (InternalError e) { // expected } try { morph.contains(5,5); fail("when you implement this method, don't forget to add tests as well"); } catch (InternalError e) { // expected } } @Test public void testIntersects() { try { morph.intersects(new Rectangle(5,5,10,10)); fail("when you implement this method, don't forget to add tests as well"); } catch (InternalError e) { // expected } try { morph.intersects(5,5,10,10); fail("when you implement this method, don't forget to add tests as well"); } catch (InternalError e) { // expected } } @Test public void testGetPathIterator() { assertFalse(morph.getPathIterator(AffineTransform.getRotateInstance(.5)) instanceof FlatteningPathIterator); assertTrue(morph.getPathIterator(AffineTransform.getRotateInstance(.5), .7) instanceof FlatteningPathIterator); } } swingx-1.0-src/src/test/org/jdesktop/swingx/geom/Star2DTest.java0000644000175000017500000000515611210401722023447 0ustar tonytonypackage org.jdesktop.swingx.geom; import static org.junit.Assert.*; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import javax.swing.JFrame; import org.jdesktop.swingx.JXPanel; import org.jdesktop.swingx.painter.AbstractPainter; import org.junit.Before; import org.junit.Test; public class Star2DTest { Star2D star; @Before public void setUp() { star = new Star2D(50,50,10,15,4); } /** * Visual check. Should paint star fully visibly at the right bottom corner. * @param args */ public static void main(String[] args) { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JXPanel p = new JXPanel(); p.setPreferredSize(new Dimension(65,65)); p.setBackgroundPainter(new AbstractPainter() { @Override protected void doPaint(Graphics2D g, Object object, int width, int height) { g.setColor(Color.RED); g.fill(new Star2D(50,50,10,15,16)); }}); f.add(p); f.pack(); f.setVisible(true); } @Test public void testGetBounds() { // [50,50] are the center coordinates. In no way they can be also x,y coords of the star bounds assertFalse(star.getBounds().x == 50); assertFalse(star.getBounds().y == 50); // 4 branch star with branches pointing to the corner of the bounding rect //assertEquals(new Rectangle(39,39,22,22), star.getBounds()); // 4 branch star with branches pointing horizontally and vertically assertEquals(new Rectangle(35,35,30,30), star.getBounds()); } @Test public void testContains() { assertTrue(star.contains(new Point2D.Double(50,50))); assertTrue(star.contains(new Rectangle(45,45,10,10))); assertTrue(star.contains(45,45,10,10)); assertTrue(star.contains(55,55)); } @Test public void testIntersects() { assertTrue(star.intersects(new Rectangle(25,25,50,50))); assertFalse(star.intersects(5,5,10,10)); } @Test public void testGetPathIterator() { assertNotNull(star.getPathIterator(AffineTransform.getRotateInstance(.5))); assertNotNull(star.getPathIterator(AffineTransform.getRotateInstance(.5), .7)); } @Test public void testGetters() { assertEquals(4, star.getBranchesCount()); assertEquals(10d, star.getInnerRadius(), .1); assertEquals(15d, star.getOuterRadius(), .1); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXMonthViewVisualTest.java0000644000175000017500000001510011210401724024757 0ustar tonytony/* * $Id: JXMonthViewVisualTest.java,v 1.7 2008/10/11 20:42:30 rah003 Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx; import java.awt.GraphicsEnvironment; import java.lang.reflect.InvocationTargetException; import java.util.Calendar; import java.util.Date; import java.util.logging.Logger; import javax.swing.SwingUtilities; import org.jdesktop.swingx.calendar.CalendarUtils; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * JXMonthView unit tests which are expected to pass and are part of a stable build. * * This one does not use mocks but some methods * of InteractiveTestCase. That's why the passing methods could not be moved * into JXMonthViewTest. * * @author Jeanette Winzenburg */ @RunWith(JUnit4.class) public class JXMonthViewVisualTest extends InteractiveTestCase { @SuppressWarnings("all") private static final Logger LOG = Logger.getLogger(JXMonthViewVisualTest.class .getName()); @SuppressWarnings("unused") private Calendar calendar; //---------------------- /** * Issue #659-swingx: lastDisplayedDate must be synched. * test that lastDisplayed from monthView is same as lastDisplayed from ui. * * Here: initial packed size - one month shown. * * @throws InvocationTargetException * @throws InterruptedException */ @Test public void testLastDisplayedDateInitial() throws InterruptedException, InvocationTargetException { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run lastDisplayedDate - headless"); return; } final JXMonthView monthView = new JXMonthView(); final JXFrame frame = wrapInFrame(monthView, ""); frame.setVisible(true); SwingUtilities.invokeAndWait(new Runnable() { public void run() { Date uiLast = monthView.getUI().getLastDisplayedDay(); Date viewLast = monthView.getLastDisplayedDay(); assertEquals(uiLast, viewLast); } }); } /** * * Issue #659-swingx: lastDisplayedDate must be synched. * * test that lastDisplayed from monthView is same as lastDisplayed from ui. * * Here: change the size of the view which allows the ui to display more * columns/rows. * * @throws InvocationTargetException * @throws InterruptedException */ @Test public void testLastDisplayedDateSizeChanged() throws InterruptedException, InvocationTargetException { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run lastDisplayedDate - headless"); return; } final JXMonthView monthView = new JXMonthView(); final JXFrame frame = wrapInFrame(monthView, ""); frame.setVisible(true); frame.setSize(frame.getWidth() * 3, frame.getHeight() * 2); // force a revalidate frame.invalidate(); frame.validate(); SwingUtilities.invokeAndWait(new Runnable() { public void run() { Date uiLast = monthView.getUI().getLastDisplayedDay(); Date viewLast = monthView.getLastDisplayedDay(); assertEquals(uiLast, viewLast); } }); } /** * * Issue #659-swingx: lastDisplayedDate must be synched. * * test that ensureDateVisible works as doc'ed if multiple months shown: * if the new date is in the * month following the last visible then the first must be set in a manner that * the date must be visible in the last month. * * @throws InvocationTargetException * @throws InterruptedException */ @Test public void testLastDisplayedDateSizeChangedEnsureVisible() throws InterruptedException, InvocationTargetException { if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run lastDisplayedDate - headless"); return; } final JXMonthView monthView = new JXMonthView(); final JXFrame frame = wrapInFrame(monthView, ""); frame.setVisible(true); frame.setSize(frame.getWidth() * 3, frame.getHeight() * 2); // force a revalidate frame.invalidate(); frame.validate(); SwingUtilities.invokeAndWait(new Runnable() { public void run() { Calendar calendar = Calendar.getInstance(); calendar.setTime(monthView.getFirstDisplayedDay()); int firstMonth = calendar.get(Calendar.MONTH); Date uiLast = monthView.getUI().getLastDisplayedDay(); calendar.setTime(uiLast); int lastMonth = calendar.get(Calendar.MONTH); // sanity: more than one month shown assertFalse(firstMonth == lastMonth); // first day of next month calendar.add(Calendar.DATE, 1); // sanity int newLastMonth = calendar.get(Calendar.MONTH); assertFalse(lastMonth == newLastMonth); monthView.ensureDateVisible(calendar.getTime()); CalendarUtils.endOfMonth(calendar); Date newUILast = monthView.getUI().getLastDisplayedDay(); assertEquals(newUILast, monthView.getLastDisplayedDay()); calendar.setTime(newUILast); // LOG.info("first/last: " + new Date(monthView.getFirstDisplayedDate()) + // "/" + new Date(newUILast)); assertEquals(newLastMonth, calendar.get(Calendar.MONTH)); } }); } @Override protected void setUp() throws Exception { calendar = Calendar.getInstance(); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXLabelVisualTest.java0000644000175000017500000000710711210401722024064 0ustar tonytonypackage org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.Icon; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.border.EmptyBorder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; @RunWith(JUnit4.class) public class JXLabelVisualTest extends InteractiveTestCase { public static void main(String[] args) throws Exception { // setSystemLF(true); JXLabelVisualTest test = new JXLabelVisualTest(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * #swingx-680 Preferred size is not set when label is rotated. */ public static void interactiveJXLabel() { JFrame testFrame = new JFrame("JXLabel Test"); testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JXLabel label = new JXLabel("This is some JXLabel text"); label.setTextRotation(Math.PI/4); testFrame.setContentPane(label); testFrame.pack(); testFrame.setLocationByPlatform(true); testFrame.setVisible(true); } /** * swingx-??? The text is wrapped 20px too wide causing horizontal slider of parent scroll pane to appear. * It seems that getVisibleRect() (called from renderer.getPreferredSpan) returns rectangle 20px too wide (width of left and right parent border) so it actually returns scroll panes visible rect rather then visible rect of the label embedded in jpanel with the border. */ public void interactiveLabelTextTooWide() { JFrame frame = new JFrame(); JPanel p = new JPanel(new BorderLayout()); p.setBorder(new EmptyBorder(10, 10, 10, 10)); JXLabel header = new JXLabel(); header.setLineWrap(true); header.setText("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed " + "do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut " + "enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi" + " ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit " + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur" + " sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt" + " mollit anim id est laborum."); Icon icon = new Icon(){ public int getIconHeight() { return 40; } public int getIconWidth() { return 80; } public void paintIcon(Component c, Graphics g, int x, int y) { g.setColor(Color.GREEN); g.fillRect(x, y, getIconWidth(), getIconHeight()); } }; header.setIcon(icon); header.setOpaque(true); p.add(header, BorderLayout.NORTH); p.setOpaque(true); p.setBackground(Color.red); JScrollPane sp = new JScrollPane(p); frame.add(sp); frame.setTitle(this.getClass().getSimpleName()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setPreferredSize(new Dimension(400, 300)); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } /** * Do nothing, make the test runner happy * (would output a warning without a test fixture). * */ @Test public void testDummy() { } }swingx-1.0-src/src/test/org/jdesktop/swingx/JXMultiSplitPaneUnitTest.java0000644000175000017500000000422611210401724025434 0ustar tonytony/** * */ package org.jdesktop.swingx; import java.awt.Component; import java.awt.Container; import java.lang.reflect.Field; import java.util.Map; import junit.framework.TestCase; import org.jdesktop.swingx.multisplitpane.DefaultSplitPaneModel; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * Submitted on the forums to test for a bug that was since fixed by Hans * Muller in {@code MultiSplitPaneLayout} version 1.4. * * @author Bruce Alspaugh */ @RunWith(JUnit4.class) public class JXMultiSplitPaneUnitTest extends TestCase { private JXMultiSplitPane multiSplitPane; @Before public void setUpJ4() throws Exception { setUp(); } @After public void tearDownJ4() throws Exception { tearDown(); } protected void setUp() throws Exception { DefaultSplitPaneModel model = new DefaultSplitPaneModel(); MultiSplitLayout layout = new MultiSplitLayout(model); multiSplitPane = new JXMultiSplitPane(); multiSplitPane.setLayout(layout); } @SuppressWarnings("unchecked") private Map getChildMap(MultiSplitLayout layout) { Field fields[] = MultiSplitLayout.class.getDeclaredFields(); try { for (Field f : fields) { if ("childMap".equals(f.getName())) { f.setAccessible(true); return (Map) f.get(layout); } } } catch (IllegalAccessException ex) { } return null; } @Test public final void testLayoutAddRemoveComponent() { Component testComponent = new Container(); MultiSplitLayout layout = multiSplitPane.getMultiSplitLayout(); Map childMap = getChildMap(layout); assertEquals(0, childMap.size()); layout.addLayoutComponent(DefaultSplitPaneModel.LEFT, testComponent); assertEquals(testComponent, childMap.get(DefaultSplitPaneModel.LEFT)); layout.removeLayoutComponent(testComponent); assertEquals(0, childMap.size()); } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXErrorPaneVisualCheck.java0000644000175000017500000000520311210401722025033 0ustar tonytony/* * $Id: JXErrorPaneVisualCheck.java,v 1.5 2008/03/26 18:11:29 rah003 Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx; import java.util.logging.Level; import org.jdesktop.swingx.error.ErrorInfo; /** * A unit test for the JXErrorPane * * @author rah003 */ public class JXErrorPaneVisualCheck extends InteractiveTestCase { public static void main(String[] args) throws Exception { JXErrorPaneVisualCheck test = new JXErrorPaneVisualCheck(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #45-swinglabs: JXErrorPane paints message text over action buttons * */ public void interactiveLongMessageText() { ErrorInfo errorInfo = new ErrorInfo("Server Error", "The request cannot be carried out\n1\n2\n3\n4\n5\n6\n7" + "\n8\n9\n0\n1\n2\n3\n4\nThis text should be shown in scroll pane.", "Server Error", null, new Exception(), Level.SEVERE, null); JXErrorPane.showDialog(null,errorInfo ); } /** * Issue #802-swingx: Default size is too small. */ public void interactiveTooSmall() { JXErrorPane.showDialog(null, new ErrorInfo("Title", "This is a test!", null, null, new Exception("This is a test!"), null, null)); } /** * Issue #468-swingx: JXErrorPane can't cope with null errorInfo. * */ public void interactiveNPEWithDefaultErrorInfo() { JXErrorPane errorPane = new JXErrorPane(); JXErrorPane.showDialog(null, errorPane); } /** * Issue #468-swingx: JXErrorPane can't cope with null errorInfo. * */ public void interactiveSetNullErrorInfo() { JXErrorPane errorPane = new JXErrorPane(); try { errorPane.setErrorInfo(null); fail("Failed to fail while setting null ErrorInfo"); } catch (NullPointerException e) { assertEquals("Unexpected error message", "ErrorInfo can\'t be null. Provide valid ErrorInfo object.", e.getMessage()); // ignore - expected. } } /** * Issue #467-swingx: calling updateUI throws error. * */ public void interactiveUpdateUI() { final JXErrorPane errorPane = new JXErrorPane(); errorPane.updateUI(); } /** * do nothing test - keep the testrunner happy. */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/JXPanelVisualCheck.java0000644000175000017500000000427211210401722024202 0ustar tonytony/* * $Id: JXPanelVisualCheck.java,v 1.3 2007/03/15 16:03:19 kleopatra Exp $ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx; import java.awt.Dimension; import javax.imageio.ImageIO; import org.jdesktop.swingx.painter.ImagePainter; /** * Contains methods to visually test JXPanel. * * @author Jeanette Winzenburg */ public class JXPanelVisualCheck extends InteractiveTestCase { public static void main(String args[]) { // setSystemLF(true); JXPanelVisualCheck test = new JXPanelVisualCheck(); try { test.runInteractiveTests(); // test.runInteractiveTests(".*List.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } public void interactiveIconPainter() throws Exception { ImagePainter imagePainter = new ImagePainter(ImageIO.read(JXPanel.class.getResource("resources/images/kleopatra.jpg"))); JXPanel panel = new JXPanel(); panel.setBackgroundPainter(imagePainter); // panel.setOpaque(false); panel.setPreferredSize(new Dimension(200, 200)); showWithScrollingInFrame(panel, "icon painter in jxpanel"); } /** * do-nothing method - suppress warning if there are no other * test fixtures to run. * */ public void testDummy() { } } swingx-1.0-src/src/test/org/jdesktop/swingx/resources/0000755000175000017500000000000011210401736021726 5ustar tonytonyswingx-1.0-src/src/test/org/jdesktop/swingx/resources/bugdata.txt0000644000175000017500000045627411210401722024113 0ustar tonytony4127936 4 5 null Fri Apr 10 14:12:00 PDT 1998 27 JTable Horizontal Scrollbar doesn't work committed 4833667 4 4 joutwate Mon Mar 17 15:32:00 PST 2003 0 Deiconizing a JInternalFrame with double-click moves focus evaluated 4419748 4 3 sdv@sparc.spb.su Tue Feb 27 17:47:00 PST 2001 5 JEditorPane CSS not supporting borders properly evaluated 4851246 4 4 joutwate Sun Apr 20 23:25:00 PDT 2003 0 RFE: Potential speed improvement in JProgressBar evaluated 4765280 4 5 shannonh Fri Oct 18 11:55:00 PDT 2002 0 RFE: Cannot drag out of a JFileChooser without first selecting a file accepted 4501166 4 4 kyuka Sun Sep 09 21:48:00 PDT 2001 1 Win32: JFileChooser doesn't display drives/volumes correctly in RtoL accepted 4845362 4 5 zpm@sparc.spb.su Tue Apr 08 18:44:00 PDT 2003 0 HTML renderer fails on empty cellpadding value and chars before title tag evaluated 4846388 3 3 bchristi Thu Apr 10 11:09:00 PDT 2003 1 XP JFileChooser shows gray smudge for "create folder" icon committed 4230443 4 5 kyuka Fri Apr 16 13:17:00 PDT 1999 1 ComponentOrientation has no effect on editable JComboBox accepted 4660820 4 3 dalem Mon Apr 01 00:24:00 PST 2002 0 JList does not show visual focus with initial Tab accepted 4263904 4 5 idk Thu Aug 19 10:41:00 PDT 1999 181 JTextPane: Paragraphs with Justified Attributes Appear Centered evaluated 4865510 4 4 leif Fri May 16 00:29:00 PDT 2003 0 Win L&F: JFileChooser: keyboard navigation is different evaluated 4826791 4 5 leif Mon Mar 03 21:22:00 PST 2003 0 Large font sizes not used in filedialog committed 4673852 4 3 naa@sparc.spb.su Wed Apr 24 11:31:00 PDT 2002 1 Entering HTML hard-break in JEditorPane does not update cursor correctly accepted 4850101 4 4 shannonh Thu Apr 17 10:49:00 PDT 2003 0 Setting mnemonic to VK_F4 underlines the letter S in a button. accepted 4776306 3 2 davidson@eng Fri Nov 08 00:52:00 PST 2002 0 property change-notification should lazily construct copies of properties committed 4406437 4 5 shannonh Fri Jan 19 15:17:00 PST 2001 0 JEditorPane.getEditorKit() should call kit.install() evaluated 4838135 4 4 davidson@eng Wed Mar 26 14:06:00 PST 2003 0 Request javax.swing.Action.MNEMONIC_INDEX_KEY committed 4837565 4 3 shannonh Tue Mar 25 17:15:00 PST 2003 0 Selection error by an empty JTable accepted 4853944 3 3 idk Thu Apr 24 21:25:00 PDT 2003 1 Images disappear in JEditorPane w/HTML evaluated 4766050 4 4 leif Mon Oct 21 00:14:00 PDT 2002 0 Look&Feel : Cannot select the other mode after selecting Windows. evaluated 4231307 4 5 joutwate Tue Apr 20 14:00:00 PDT 1999 3 JTabbedPane switching panel focus evaluated 4559032 4 4 leif Fri Dec 07 15:38:00 PST 2001 0 JFileChooser does not refresh directory listing when typing F5 evaluated 4765276 4 4 joutwate Fri Oct 18 11:53:00 PDT 2002 0 Keystroke lost after displaying dialog from InputVerifier accepted 4672878 4 4 sdv@sparc.spb.su Tue Apr 23 04:00:00 PDT 2002 0 Difference's found in t-bullets.PNG in AutoWeevil. evaluated 4833517 2 2 leif Mon Mar 17 11:37:00 PST 2003 0 GTK L&F: Support for general Metacity skins in XML committed 4758890 3 3 leif Mon Oct 07 10:32:00 PDT 2002 1 REGRESSION: Focus not painted in JToolBar with Windows PLAF evaluated 4781707 4 3 leif Wed Nov 20 05:33:00 PST 2002 0 JFileChooser must contain goto last folder option evaluated 4748359 4 4 shannonh Mon Sep 16 19:58:00 PDT 2002 3 Click in JTableHeader cancels Cell Editor changes evaluated 4825182 4 4 joutwate Thu Feb 27 14:17:00 PST 2003 0 DefaultBoundedRangeModel.setMinimum() changes extent unnecessarily evaluated 4126679 4 5 zpm@sparc.spb.su Tue Apr 07 16:31:00 PDT 1998 2 JRadioButtons with Icons don't size themselves correctly. evaluated 4417096 4 5 joutwate Tue Feb 20 14:24:00 PST 2001 1 JSlider: add label components to containment hierarchy evaluated 4822403 5 5 sky Fri Feb 21 17:34:00 PST 2003 0 RFE: Look and Feel classes are poorly designed and hostile to subclassing accepted 4295357 4 4 naoto Tue Nov 30 05:50:00 PST 1999 0 RTL only implicit, left aligned JTExtPane does not change text alignment accepted 4855256 4 5 sky Mon Apr 28 17:55:00 PDT 2003 0 RFE: JTree does not handle renaming its UserObject as well as other things accepted 4365538 4 1 null Thu Aug 24 13:15:00 PDT 2000 1 Use of deprecated Date constructor in JTable evaluated 4870636 5 5 joutwate Wed May 28 11:08:00 PDT 2003 0 RFE: Option to have close(x) button on JTabbedPane evaluated 4781716 3 2 leif Wed Nov 20 05:56:00 PST 2002 0 JFileChooser must respond as usual to floppy drive selection committed 4781696 4 3 joutwate Wed Nov 20 05:10:00 PST 2002 0 XP L&F: Scroll bars do not change color on mouse over evaluated 4144344 4 4 sky Mon Jun 01 08:46:00 PDT 1998 0 DefaultTreeCellEditor TextField should grow, in width, as necessary evaluated 4130798 4 5 shannonh Mon Apr 20 15:24:00 PDT 1998 0 MotifRadioButtonUI: paintFocus() method needs more careful logic evaluated 4515236 4 3 dalem Tue Oct 16 00:16:00 PDT 2001 4 DefaultTableColumnModel causes OOB exception when header row event triggered accepted 4765253 4 4 shannonh Fri Oct 18 11:34:00 PDT 2002 0 Method javax.swwing.JLabel.getPreferredSize() return wrong value! evaluated 4532590 4 4 zpm@sparc.spb.su Wed Nov 28 17:25:00 PST 2001 12 JTextPane jTextPane.setHighlighter(null) doesn't disable highlighter. accepted 4840405 5 5 joutwate Mon Mar 31 17:44:00 PST 2003 0 JInternalFrame does not animate maximize/minimize in Windows L&F evaluated 4724077 4 3 idk Wed Jul 31 16:54:00 PDT 2002 2 Problems with text where visual content doesn't start at model position 0 accepted 4327306 4 5 leif Mon Apr 03 13:42:00 PDT 2000 1 JFileChooser.setToolTipText() only partially effective accepted 4699955 4 3 sky Mon Jun 10 15:33:00 PDT 2002 2 JSpinner focusGained(...) listener does not allow selectAll functionality committed 4844444 4 4 shannonh Mon Apr 07 15:08:00 PDT 2003 1 Bluecurve theme is named Wonderland in some distributions committed 4230387 4 2 kyuka Fri Apr 16 11:25:00 PDT 1999 1 RFE: JProgressBar does not create international percent done strings evaluated 4788785 4 5 shannonh Wed Dec 04 18:00:00 PST 2002 0 OverlayLayout refuses to put a JPanel over a JSplitpane accepted 4871085 4 3 leif Thu May 29 01:44:00 PDT 2003 0 Tooltip for JInternalFrame behaves incorrectly dispatched 4713475 4 4 sky Thu Jul 11 11:11:00 PDT 2002 0 KeyListener pieces of BasicListUI should be made public or protected accepted 4286743 4 5 sky Mon Nov 01 00:56:00 PST 1999 2 Allow JScrollPane to setEnable(false) evaluated 4712086 4 5 leif Tue Jul 09 09:06:00 PDT 2002 0 JFileChooser: Home button inconsistencies in Metal Look and Feel evaluated 4304521 4 5 idk Thu Jan 13 09:56:00 PST 2000 11 Document with TabStop Attributes not written correctly into RTF File accepted 4164958 4 5 idk Mon Aug 10 06:41:00 PDT 1998 1 StyledEditorKit, RTFEditorKit and HTMLEditor missing fields evaluated 4869033 4 5 joutwate Fri May 23 00:14:00 PDT 2003 0 GTK L&F: Radio buttons don't look like native incomplete 4419012 4 5 leif Mon Feb 26 00:22:00 PST 2001 0 JToolBar buttons should have requestFocusEnabled = false evaluated 4683301 4 3 zav@sparc.spb.su Fri May 10 15:09:00 PDT 2002 0 BasicPopupMenuUI should use AWTEventListener vs MouseListeners on all components accepted 4724001 4 3 joutwate Wed Jul 31 15:19:00 PDT 2002 0 The private class Page in JTabbedPane prevents extendability accepted 4297788 4 5 naoto Wed Dec 08 10:35:00 PST 1999 3 Cursor loops in JTextArea when editing English text in RTL mode and vice versa evaluated 4339222 4 5 null Thu May 18 00:50:00 PDT 2000 0 System.out.println throws NullPointerException when toString() returns null evaluated 4254546 4 5 null Thu Jul 15 17:19:00 PDT 1999 0 Bizarre behavior when firing JTable update with bad values. evaluated 4692565 4 3 moa@sparc.spb.su Tue May 28 15:23:00 PDT 2002 0 TabbedPaneScrollLayout is private accepted 4844479 5 5 sky Mon Apr 07 15:52:00 PDT 2003 0 RFE: LinkLabel, similar to Label except it can display a hyperlink accepted 4759422 4 5 shannonh Mon Oct 07 20:35:00 PDT 2002 0 RFE: The anchor should not be the same as the focus in a JTable accepted 4799354 4 3 shannonh Mon Jan 06 16:15:00 PST 2003 0 In JLabel, etc., setText does not update properly with HTML object tag accepted 4760448 4 3 leif Wed Oct 09 10:11:00 PDT 2002 2 MetalFileChooserUI should allow user to bypass ShellFolder methods accepted 4871450 3 3 zav@sparc.spb.su Thu May 29 15:40:00 PDT 2003 0 Toggling of mnemonics visibility state inconsistent on WinXP platforms dispatched 4870112 4 3 zav@sparc.spb.su Tue May 27 14:44:00 PDT 2003 0 JMenu is not extensible dispatched 4425358 4 5 naa@sparc.spb.su Tue Mar 13 19:17:00 PST 2001 3 Reopen 4214992: JTextField Always Right-Justifies Oversized Strings accepted 4139692 4 5 joutwate Mon May 18 16:44:00 PDT 1998 245 JOptionPane.showInternalMessageDialog() does not create a modal dialog accepted 4723745 3 4 leif Wed Jul 31 11:56:00 PDT 2002 2 1.4 REGRESSION: Metal & Windows FileChooserUI classes cannot be used without She committed 4769783 4 4 sky Mon Oct 28 11:11:00 PST 2002 0 Adding a mouselistener to JScrollPanes viewport causes the pane to lose tooltip evaluated 4807159 4 5 sky Thu Jan 23 00:02:00 PST 2003 0 RFE: Bad implementation of constructor FontUIResource(Font font) accepted 4869098 5 5 sky Fri May 23 13:57:00 PDT 2003 0 GTK L&F: ColorChooser: Field/Spin Boxes Larger than platform version accepted 4859197 4 3 bchristi Tue May 06 14:16:00 PDT 2003 1 JFileChooser (WLF) line spacing too large in detailed view evaluated 4759090 4 4 joutwate Mon Oct 07 14:29:00 PDT 2002 0 RFE: Ability for Non-Standard JSlider tick placement accepted 4325865 4 4 naoto Tue Mar 28 23:54:00 PST 2000 0 Motif LAF, Cursor does not change direction when leaving RTL into LTR and vice v accepted 4179560 4 3 shannonh Wed Oct 07 13:16:00 PDT 1998 2 AbstractButton.setVerticalTextPosition mispositions text. evaluated 4722419 4 3 sky Mon Jul 29 15:22:00 PDT 2002 0 MaskFormatter should provide a minimum match length accepted 4801292 4 4 sky Thu Jan 09 18:36:00 PST 2003 0 Repainting errors in AbstractColorChooserPanel.updateChooser() committed 4203912 4 5 idk Mon Jan 18 17:22:00 PST 1999 88 JTextArea uses too much memory (if large byte array passed to cto= evaluated 4386259 4 4 null Mon Nov 06 05:05:00 PST 2000 2 JList, Spacebar functionality to select and deselect JList items is broken accepted 4510854 4 4 leif Thu Oct 04 10:33:00 PDT 2001 0 JColorChooser demo(SwingSet2) not getting painted well on WindowsXP platform. evaluated 4548788 5 3 sky Wed Dec 05 10:26:00 PST 2001 1 JTree should toggle for all even-numbered clicks evaluated 4624483 4 3 shannonh Wed Jan 16 08:52:00 PST 2002 10 JTable incorrectly consumes Esc key committed 4760407 4 5 idk Wed Oct 09 09:38:00 PDT 2002 0 WrappedPlainView should have selectors for (un)selected color committed 4811073 4 3 sky Thu Jan 30 20:34:00 PST 2003 0 GTK L&F quality evaluated 4410888 4 5 leif Thu Feb 01 00:45:00 PST 2001 0 TitledBorder spacing gaps should be adjustable (Bug and RFE) evaluated 4623272 5 5 joutwate Mon Jan 14 11:38:00 PST 2002 0 RFE: JTabbedPane: provide popup menu when scrollable tabs aren't shown. accepted 4788378 4 5 sky Wed Dec 04 10:09:00 PST 2002 0 JFormattedTextField should allow multiple formats to match accepted 4428752 4 2 sky Wed Mar 21 19:58:00 PST 2001 0 Apple Aqua: Need drawing bounds independent of layout bounds (outsets) evaluated 4269592 4 2 naoto Tue Sep 07 16:54:00 PDT 1999 0 SwingSet: Unexpected results when entering text with Right to Left Orientation accepted 4288630 4 3 zpm@sparc.spb.su Fri Nov 05 16:48:00 PST 1999 0 tooltip on tabbed panel prevents clicking on tab accepted 4835498 5 5 bchristi Thu Mar 20 15:01:00 PST 2003 0 JFileChooser/WinL&F:"My Computer" sidebar button should become deselected accepted 4855121 3 3 leif Mon Apr 28 15:21:00 PDT 2003 0 XP L&F: Table Header does not have rollover effect committed 4835466 5 5 bchristi Thu Mar 20 14:30:00 PST 2003 0 JFileChooser/Windows L&F: border drawn differently when renaming a file accepted 4808567 3 5 sky Mon Jan 27 10:45:00 PST 2003 2 RFE: Swing Windows L&F should honour desktop font smoothing settings. committed 4614616 4 4 dalem Mon Dec 17 11:55:00 PST 2001 1 Overriding getColumnClass in DefaultTableModel causes Exc if it return interface accepted 4615411 4 3 joutwate Tue Dec 18 00:58:00 PST 2001 4 REGRESSION: JOptionPane.showConfirmDialog has wrong focus accepted 4424160 4 5 leif Fri Mar 09 18:36:00 PST 2001 0 Floating toolbar unduly re-docked on uninstallUI evaluated 4307597 4 4 leif Thu Jan 27 02:56:00 PST 2000 9 Kestrel,FileChooser Warning Msg."No Disk In Drive" is not available in Win98/95 accepted 4865918 3 3 aep@sparc.spb.su Mon May 19 02:09:00 PDT 2003 0 REGRESSION: JCK1.4a-runtime api/javax_swing/interactive/JScrollBarTests.html#JSc evaluated 4741029 4 4 shannonh Tue Sep 03 16:50:00 PDT 2002 0 JTable: doesn't move the focus to all columns of selected region evaluated 4532517 4 5 joutwate Wed Nov 28 15:53:00 PST 2001 26 shouldYieldFocus does not allow side effects in 1.4 committed 4798817 4 3 leif Fri Jan 03 14:48:00 PST 2003 0 "My Documents" button is always selected when opening a JFileChooser in Win2K evaluated 4825416 4 5 leif Thu Feb 27 21:53:00 PST 2003 0 XP L&F: JToolBar grip is not centered evaluated 4804485 4 4 kyuka Thu Jan 16 15:41:00 PST 2003 1 TableColumnModel getColumnIndexAtX wrong value in RIGHT_TO_LEFT orientation committed 4760053 4 4 shannonh Tue Oct 08 17:09:00 PDT 2002 1 (MANDRAKE 8.1) Clipboard data provided in wrong format accepted 4664642 4 4 leif Mon Apr 08 15:25:00 PDT 2002 0 JToolBar should have the ability to allow them to only DOCK on certain sides accepted 4867054 4 4 leif Tue May 20 16:45:00 PDT 2003 0 Not following Windows XP style in Swing components committed 4358053 5 5 joutwate Mon Jul 31 16:46:00 PDT 2000 2 new ImageIcon(null,"someDescription") causes the image fetching thread to fail evaluated 4729632 4 5 idk Fri Aug 09 17:26:00 PDT 2002 0 RFE: Make javax.swing.text.html.FrameView public accepted 4735839 4 3 idk Thu Aug 22 19:44:00 PDT 2002 2 RTFEditorKit wrongly parses RTF while reading /writing to stream/document committed 4839739 3 2 idk Fri Mar 28 18:45:00 PST 2003 0 JEditorPane has 508 problems if there are comments in the HTML evaluated 4337584 4 4 leif Thu May 11 15:45:00 PDT 2000 4 general problems with JFileChooser and rfe's evaluated 4742686 4 4 leif Thu Sep 05 17:32:00 PDT 2002 4 1.4 REGRESSION: WindowsLookAndFeel not using control property evaluated 4428370 4 5 zav@sparc.spb.su Wed Mar 21 00:15:00 PST 2001 0 Problem using JMenu/JMenuItem's with Icon only evaluated 4799305 5 4 naa@sparc.spb.su Mon Jan 06 15:03:00 PST 2003 1 RFE: Decouple selection from cursor behaviour in javax.swing.text committed 4815339 4 3 kyuka Fri Feb 07 17:40:00 PST 2003 0 JComboBox drop-down list orientation is changed after the L&F is changed committed 4515838 4 3 zav@sparc.spb.su Wed Oct 17 00:44:00 PDT 2001 0 Can't change the border of a JComboBox committed 4751229 4 3 idk Fri Sep 20 18:03:00 PDT 2002 3 Iterator returned by HTMLDocument.getIterator() is incorrectly empty accepted 4133790 4 5 shannonh Wed Apr 29 18:27:00 PDT 1998 0 Motif L+F JCheckBoxMenuItems don't align the text properly evaluated 4765387 5 5 naa@sparc.spb.su Fri Oct 18 13:16:00 PDT 2002 1 Unexpected behaviour of HTMLEditorKit Class evaluated 4173836 4 5 zav@sparc.spb.su Tue Sep 15 11:57:00 PDT 1998 7 RFE: setListData in JComboBox committed 4628023 4 4 sky Thu Jan 24 00:26:00 PST 2002 1 Make treeNodesChanged indicate children may have been reordered accepted 4545951 4 3 joutwate Mon Dec 03 14:22:00 PST 2001 4 JOptionPane.showMessageDialog does not size dialog properly accepted 4733552 4 4 joutwate Mon Aug 19 15:01:00 PDT 2002 0 JScrollBar fires event for both mouse down and mouse up evaluated 4393423 3 5 shannonh Wed Nov 29 00:01:00 PST 2000 11 JTable.getSelectedRow incorrect with empty table, after ENTER is pressed. committed 4344938 4 5 leif Mon Jun 12 14:44:00 PDT 2000 0 Badly named classes accepted 4496323 4 4 zav@sparc.spb.su Fri Aug 24 15:00:00 PDT 2001 0 Metal L&F does not handle changing of JMenuBar objects accepted 4684090 4 3 shannonh Mon May 13 13:36:00 PDT 2002 10 Tab on editable JComboBox inside JTable transfers focus outside JTable accepted 4310381 4 4 moa@sparc.spb.su Sun Feb 06 18:51:00 PST 2000 1 Text in multi-row/col JTabbedPane tabs can be truncated/clipped committed 4865506 4 4 leif Fri May 16 00:27:00 PDT 2003 0 Win L&F: JFileChooser: Java version does not have go back (history) button evaluated 4465516 4 5 sky Sun Jun 03 16:16:00 PDT 2001 4 Need to suppress clipped text behavior evaluated 4424571 4 5 joutwate Mon Mar 12 13:27:00 PST 2001 0 JTable highlights incorrect row when using input verfier accepted 4696827 5 5 sky Tue Jun 04 08:53:00 PDT 2002 0 Investigate adding ComponentUI.getXXXSize(JComponent, Dimension) accepted 4870644 3 3 zav@sparc.spb.su Wed May 28 11:15:00 PDT 2003 0 Default button responds to CTRL-ENTER while popup menu is active. accepted 4505116 5 5 sky Thu Sep 20 10:57:00 PDT 2001 0 SpringLayout default behavior evaluated 4865853 3 3 leif Sun May 18 13:38:00 PDT 2003 0 JInternalFrame title bar does not scale to or ignore titleFont size with XP L&F committed 4851758 4 5 idk Mon Apr 21 20:16:00 PDT 2003 0 Uneditable text components should inherit their parent's cursor. evaluated 4765334 4 5 joutwate Fri Oct 18 00:33:00 PDT 2002 0 Desktop Icon for JInternalFrame goes behind an existing icon accepted 4870674 4 5 aep@sparc.spb.su Wed May 28 11:50:00 PDT 2003 0 JSplitPane's one-touch buttons should deal with resized split panes better dispatched 4423439 4 5 leif Thu Mar 08 14:03:00 PST 2001 8 JFileChooser - can't change the language other than the OS language accepted 4765327 5 5 sky Fri Oct 18 00:28:00 PDT 2002 1 RFE: There should be a isSingleSelectionEvent(MouseEvent) in BasicTreeUI accepted 4735546 3 3 shannonh Thu Aug 22 13:00:00 PDT 2002 0 NPE in BasicTableUI during Swing drag and drop evaluated 4861977 4 5 joutwate Fri May 09 17:10:00 PDT 2003 2 JOptionPane.showInternalConfirmDialog does not respect the JDesktopPane viewport evaluated 4809958 4 4 zav@sparc.spb.su Wed Jan 29 10:08:00 PST 2003 0 REGRESSION:overlappedByOwnedWindow() fails to check if windows are visible committed 4649181 3 3 joutwate Thu Mar 07 16:13:00 PST 2002 4 JFrames and JDialogs do not raise or resize properly in Linux committed 4458089 4 5 shannonh Sun May 13 18:29:00 PDT 2001 5 JOptionPane.setFont() does not affect font used by its message and buttons accepted 4836420 5 5 naa@sparc.spb.su Sun Mar 23 19:03:00 PST 2003 0 demo/jfc/Stylepad text properties should be 2-state controls accepted 4844503 5 5 zav@sparc.spb.su Mon Apr 07 16:23:00 PDT 2003 0 Swingset2: LAF reported incorrectly if changed using popup menu evaluated 4390321 4 3 leif Fri Nov 17 08:52:00 PST 2000 0 JFileChooser.setSelectedFile(File) method throws NPE committed 4487493 4 4 leif Thu Aug 02 00:05:00 PDT 2001 0 Merlinb73:FileChsrDemo:Folder icon Label inconsistent with Win2K native filedial evaluated 4848156 4 5 idk Mon Apr 14 15:35:00 PDT 2003 0 VerticalPageAction does not use Scrollable.getScrollableBlockIncrement() evaluated 4724980 3 3 shannonh Thu Aug 01 17:08:00 PDT 2002 14 JTable: Add API to control what happens to edits when table loses focus. evaluated 4469061 4 3 null Tue Jun 12 16:59:00 PDT 2001 0 TableColumnModel selection model and notification accepted 4521993 4 4 idk Thu Nov 01 13:50:00 PST 2001 2 JEditorPane will not allow pasting directly into a HTML Table cell accepted 4860722 4 5 leif Thu May 08 15:15:00 PDT 2003 0 Win L&F: Does not have resize graphic on bottom RH corner accepted 4836162 4 4 naa@sparc.spb.su Fri Mar 21 15:32:00 PST 2003 0 Selection and Caret are drawn incorrectly when JTextField is Scaled accepted 4626900 4 3 idk Tue Jan 22 17:12:00 PST 2002 1 StrikeThrough attribute not generated in document accepted 4799266 3 3 zav@sparc.spb.su Mon Jan 06 14:15:00 PST 2003 5 REGRESSION: JComboBox doesn't work in JPopupMenu evaluated 4767071 4 5 leif Tue Oct 22 19:02:00 PDT 2002 0 No Autocomplete for JFileChooser file selection using keyboard evaluated 4760436 4 5 shannonh Wed Oct 09 10:05:00 PDT 2002 0 ButtonGroup.getSelection() does not return a user-known ButtonModel. evaluated 4409239 4 5 null Mon Jan 29 11:34:00 PST 2001 8 Printing in JTable clips cell contents accepted 4856343 3 3 idk Wed Apr 30 10:31:00 PDT 2003 0 Problem with applet interaction with system selection clipboard evaluated 4130825 5 4 joutwate Mon Apr 20 15:51:00 PDT 1998 12 Cascade and Tile functionality missing from JDesktopPane evaluated 4634626 4 5 zav@sparc.spb.su Thu Feb 07 05:16:00 PST 2002 8 Implement context popup menus for components committed 4105948 4 5 joutwate Thu Jan 22 10:46:00 PST 1998 9 JOptionPane REALLY Needs Conditional Dismissal evaluated 4847362 4 3 leif Fri Apr 11 14:51:00 PDT 2003 0 Windows XP style L&F can paint two buttons as "rollover" committed 4347815 4 5 null Fri Jun 23 00:31:00 PDT 2000 21 JTable.setCellSelectionEnabled(boolean) implementation bug committed 4765240 3 3 zpm@sparc.spb.su Fri Oct 18 11:23:00 PDT 2002 2 Cannot paste from MS-Word into HTMLEditorKit evaluated 4337898 4 5 null Fri May 12 14:51:00 PDT 2000 0 Serializing DefaultTableCellRenderer changes colors. accepted 4759922 3 3 kve@sparc.spb.su Tue Oct 08 14:48:00 PDT 2002 0 JFileChooser.rescanCurrentDirectory() crashes with an AIOBE committed 4834298 4 5 leif Tue Mar 18 15:15:00 PST 2003 0 JFileChooser.getSelectedFiles() failed with multi-selection and double-click evaluated 4760088 4 5 sky Tue Oct 08 17:43:00 PDT 2002 0 JSpinner(or it's editor) does not fire KeyEvent accepted 4322989 4 5 leif Fri Mar 17 15:53:00 PST 2000 3 Need Directory Chooser dialog evaluated 4846692 5 5 kve@sparc.spb.su Thu Apr 10 15:49:00 PDT 2003 1 Problem displaying text of JOptionPane with Solaris 8 and OpenWindows Desktop evaluated 4424708 4 4 naa@sparc.spb.su Mon Mar 12 16:00:00 PST 2001 9 JPasswordField cursor placed incorrectly after setText("") evaluated 4819695 3 2 zav@sparc.spb.su Tue Feb 18 01:41:00 PST 2003 0 Regression javax/swing/JPopupMenu/PopupTest/PopupTester.java is failing evaluated 4192122 4 5 shannonh Mon Nov 23 05:55:00 PST 1998 1 Bottom of focus outline not drawn with Empty Border evaluated 4791070 4 3 kyuka Mon Dec 09 19:02:00 PST 2002 0 ComponentOrientation:JOptionPane's focus traversal does not respect RTL. committed 4490754 4 4 shannonh Fri Aug 10 00:44:00 PDT 2001 6 RFE: JTextField doesn't contain getActionCommand (only setActionCommand) evaluated 4820833 4 4 shannonh Wed Feb 19 15:21:00 PST 2003 0 JTable: Selection anchor (and lead) not updated when inserting or deleting rows. accepted 4760478 5 5 kve@sparc.spb.su Wed Oct 09 10:29:00 PDT 2002 0 JColorChooser construction is slow accepted 4478765 5 5 sky Wed Jul 11 14:34:00 PDT 2001 1 EOU: Make subclassing JViewport easier accepted 4503727 4 4 zav@sparc.spb.su Mon Sep 17 15:05:00 PDT 2001 8 RFE Use of Scroll carets on JMenu when they span beyond the depth of the screen evaluated 4841767 5 5 idk Wed Apr 02 15:06:00 PST 2003 1 Copy and Paste in JTextArea for unsigned Applet accepted 4871404 4 4 sky Thu May 29 14:50:00 PDT 2003 0 Swing JTable key bindings seem wrong (incomplete) accepted 4132585 5 5 zpm@sparc.spb.su Fri Apr 24 17:51:00 PDT 1998 0 JButtons have ugly Frames when changing Background evaluated 4510123 3 2 zpm@sparc.spb.su Tue Oct 02 20:50:00 PDT 2001 0 JTextArea.setWrapStyleWord() cannot handle the composed string properly evaluated 4232637 4 3 joutwate Fri Apr 23 17:43:00 PDT 1999 1 Can not use requestDefaultFocus with CardLayout JPanel to set a focus accepted 4140209 4 5 joutwate Tue May 19 17:31:00 PDT 1998 1 Regarding Swing Demo as an applet. Applet does not have the focus at start up. evaluated 4768338 4 3 zav@sparc.spb.su Thu Oct 24 00:51:00 PDT 2002 0 Height of JMenuBar not adjusted when wrapping occurs committed 4454866 4 5 joutwate Fri May 04 17:22:00 PDT 2001 0 internal frames leave garbage behind when dragged over edge in multimon (win32) evaluated 4686138 3 2 sky Thu May 16 00:44:00 PDT 2002 0 1.4 REGRESSION: Letter like (y,g) truncated in TableCellEditor, char '_' not vsb committed 4322996 4 5 zav@sparc.spb.su Fri Mar 17 16:08:00 PST 2000 3 Add BasicComboBoxEditor constructor that accepts a JTextField evaluated 4133141 4 5 davidson@eng Tue Apr 28 11:32:00 PDT 1998 26 Extend Action interface to handle toggles committed 4807140 3 3 joutwate Thu Jan 23 11:37:00 PST 2003 0 Bug ID:4221012 is not fixed for MotifLookAndFeel committed 4765300 3 3 sky Fri Oct 18 00:10:00 PDT 2002 5 Use of JSpinners w/JTables & losing focus doesn't commit, but is supposed to committed 4765309 5 5 joutwate Fri Oct 18 00:15:00 PDT 2002 0 JSlider.setForeground has no visible effect when L&F set to Windows accepted 4401437 4 4 leif Wed Jan 03 11:12:00 PST 2001 0 JFileChooser doesn't validate [characters in] filenames accepted 4843244 4 3 sky Fri Apr 04 15:03:00 PST 2003 3 GTK L&F : Galaxy engine is not supported accepted 4676022 4 3 sky Fri Apr 26 19:25:00 PDT 2002 1 commitEdit() on JFormattedTextField changes Value type accepted 4768318 4 4 leif Thu Oct 24 00:32:00 PDT 2002 1 JFileChooser.setApproveButtonMnemonic() doesn't work evaluated 4853783 4 5 sky Thu Apr 24 17:29:00 PDT 2003 0 SwingSet2 as an applet deadlocks on startup on Solaris accepted 4305614 5 5 sky Wed Jan 19 10:10:00 PST 2000 1 RepaintManager should maintain Window mapping too evaluated 4687405 4 3 idk Fri May 17 15:21:00 PDT 2002 0 HTMLDocument defaultRoot inserts extra paragraph tag accepted 4449310 4 5 leif Mon Apr 23 11:01:00 PDT 2001 0 Accelerator not displayed in HTML tool tip (Metal L&F) evaluated 4421177 4 4 shannonh Fri Mar 02 00:45:00 PST 2001 0 SwingSet2: JTable headers do not update with L&F change accepted 4634555 4 1 shannonh Thu Feb 07 00:52:00 PST 2002 0 Can't reorder or resize JTable columns from the keyboard evaluated 4203754 4 5 joutwate Sun Jan 17 19:36:00 PST 1999 0 Labels in a JSlider don't diable or enable with the slider evaluated 4189224 4 5 null Wed Nov 11 15:13:00 PST 1998 7 BoxLayout constructor - why it needs Container as parameter? evaluated 4799919 5 4 moa@sparc.spb.su Tue Jan 07 17:47:00 PST 2003 0 RFE: Make BasicTabbedPaneUI.requestFocusForVisibleComponent protected committed 4850475 3 3 idk Thu Apr 17 19:02:00 PDT 2003 1 REGRESSION: PlainDocument with textfield (i.e., custom maskfield) doesn't work evaluated 4284162 4 3 sdv@sparc.spb.su Fri Oct 22 17:28:00 PDT 1999 4 add support for the css text-indent attribute evaluated 4869215 4 3 sky Fri May 23 16:28:00 PDT 2003 0 GTK L&F: Application Icons as well as stock icons need to respond to theme chan accepted 4789491 3 2 sharonz Thu Dec 05 16:57:00 PST 2002 0 JFileChooser, how to make it select directories? committed 4154409 4 4 joutwate Thu Jul 02 15:08:00 PDT 1998 0 Solaris: initial focus is not set to any focusable subcomponent. evaluated 4860128 3 3 aep@sparc.spb.su Wed May 07 18:38:00 PDT 2003 0 REGRESSION: JTree does not paint "focused" node correctly, yellow border missing evaluated 4865499 4 4 leif Fri May 16 00:24:00 PDT 2003 0 Win L&F: JFileChooser: Context Help not consistent with XP evaluated 4624680 5 5 sky Wed Jan 16 14:14:00 PST 2002 0 Useless error reporting from UIDefaults.getUI and undoc'd null return accepted 4818934 3 3 idk Fri Feb 14 13:14:00 PST 2003 0 Excessive painting in text components when editing evaluated 4870281 2 2 idk Tue May 27 18:17:00 PDT 2003 0 nsk test nsk/stress/jck12a/jck12a017 hangs with tiger rt_baseline accepted 4703711 4 4 shannonh Tue Jun 18 04:10:00 PDT 2002 0 RFE: Need JOptionPane.WORKING_MESSAGE message type evaluated 4839061 4 5 shannonh Thu Mar 27 17:36:00 PST 2003 0 no JTable renderer support for primitive type wrappers evaluated 4338140 4 5 null Mon May 15 11:02:00 PDT 2000 2 DefaultListSelectionModel.insertIndexInterval() should update lead/anchorIndex. evaluated 4288818 4 4 sherman@japan Mon Nov 08 00:39:00 PST 1999 0 JEditorPane has strange characters in Chinese Windows 98 accepted 4521954 4 3 naa@sparc.spb.su Thu Nov 01 00:55:00 PST 2001 0 Text selection via double click should optionally highlight trailing space evaluated 4861684 4 3 sky Fri May 09 11:49:00 PDT 2003 0 Using new release, my application turns strange colors. incomplete 4408327 4 5 leif Thu Jan 25 14:21:00 PST 2001 2 "Drive Empty" dialog not getting disposed on clicking "Ignore" or "Abort buttons accepted 4260730 4 5 leif Sat Aug 07 14:37:00 PDT 1999 0 MetalFileChooserUI can't override private createSingleClickListener evaluated 4223515 4 4 shannonh Wed Mar 24 09:51:00 PST 1999 0 Add subimage capability to ImageIcon to allow use of image sheets evaluated 4222821 4 4 joutwate Mon Mar 22 18:01:00 PST 1999 11 Iconifying a JInternalFrame causes its GlassPane to lose state accepted 4701238 3 3 naoto Wed Jun 12 00:39:00 PDT 2002 25 REGRESSION: Bidirectional text not working in JTextComponents committed 4694944 3 3 leif Thu May 30 18:59:00 PDT 2002 14 1.4 REGRESSION: JFileChooser no longer works for virtual filesystems committed 4765314 5 5 sky Fri Oct 18 00:19:00 PDT 2002 1 JWindow behaves differently than JWindow accepted 4854803 4 3 shannonh Mon Apr 28 06:13:00 PDT 2003 0 Resize cursor shown all over the table header in some cases accepted 4846272 4 5 leif Thu Apr 10 07:38:00 PDT 2003 0 Focus lost from Windows LAF JFileChooser on changing to Windows HighContrast set evaluated 4765286 4 5 sky Fri Oct 18 11:59:00 PDT 2002 0 JTree keep on calling TreeModel.getChild() accepted 4677184 4 4 zav@sparc.spb.su Tue Apr 30 10:14:00 PDT 2002 0 RFE: JMenu.setMenuLocation(int x, int y) should accept Point arg evaluated 4465792 4 4 null Mon Jun 04 10:54:00 PDT 2001 0 javax.swing.JTable.isColumnSelected() does not throw IAE accepted 4710695 4 5 zav@sparc.spb.su Wed Jul 03 04:10:00 PDT 2002 1 JMenu focus listener change from 1.3 to 1.4 accepted 4811071 3 3 sky Thu Jan 30 20:30:00 PST 2003 0 Gnome L&F / Windowmanager Support committed 4158988 4 5 joutwate Mon Jul 20 16:48:00 PDT 1998 25 2-click on upper left corner can't close JInternalFrame evaluated 4860674 4 5 leif Thu May 08 14:25:00 PDT 2003 0 XP L&F: Some components not updating correctly when switching theme committed 4639981 4 5 sky Tue Feb 19 16:42:00 PST 2002 0 Cannot set button as default until it has been added to root pane accepted 4765379 5 5 shannonh Fri Oct 18 13:11:00 PDT 2002 0 Lack of support for event generation from JTable cell selection accepted 4692568 4 3 leif Tue May 28 15:23:00 PDT 2002 0 The Cancel button on JFileChooser shouldn't have an access key Alt-C. evaluated 4726740 4 5 kyuka Tue Aug 06 00:04:00 PDT 2002 0 JTabbedPane(SCROLL_TAB_LAYOUT) doesn't work properly in right-to-left mode. committed 4725009 3 3 shannonh Thu Aug 01 17:42:00 PDT 2002 0 1.4.0 REGRESSION: Moving last column of JTable causes invalid selection events committed 4795415 3 2 joutwate Tue Dec 17 20:22:00 PST 2002 0 GTK+ L&F bugs uncovered with special BSOD test theme committed 4622863 4 5 idk Fri Jan 11 17:57:00 PST 2002 1 Improve performance of Swing HTML renderer committed 4780662 4 4 kyuka Mon Nov 18 15:17:00 PST 2002 0 Motif L&F:the image icon is on the left side of JOptionPane when the RTL is set committed 4842577 5 5 leif Thu Apr 03 16:25:00 PST 2003 0 JFileChooser does not immediately clear the file list upon change of directory accepted 4765282 5 5 joutwate Fri Oct 18 11:56:00 PDT 2002 1 Scrollbars for JScrollPane receive focus when used with JTextArea accepted 4855133 3 3 leif Mon Apr 28 15:29:00 PDT 2003 0 XP L&F: Checkbox should not be surrounded by dashed box with focus incomplete 4337600 5 5 leif Thu May 11 16:19:00 PDT 2000 0 JCheckBoxMenuItem Documentation for Key Assignments in Incomplete evaluated 4812854 5 5 sky Tue Feb 04 15:28:00 PST 2003 0 Image component for displaying/resizing images accepted 4240860 4 4 zpm@sparc.spb.su Mon May 24 19:09:00 PDT 1999 0 JToolBar.ActionChangedListener not persistant accepted 4855867 4 5 idk Tue Apr 29 15:43:00 PDT 2003 0 DefaultCaret does not use TransferHandler when exporting selected text evaluated 4801246 4 4 sky Thu Jan 09 17:37:00 PST 2003 2 JTree should fire selection change notice on mouse up evaluated 4810151 3 3 leif Wed Jan 29 14:54:00 PST 2003 0 JFileChooser details view uses wrong (possibly unreadable) text color evaluated 4416811 4 5 zpm@sparc.spb.su Mon Feb 19 17:02:00 PST 2001 1 getToolTipText(MouseEvent event) of JComboBox is never called accepted 4484778 4 4 naa@sparc.spb.su Thu Jul 26 00:16:00 PDT 2001 1 HTMLWriter fails to write out object tag correctly accepted 4847375 4 4 bchristi Fri Apr 11 15:05:00 PDT 2003 5 JFileChooser Create New Folder button is disabled incorrectly committed 4708978 4 4 sky Thu Jun 27 09:32:00 PDT 2002 0 Ability for parent Containers *Listeners to be notified even if event consumed accepted 4841152 4 3 idk Tue Apr 01 17:09:00 PST 2003 0 StyleConstants/JTextPane should support the Default alignment to support Locale accepted 4298777 4 5 leif Sun Dec 12 11:52:00 PST 1999 1 JFileChooser's behaviour on Win95 (win32) accepted 4222508 4 3 davidson@eng Mon Mar 22 09:19:00 PST 1999 1 JColorChooser ignores setEnabled() function call accepted 4408424 4 5 null Thu Jan 25 17:00:00 PST 2001 0 getLocation() and getLocationOnScreen() broken for JTableHeader children accepted 4197909 4 3 shannonh Wed Dec 16 10:01:00 PST 1998 1 Support drag selection of ranges in lists. evaluated 4713930 4 5 shannonh Fri Jul 12 02:59:00 PDT 2002 0 Swing: setMultiClickThreshhold issue, related to bug 4367718 evaluated 4835791 4 5 joutwate Fri Mar 21 02:55:00 PST 2003 0 demo/jfc/SwingSet2 doesn't work as expected evaluated 4870187 4 4 shannonh Tue May 27 15:56:00 PDT 2003 0 RFE: customize JLabel text-truncation property evaluated 4848179 4 5 idk Mon Apr 14 16:00:00 PDT 2003 1 If all children are removed from javax.swing.text.View no new child can be added evaluated 4813436 4 5 kwalrath Wed Feb 05 00:01:00 PST 2003 1 JOptionPane.showOptionDialog does not return if "options" is JButton[] evaluated 4311584 4 5 idk Thu Feb 10 11:46:00 PST 2000 1 Scrolling on hsviewer using arrow keys is slow (2 - 3s until scrolling begins) accepted 4492274 4 3 sdv@sparc.spb.su Wed Aug 15 10:33:00 PDT 2001 6 JEditorPane.setPage(URL)-the URL treated as immutable object evaluated 4154399 4 4 joutwate Thu Jul 02 14:56:00 PDT 1998 5 Initial focus is not set to the "first" focusable component. evaluated 4700643 4 3 null Tue Jun 11 14:17:00 PDT 2002 6 JTable selection misbehaves when a row is inserted at position 0 accepted 4140481 4 5 shannonh Wed May 20 00:38:00 PDT 1998 9 BoxLayout Not sizing or aligning correctly committed 4625667 4 5 joutwate Fri Jan 18 02:33:00 PST 2002 5 Strange FOCUS_GAINED event is sent to application accepted 4403550 4 5 shannonh Wed Jan 10 11:59:00 PST 2001 6 JTextField.setVisible(boolean b) does not work correctly. evaluated 4809663 4 4 shannonh Tue Jan 28 18:21:00 PST 2003 0 RFE: JOptionPane with Yes-Yes to all-No-No to all-Cancel evaluated 4474804 4 4 joutwate Tue Jun 26 14:35:00 PDT 2001 0 JInternalFrames size with both mouse buttons evaluated 4686092 4 4 aep@sparc.spb.su Wed May 15 20:37:00 PDT 2002 0 SwingSet2 Content Alignment feature not working in Hopper 1.4.1-B11 committed 4391936 4 4 null Wed Nov 22 13:11:00 PST 2000 1 Swing's text measurement should not use Toolkit font metrics accepted 4760482 4 4 joutwate Wed Oct 09 10:31:00 PDT 2002 0 Maximized JInternalFrames in Windows LaF get bogus activated events accepted 4769772 4 4 joutwate Mon Oct 28 11:01:00 PST 2002 2 JInternalFrame.setIcon(true) before JDesktopPane.add(JIF) causes wrong state evaluated 4761990 3 3 naa@sparc.spb.su Fri Oct 11 00:00:00 PDT 2002 4 1.4 REGRESSION: Highlighting Color Behavior has changed committed 4231737 4 5 shannonh Wed Apr 21 00:56:00 PDT 1999 0 JDialogs not placed correctly when invoked from JPopups accepted 4774166 4 3 joutwate Tue Nov 05 14:52:00 PST 2002 0 InputVerifier not called after a window loses then regains focus committed 4790683 4 4 idk Mon Dec 09 11:11:00 PST 2002 1 JPasswordField should have a char[] constructor committed 4592902 4 4 leif Tue Dec 11 10:41:00 PST 2001 0 tooltips do not immediately hide when moving out of window accepted 4442981 4 3 kve@sparc.spb.su Thu Apr 12 17:38:00 PDT 2001 0 Win2000/XP L&F: Resizing JFileChooser: Does not have a minimum limit evaluated 4871932 4 4 shannonh Fri May 30 00:26:00 PDT 2003 0 MouseMotionListener on JTable disappears when Look And Feel (LAF) changes dispatched 4141524 4 2 sky Fri May 22 18:44:00 PDT 1998 2 UndoManager doesn't help you keep your GUI up to date evaluated 4871936 4 4 sky Fri May 30 00:30:00 PDT 2003 0 RFE: provide a JFontChooser accepted 4782243 4 4 leif Wed Nov 20 17:33:00 PST 2002 0 setVisible on JToolBar does not hide the floating window evaluated 4336757 5 5 joutwate Tue May 09 13:32:00 PDT 2000 0 Regression 1.2.2 to 1.3: was setPreviousBounds() is now setNormalBounds() evaluated 4181978 4 4 sharonz Fri Oct 16 03:59:00 PDT 1998 0 There is no spec for DebugGraphics draw methods accepted 4838730 3 3 idk Thu Mar 27 11:03:00 PST 2003 1 REGRESSION: In JTextArea setEditable(...) breaks focus traversal keys evaluated 4777616 3 4 joutwate Tue Nov 12 00:50:00 PST 2002 0 setDefaultLookAndFeelDecorated(true) and Java Web Start don't mix well committed 4765362 5 5 shannonh Fri Oct 18 00:54:00 PDT 2002 0 SetFont() in DefaultTableCellRenderer doesn't work accepted 4851010 4 4 idk Fri Apr 18 16:37:00 PDT 2003 0 RFE: In ComponentView.java, please change setComponentParent to public final accepted 4811015 5 5 davidson@eng Thu Jan 30 19:42:00 PST 2003 0 Reopen 4528403: JList checks ListModel equality incorrectly accepted 4252173 4 4 davidson@eng Wed Jul 07 11:22:00 PDT 1999 0 Inability to reuse the HorizontalSliderThumbIcon evaluated 4292346 4 5 joutwate Wed Nov 17 11:52:00 PST 1999 5 loading animated gifs throws mediaTracker.ABORTED error evaluated 4331767 4 5 sky Wed Apr 19 14:12:00 PDT 2000 1 Can't make swing use your own UIDefaults class to override getUIError evaluated 4203039 3 5 leif Thu Jan 14 06:19:00 PST 1999 2 JToolBar needs API to limit docking to a particular orientation committed 4870668 5 5 joutwate Wed May 28 11:44:00 PDT 2003 0 RFE: Refactor MetalRootPaneUI to be more flexible accepted 4501171 4 5 leif Sun Sep 09 23:33:00 PDT 2001 0 setHolizontalAlignment() in Windows L&F JFileChooser doesn't work. accepted 4403207 4 4 leif Tue Jan 09 14:40:00 PST 2001 0 setFont does not work for JFileChooser accepted 4782077 4 5 naa@sparc.spb.su Wed Nov 20 14:37:00 PST 2002 1 CTRL-H menu item accelerator also causes text removal with text components committed 4466930 4 3 null Wed Jun 06 15:26:00 PDT 2001 0 JTable.selectAll boundary handling accepted 4850092 3 3 leif Thu Apr 17 10:24:00 PDT 2003 0 REGRESSION: call to updateUI() on a JButton changes the size of the button committed 4647551 3 3 joutwate Tue Mar 05 14:26:00 PST 2002 7 REGRESSION: KeyListener for JFrame doesn't work after click in JInternalFrame committed 4614926 4 5 null Mon Dec 17 16:46:00 PST 2001 7 Native rendering into Swing components committed 4282679 4 3 idk Tue Oct 19 15:22:00 PDT 1999 0 JEditorPane: Using different style tags is producing weird results evaluated 4763807 4 3 zav@sparc.spb.su Wed Oct 16 09:25:00 PDT 2002 1 JComboBox does not fire any mouse events with Metal L&F accepted 4716484 4 4 aim Wed Jul 17 17:31:00 PDT 2002 1 Swing classes don't use getBorderInsets(Component,Insets) to save on object inst committed 4346610 4 5 leif Mon Jun 19 16:42:00 PDT 2000 3 Adding JSeparator to JToolBar "pushes" buttons added after separator to edge evaluated 4480696 5 5 leif Tue Jul 17 10:57:00 PDT 2001 2 Comments On The Swing GUI MS Windows accepted 4753342 4 4 sky Wed Sep 25 15:40:00 PDT 2002 0 JFrame, JWindow and JDialog should redirect add/remove methods to ContentPane accepted 4822127 4 3 leif Fri Feb 21 00:18:00 PST 2003 0 misc swing problems with WinXP L&F evaluated 4800753 3 4 leif Thu Jan 09 03:38:00 PST 2003 0 Missing generic way to change ToolTipManagers and also the shared instance. accepted 4801190 4 5 kve@sparc.spb.su Thu Jan 09 16:05:00 PST 2003 2 JFileChooser does not show registered extensions under Windows with Metal evaluated 4337815 4 2 idk Fri May 12 11:06:00 PDT 2000 0 Make the constructor of javax.swing.text.html.StyleSheet.ListPainter public evaluated 4469678 5 4 leif Wed Jun 13 17:25:00 PDT 2001 0 JFileChooser's new default layout breaks application that works in JDK1.3 accepted 4705104 3 4 idk Thu Jun 20 02:03:00 PDT 2002 3 Notepad hangs up when open uigur text in gb18030 locale. committed 4525475 4 3 leif Fri Nov 09 00:45:00 PST 2001 1 Cannot prevent file-system modification in JFileChooser evaluated 4795413 3 2 joutwate Tue Dec 17 20:07:00 PST 2002 0 GTK+ L&F not fully reflecting GNOME High contrast large print theme committed 4623275 5 5 moa@sparc.spb.su Mon Jan 14 11:44:00 PST 2002 3 RFE: JTabbedPane: Provide option to display tab names vertically accepted 4819544 4 5 joutwate Mon Feb 17 10:32:00 PST 2003 0 SwingSet2 JTable Demo throws NullPointerException evaluated 4592978 4 4 dalem Tue Dec 11 13:03:00 PST 2001 0 The ScrollBar Up Button can't bring you completely up if JList has a border accepted 4618607 5 5 zpm@sparc.spb.su Wed Jan 02 11:16:00 PST 2002 7 RFE: Popups for narrow JComboBox are too narrow accepted 4847161 3 3 zav@sparc.spb.su Fri Apr 11 10:30:00 PDT 2003 0 REGRESSION: RegTest-cte CTE_REGTEST/Generic/4683300/Test4683300.java failed committed 4199622 4 5 zav@sparc.spb.su Wed Dec 23 11:54:00 PST 1998 26 RFE: JComboBox shouldn't sending ActionEvents for keyboard navigation committed 4515765 4 4 leif Wed Oct 17 11:04:00 PDT 2001 0 Win L&F: Disabled menu items should show highlight committed 4710678 4 5 sky Wed Jul 03 03:15:00 PDT 2002 0 SwingApplet demo does not print properly accepted 4858524 4 3 aep@sparc.spb.su Mon May 05 13:02:00 PDT 2003 1 JSpinner does not respect editor (JFormattedTextField) margin evaluated 4528786 4 3 idk Sat Nov 17 16:19:00 PST 2001 0 Can't write "^" in Swing GUI Components with Swedish keyboard accepted 4830695 4 3 shannonh Tue Mar 11 14:49:00 PST 2003 0 Require ability to add data import ability on top of existing TransferHandler accepted 4485588 4 3 joutwate Fri Jul 27 17:31:00 PDT 2001 2 default button characteristics are lost for multiple internal frames evaluated 4778542 4 4 shannonh Wed Nov 13 17:48:00 PST 2002 0 property "terminateEditOnFocusLost" results in distorted cell when editing table committed 4744971 4 4 leif Tue Sep 10 15:25:00 PDT 2002 1 ToolTips not changing when JTable cells have same Tooltip Text evaluated 4486794 4 4 idk Wed Aug 01 05:48:00 PDT 2001 5 "ctrl+shft+o" causes textcomponent crash after Inserting numbers and spaces evaluated 4265389 4 4 kyuka Tue Aug 24 16:28:00 PDT 1999 0 JSplitPane does not support ComponentOrientation committed 4138768 4 5 zav@sparc.spb.su Thu May 14 17:41:00 PDT 1998 0 JMenuItem: Setting Mnemonic to VK_HELP displays as "help" evaluated 4503816 4 3 joutwate Mon Sep 17 16:40:00 PDT 2001 4 setNextFocusableComponent no longer backward compatible accepted 4623505 4 3 dalem Mon Jan 14 16:44:00 PST 2002 3 ArrayIndexOutOfBoundsException due to bad update in DefaultListSelectionModel accepted 4189256 4 5 joutwate Wed Nov 11 16:02:00 PST 1998 1 JDesktopPane disregards opacity setting evaluated 4795987 4 5 shannonh Wed Dec 18 16:58:00 PST 2002 1 DefaultTableCellRenderer does not honor 'isEnabled' accepted 4850450 4 5 sky Thu Apr 17 18:26:00 PDT 2003 0 Inconsistent JFormattedTextField selection behavior at FocusGained accepted 4501167 4 3 leif Sun Sep 09 21:58:00 PDT 2001 0 Arabic date string displayed in a wrong format in JFileChooser accepted 4848868 4 5 idk Tue Apr 15 15:19:00 PDT 2003 0 BoxLayout expands components with HTML and it shouldn't evaluated 4203556 4 5 sky Fri Jan 15 00:08:00 PST 1999 7 registerKeyboardAction does not always mean getting the event evaluated 4803767 4 4 joutwate Wed Jan 15 14:40:00 PST 2003 2 RFE : Ability to set OUTLINE DRAGGING in JFrame committed 4151536 4 3 leif Tue Jun 23 10:47:00 PDT 1998 6 JFileChooser should allow traversable but unacceptable directories accepted 4486499 5 5 naa@sparc.spb.su Tue Jul 31 14:10:00 PDT 2001 4 javax.swing.text.html.HTMLWriter is badly written and needs rewriting evaluated 4773496 4 3 leif Mon Nov 04 15:16:00 PST 2002 0 XP L&F: not enough padding in JComboBox committed 4337267 4 3 naoto Wed May 10 18:59:00 PDT 2000 1 Arabic Numeral Shaping evaluated 4256525 4 3 joutwate Thu Jul 22 18:52:00 PDT 1999 1 JInternalFrame Activation should be cheaper committed 4140808 4 5 idk Thu May 21 10:57:00 PDT 1998 4 AbstractDocument must not assume that its Content object is empty evaluated 4418620 4 5 leif Fri Feb 23 14:58:00 PST 2001 1 Shared JToolTip loses border evaluated 4865915 3 3 aep@sparc.spb.su Mon May 19 01:57:00 PDT 2003 0 JCK1.4a-runtime api/javax_swing/interactive/JScrollBarTests.html#JScrollBar evaluated 4801274 4 5 shannonh Thu Jan 09 18:16:00 PST 2003 0 Tab key selects a non-existent row in an empty JTable accepted 4421314 4 5 shannonh Fri Mar 02 15:59:00 PST 2001 0 JOptionPane.showInputDialog gets wrong choice with dup. text evaluated 4292342 4 3 joutwate Wed Nov 17 11:49:00 PST 1999 7 Clicking in an inactive JInternalFrame can cause a begin-drag (96845) evaluated 4783442 4 4 sky Fri Nov 22 11:57:00 PST 2002 1 JPopupMenu drawn underneath JInternalFrame contents in fullscreen mode evaluated 4440338 4 5 leif Wed Apr 11 16:48:00 PDT 2001 2 Redundant file loading threads using JFileChooser; deadlock accepted 4730390 4 5 leif Mon Aug 12 17:15:00 PDT 2002 0 Get system level information about non-existing file names/extensions. accepted 4820794 4 5 shannonh Wed Feb 19 14:35:00 PST 2003 0 Pressing Caps Lock key starts cell editor in JTable accepted 4760425 3 3 sky Wed Oct 09 09:59:00 PDT 2002 9 Erroneous Behaviors When Accessing System Clipboard in Swing Applets evaluated 4767393 4 3 zav@sparc.spb.su Wed Oct 23 10:54:00 PDT 2002 0 Disabled JMenu is selectable via mnemonic committed 4366725 4 5 leif Tue Aug 29 00:06:00 PDT 2000 1 JFileChooser.setOpaque(false) does not work fully accepted 4857299 5 5 aep@sparc.spb.su Thu May 01 16:11:00 PDT 2003 0 RFE: in JTree, expandPath should respect scrollsOnExpand accepted 4849941 4 2 rm108251 Thu Apr 17 03:08:00 PDT 2003 0 Right border missing in JTable dispatched 4313120 4 5 sky Wed Feb 16 11:54:00 PST 2000 5 ColorUIResource: add Alpha channel support (plus another request) evaluated 4238847 4 3 sky Mon May 17 13:38:00 PDT 1999 0 Visibility in Extending UndoManager evaluated 4812585 3 3 zav@sparc.spb.su Tue Feb 04 09:47:00 PST 2003 0 BasicComboBoxUI.FocusHandler doesn't hide popup menu when focus is lost committed 4745771 4 3 shannonh Wed Sep 11 15:32:00 PDT 2002 9 JVM hangs after using ownerless JDialog evaluated 4851443 3 3 shannonh Mon Apr 21 00:28:00 PDT 2003 0 1.4.0 Regression: Animated GIFS stop animating on JButtons and JLabels committed 4847998 4 4 sky Mon Apr 14 11:45:00 PDT 2003 0 RFE: Please include TableLayout accepted 4765288 4 3 zpm@sparc.spb.su Fri Oct 18 00:02:00 PDT 2002 0 HTMLDocument inserts HTML with
tag incorrectly accepted 4520587 4 3 sky Mon Oct 29 00:15:00 PST 2001 13 RFE: Need a JSpinner.reformat() method as a JSpinner.commitEdit()'s complement evaluated 4834918 2 3 joutwate Wed Mar 19 18:13:00 PST 2003 22 Win L&F: JInternalFrame should merge with JMenuBar when maximized committed 4783248 3 2 leif Fri Nov 22 05:54:00 PST 2002 0 Win XP L&F : Slider leaves trail when dragged evaluated 4626632 5 5 davidson@eng Tue Jan 22 11:33:00 PST 2002 1 Various containers for Action throw NPE when PropChgEvent has null newValue accepted 4793790 4 4 shannonh Fri Dec 13 15:37:00 PST 2002 0 checkbox table cell editor doesn't work properly evaluated 4765256 4 4 joutwate Fri Oct 18 11:36:00 PDT 2002 5 REGRESSION: Icons in JDesktopPane not repositioned when pane is resized accepted 4486577 5 4 idk Tue Jul 31 16:01:00 PDT 2001 0 Wasteful use of getBounds() in interface Shape evaluated 4209604 4 5 joutwate Mon Feb 08 08:04:00 PST 1999 0 ProgressMonitorInputStream updates ProgressMonitor outside event thread evaluated 4665225 4 4 aep@sparc.spb.su Tue Apr 09 14:10:00 PDT 2002 0 swing isn't coalescing some mouse drag events on scrollbars. evaluated 4487510 5 5 shannonh Thu Aug 02 00:34:00 PDT 2001 1 RFE: Need ability to set the disabledBackground for a JTextField or JTextArea evaluated 4137343 4 3 leif Tue May 12 00:33:00 PDT 1998 2 Toolbar and menubar layout managers don't wrap evaluated 4825653 4 5 idk Fri Feb 28 11:46:00 PST 2003 0 JEditorPane getStream and setPage interdependency problem evaluated 4855171 4 3 sky Mon Apr 28 16:11:00 PDT 2003 1 Cannot set a document to JFormattedTextField got from JSpinner's editor accepted 4678300 4 4 joutwate Wed May 01 17:56:00 PDT 2002 21 SwingSet2 and other demos should use setJMenuBar() committed 4185305 4 5 joutwate Wed Oct 28 17:57:00 PST 1998 1 JProgressBar Metal PLAF overwrites empty borders evaluated 4465504 5 3 idk Sun Jun 03 13:48:00 PDT 2001 2 Add getEditorKit() to JTextComponent evaluated 4749645 3 3 leif Wed Sep 18 14:17:00 PDT 2002 2 WindowsLAF: Tooltip on bottommost menu item hides this menu item evaluated 4628641 4 5 idk Fri Jan 25 10:52:00 PST 2002 0 Make Segment implement CharSequence accepted 4765292 3 4 joutwate Fri Oct 18 00:05:00 PDT 2002 0 REGRESSION: WindowsLookAndFeel causes need for JInternalFrame revalidation evaluated 4148068 4 5 idk Thu Jun 11 17:35:00 PDT 1998 2 can't get all Properties from swing.text.Document evaluated 4232728 4 4 zav@sparc.spb.su Sun Apr 25 20:27:00 PDT 1999 1 No method to manipulate Scroll Button or ComboBox Button evaluated 4508646 4 4 leif Fri Sep 28 00:17:00 PDT 2001 10 Tooltip generated by JToolBar.add(Action) wrong accepted 4869855 2 3 zav@sparc.spb.su Tue May 27 08:54:00 PDT 2003 0 method MenuSelectionManager.setSelectedPath() throws NPE evaluated 4164323 4 4 davidson@eng Thu Aug 06 18:45:00 PDT 1998 3 AppletBeanInfo not defined, bound properties reported incorrectly evaluated 4622251 5 5 sky Thu Jan 10 19:45:00 PST 2002 5 RFE: JSpinner wrapping from minimum to maximum or maximum to minimum. accepted 4523840 4 3 joutwate Tue Nov 06 15:56:00 PST 2001 1 inactive internal frames and propogation of mouse events accepted 4716471 4 3 idk Wed Jul 17 17:13:00 PDT 2002 0 extendible EditorKits accepted 4469726 4 5 davidson@eng Wed Jun 13 18:50:00 PDT 2001 0 identification and use of non-client fonts in win32 desktop properties accepted 4835479 5 4 bchristi Thu Mar 20 14:47:00 PST 2003 0 JFileChooser/WindowsL&F: show hidden files if set in native Folder Options accepted 4494156 5 5 sdv@sparc.spb.su Mon Aug 20 18:30:00 PDT 2001 2 JEditorPane hyperlinks activate only when mouse is motionless accepted 4865103 4 5 aep@sparc.spb.su Thu May 15 18:22:00 PDT 2003 0 JScrollPane in GridBagLayout resizes incorrectly evaluated 4614558 5 3 sky Mon Dec 17 10:15:00 PST 2001 1 JTree setting Focus on JTextPane seems impossible accepted 4368790 4 5 shannonh Wed Sep 06 13:50:00 PDT 2000 13 JButton stays pressed when focus stolen evaluated 4793741 4 4 leif Fri Dec 13 14:45:00 PST 2002 0 setDefaultLookAndFeelDecorated Hint is ignored for JToolbar evaluated 4669384 5 3 joutwate Tue Apr 16 14:42:00 PDT 2002 0 Problems with keyboard navigation in SwingSet2 List Demo evaluated 4765296 4 5 shannonh Fri Oct 18 00:08:00 PDT 2002 0 No focus rectangle on checkbox with html-formatted text accepted 4849062 4 5 sky Tue Apr 15 20:10:00 PDT 2003 1 JTable and JList have incompatible definitions of cellFocus for renderers. accepted 4487456 4 4 zav@sparc.spb.su Thu Aug 02 11:08:00 PDT 2001 0 JComboBox generates mouseRelease events for certain LAF only committed 4482128 4 4 joutwate Thu Jul 19 17:52:00 PDT 2001 1 REGRESSION: Editable JComboBox as a TableCellEditor doesn't render the selection evaluated 4871520 3 3 sky Thu May 29 17:08:00 PDT 2003 0 PopupFactory.setSharedInstance refers to undefined "AppContext" committed 4676790 4 3 zav@sparc.spb.su Mon Apr 29 17:23:00 PDT 2002 1 The Short-cut keys for the Menus has focus level Issues. accepted 4825409 3 4 leif Thu Feb 27 21:10:00 PST 2003 0 XP L&F: JFileChooser navigation button sizing problem committed 4462415 4 3 joutwate Wed May 23 14:50:00 PDT 2001 0 Splash screen replace SwingSet demo panel in SwingSet2 due to race condition evaluated 4792192 5 5 joutwate Wed Dec 11 00:11:00 PST 2002 0 RFE: Need an event-free programmatic means of changing a JComboBox selection evaluated 4161616 4 5 leif Wed Jul 29 11:58:00 PDT 1998 21 Make tool bars more like MS toolbars evaluated 4652910 4 5 shannonh Thu Mar 14 00:35:00 PST 2002 0 JPI Exception dialog - OK accelerator key missing (PIT02:[03/11/02] ) evaluated 4422795 4 5 leif Wed Mar 07 00:04:00 PST 2001 0 MetalBorders.TableHeaderBorder: not a UIResource, wrong Insets evaluated 4303294 4 5 shannonh Fri Jan 07 13:23:00 PST 2000 6 Implement discontinuous selection from the keyboard for list-like components committed 4480327 4 4 leif Mon Jul 16 14:59:00 PDT 2001 44 1.4's JFileChooser extremely slow for remote folders accepted 4222732 4 3 null Mon Mar 22 15:18:00 PST 1999 1 JTable setBorder overwrites data in first row (ie bad inset layout) accepted 4817131 4 5 kyuka Tue Feb 11 19:59:00 PST 2003 0 JScrollPane.setComponentOrientation() doesn't change corner components. committed 4835483 5 5 bchristi Thu Mar 20 14:51:00 PST 2003 0 JFileChooser/WindowsL&F:Details view column headings should be left-justified accepted 4688783 4 3 zav@sparc.spb.su Tue May 21 11:54:00 PDT 2002 0 JPopupMenu hardcoded i JMenu evaluated 4349334 4 5 null Wed Jun 28 18:11:00 PDT 2000 1 Column headers are cut off in JTable for Windows L&F accepted 4508191 4 3 joutwate Thu Sep 27 15:25:00 PDT 2001 3 JOptionPane.showInternalOptionDialog blocks after its enclosing JFrame is closed accepted 4777579 3 3 zpm@sparc.spb.su Tue Nov 12 11:56:00 PST 2002 0 1.4 REGRESSION: Redo with HTMLEditorKit causes NullPointerException committed 4104906 4 5 joutwate Mon Jan 19 00:20:00 PST 1998 20 JOptionPane should wordwrap message text evaluated 4792249 4 4 sky Wed Dec 11 13:21:00 PST 2002 0 MaskFormatter bugs with valueToString() and stringToValue() evaluated 4836762 4 4 sharonz Mon Mar 24 14:14:00 PST 2003 0 Documentation typo in javax.swing.text.Document committed 4667991 4 5 dalem Sun Apr 14 04:26:00 PDT 2002 1 built-in support for sorting table accepted 4855750 5 5 bchristi Tue Apr 29 13:36:00 PDT 2003 0 JFileChooser doesn't allow to remove disabled Help Button evaluated 4762915 4 4 zav@sparc.spb.su Mon Oct 14 18:06:00 PDT 2002 2 JComboBox:prototypeDisplayValue not passed to internal lists PrototypeCellValue evaluated 4214395 4 5 joutwate Wed Feb 24 08:01:00 PST 1999 5 JOptionPane's createInternalFrame() method doesn't allow JInternalFrame subclass evaluated 4525465 4 4 joutwate Fri Nov 09 00:34:00 PST 2001 0 SwingSet2/BezierAnimationCurve demo needs to be updated accepted 4777756 4 3 shannonh Tue Nov 12 16:19:00 PST 2002 1 JTable doesn't remove active CellEditor when TableModel changes evaluated 4640081 4 3 zav@sparc.spb.su Tue Feb 19 18:48:00 PST 2002 4 JPopupMenu.show() does not display JPopup if previously hidden accepted 4466892 4 3 joutwate Wed Jun 06 14:32:00 PDT 2001 1 Enhance SwingSet2 demo to use flat-button JToolBar under Win L&F evaluated 4801152 4 4 joutwate Thu Jan 09 15:20:00 PST 2003 3 Various Focus problems with JInternalFrame committed 4625388 4 4 naa@sparc.spb.su Thu Jan 17 15:32:00 PST 2002 2 JEditorPane read method does not work with Changed Char set and doc w/o url accepted 4723012 3 4 shannonh Tue Jul 30 14:36:00 PDT 2002 0 1.4.0 REGRESSION: JTable column header is not properly centered. committed 4714318 3 3 kve@sparc.spb.su Fri Jul 12 14:46:00 PDT 2002 0 1.4.0 REGRESSION: Multi Selection JFileChooser throws ArrayIndexOutOfBoundsExcep committed 4522861 4 2 zpm@sparc.spb.su Mon Nov 05 08:11:00 PST 2001 4 JEditor HTMLEditorKit spacing regression to 1.3.x evaluated 4865494 4 4 leif Fri May 16 00:22:00 PDT 2003 0 Win L&F: JFileChooser: View As Options not consistent with XP committed 4324692 4 4 naoto Fri Mar 24 05:12:00 PST 2000 2 Cursor loops infinitely in multiline JTextPane evaluated 4129691 4 5 shannonh Thu Apr 16 13:48:00 PDT 1998 0 Motif,JButton:If paintBorder is false focus not painting though paintfocus true evaluated 4501652 4 5 leif Tue Sep 11 00:07:00 PDT 2001 1 Attributes of columns should not depend on the position. (JFileChooser) accepted 4849177 4 4 joutwate Wed Apr 16 03:47:00 PDT 2003 0 NPE thrown in Table Demo of SwingSet2 accepted 4155103 4 2 sky Tue Jul 07 11:32:00 PDT 1998 8 JFrame, JDialog, JWindow, and JApplet don't use RepaintManager evaluated 4103946 4 4 joutwate Wed Jan 14 13:20:00 PST 1998 0 Motif scrollbars keyboard navigation not working properly evaluated 4273817 4 5 shannonh Mon Sep 20 19:01:00 PDT 1999 0 Add a forcedPaintFocus property to JCheckBox evaluated 4789550 5 5 shannonh Thu Dec 05 17:57:00 PST 2002 1 RFE: Need showMessageDialog with only one parameter in javax.swing.JOptionPane committed 4776403 4 3 zav@sparc.spb.su Fri Nov 08 15:00:00 PST 2002 0 setRolloverEnabled(true) not working for JMenuItem committed 4745084 4 5 sky Tue Sep 10 17:17:00 PDT 2002 1 Make it easier to have custom icons for tree cell renderers and editors accepted 4482545 4 4 joutwate Fri Jul 20 14:36:00 PDT 2001 1 JInternalFrame.isPalette should be supported in Window LAF evaluated 4318634 4 4 sky Fri Mar 03 10:49:00 PST 2000 1 Request improved dirty region tracking in javax.swing.RepaintManager evaluated 4691083 4 4 joutwate Thu May 23 22:08:00 PDT 2002 1 RFE: Add a constructor to ProgressMonitor to specify a JProgressBar evaluated 4615021 4 5 mca Mon Dec 17 18:32:00 PST 2001 0 Improve Swing icons committed 4533820 4 3 joutwate Fri Nov 30 16:11:00 PST 2001 76 Extend InputVerifiers to keep events from firing on target components. evaluated 4417601 5 5 zpm@sparc.spb.su Wed Feb 21 14:44:00 PST 2001 0 JMenus with no items paint a tiny menu. evaluated 4783623 4 4 joutwate Fri Nov 22 15:04:00 PST 2002 0 non-active JInternalFrame won't call COMPONENT_RESIZED when maximized accepted 4368107 4 4 kyuka Sun Sep 03 07:49:00 PDT 2000 0 JTable cell text is parttialy or totally hidden when cells are double clicked accepted 4497885 4 4 leif Wed Aug 29 15:25:00 PDT 2001 3 Etched- and TitledBorder in Swing with Windows L&F don't use system colors. accepted 4832239 4 4 shannonh Thu Mar 13 14:41:00 PST 2003 3 RFE: JOptionPane using initialValue when options is null accepted 4765307 4 5 shannonh Fri Oct 18 00:13:00 PDT 2002 0 REGRESSION: Accelerator vs. TransferHandler committed 4471450 4 5 idk Mon Jun 18 18:34:00 PDT 2001 5 Add support for floating boxes to swing text framework evaluated 4130812 4 5 shannonh Mon Apr 20 15:34:00 PDT 1998 0 Motif JToggleButton: painting focus is not handled well evaluated 4798542 4 4 shannonh Thu Jan 02 17:35:00 PST 2003 1 Mnemonics not working when ALT key is released before character key evaluated 4830281 3 3 joutwate Mon Mar 10 20:48:00 PST 2003 0 DPI setting not supported in GTK L&F committed 4465512 4 5 zav@sparc.spb.su Sun Jun 03 15:44:00 PDT 2001 2 New 1.4 focus rework for popup menus isn't ignoring menu accelerators accepted 4675781 4 4 sky Fri Apr 26 15:12:00 PDT 2002 1 javax.swing.Timer does not safely handle negative delays accepted 4801162 4 4 idk Thu Jan 09 15:29:00 PST 2003 1 RFE: Make javax.swing.JTextPane.replaceSelection at least protected committed 4794439 4 4 idk Mon Dec 16 14:37:00 PST 2002 0 ListCellRenderer in JList rendering HTML text calculates it own size wrong evaluated 4262543 4 3 sky Sat Aug 14 14:53:00 PDT 1999 2 DebugGraphics extends Graphics, not Graphics2D evaluated 4858534 4 4 joutwate Mon May 05 13:21:00 PDT 2003 0 JSlider does not resize after JInternalFrame it's in is maximized, iconified evaluated 4684300 4 4 leif Mon May 13 16:57:00 PDT 2002 0 Swing tooltips don't dissapear when the mouse moves over them accepted 4274423 4 5 shannonh Wed Sep 22 11:30:00 PDT 1999 0 JOptionPane.getMaxCharactersPerLineCount needs a setMaxCharactersPerLineCount evaluated 4632500 5 4 leif Sat Feb 02 19:32:00 PST 2002 2 Application icon (teacup) appears on jfilechooser in java windows l&f accepted 4793728 5 5 shannonh Fri Dec 13 14:24:00 PST 2002 1 RFE: JRadioButton( JComponent component) would be nice accepted 4371409 4 5 leif Fri Sep 15 06:22:00 PDT 2000 0 TEST_BUG: the test JColorChooser/JCC_setSelectionModel is invalid accepted 4346941 4 5 shannonh Tue Jun 20 15:55:00 PDT 2000 7 JRadioButton objects lose ther opaque settings after updateComponentTree() evaluated 4424085 4 5 sky Fri Mar 09 16:21:00 PST 2001 0 Several Swing problems accepted 4765382 5 5 leif Fri Oct 18 13:13:00 PDT 2002 0 JFileChooser - focus problem accepted 4765323 5 5 shannonh Fri Oct 18 00:26:00 PDT 2002 3 JTable.setAutoResizeMode(AUTO_RESIZE_ALL_COLUMNS) doesn't resize proportionally accepted 4826493 5 5 leif Mon Mar 03 13:40:00 PST 2003 0 Remove/Disable Files of Type List Item in the Directory only JFileChooser evaluated 4165217 4 4 kve@sparc.spb.su Mon Aug 10 15:39:00 PDT 1998 1 JColorChooser is not serialized evaluated 4802583 4 5 moa@sparc.spb.su Mon Jan 13 16:37:00 PST 2003 0 JTabbedPane paints components from unselected tabs committed 4767065 4 4 joutwate Tue Oct 22 18:50:00 PDT 2002 0 Strange Focus behavior of JInternalFrames on JDesktopPane evaluated 4735107 4 3 shannonh Wed Aug 21 18:32:00 PDT 2002 3 Architecture of JTable and TableModel evaluated 4765310 5 5 sky Fri Oct 18 00:16:00 PDT 2002 1 javax.swing.JSpinner$DateEditor(JSpinner, DateFormat) should be public.d accepted 4524271 4 3 naoto Wed Nov 07 00:14:00 PST 2001 0 RFE: Thai WTT 2.0 editing support in JTextComponent accepted 4641856 3 3 zpm@sparc.spb.su Fri Feb 22 11:36:00 PST 2002 0 Swing popup menus get clipped when a browser is sized smaller than the applet evaluated 4645049 5 5 joutwate Thu Feb 28 14:23:00 PST 2002 0 minor iconify/restore/close buttons windows L&F inconsistent accepted 4527482 4 4 sky Wed Nov 14 18:56:00 PST 2001 5 JTextField and JLabel do not display correct font under Windows L&F in 1.4beta3 accepted 4833645 5 5 kve@sparc.spb.su Mon Mar 17 15:01:00 PST 2003 0 BoxLayout does not respect components preferred widths evaluated 4684067 4 3 naa@sparc.spb.su Mon May 13 13:31:00 PDT 2002 2 HTMLEditor Kit, Can't delete list items accepted 4263171 4 5 leif Tue Aug 17 15:29:00 PDT 1999 0 JToolBar doesn't draw properly when dragged evaluated 4765319 4 3 zav@sparc.spb.su Fri Oct 18 00:23:00 PDT 2002 0 1.4 REGRESSION: Alt-Up/Down doens't open combo in WinLAF accepted 4244395 4 4 zpm@sparc.spb.su Mon Jun 07 11:19:00 PDT 1999 0 Drawing bugs when using emptyBorder with button classes accepted 4486151 4 2 sky Mon Jul 30 17:36:00 PDT 2001 1 SpringLayout does not support ComponentOrientation incomplete 4727901 4 3 sky Wed Aug 07 14:35:00 PDT 2002 0 Add a SortedListModel class evaluated 4854950 4 4 joutwate Mon Apr 28 11:35:00 PDT 2003 0 JFrame's decorated root pane doesn't like MouseListeners accepted 4624567 4 4 dalem Wed Jan 16 11:41:00 PST 2002 0 REGRESSION: JTable in JInternalFrame won't initially drag scroll evaluated 4109871 4 4 shannonh Thu Feb 05 13:56:00 PST 1998 20 JComboBox is not fully accessible in JTable. committed 4296022 4 5 idk Wed Dec 01 16:23:00 PST 1999 69 Displaying XML within a JEditorPane evaluated 4721224 4 5 aep@sparc.spb.su Fri Jul 26 03:03:00 PDT 2002 2 JApplet shouldn't be a focus cycle root evaluated 4295363 4 4 kyuka Tue Nov 30 06:11:00 PST 1999 4 Component Orientation for JTable Cells does not work accepted 4202392 4 5 leif Tue Jan 12 08:55:00 PST 1999 3 add propertyChangeListener support to TitledBorder evaluated 4533778 4 4 shannonh Fri Nov 30 15:25:00 PST 2001 3 isSelectionEmpty() returns false in empty JTable 1.3.1, 1.4beta3 committed 4665233 4 4 sky Tue Apr 09 14:18:00 PDT 2002 2 swing RepaintManager is not optimal for some JTable update scenarios accepted 4825408 3 4 leif Thu Feb 27 21:05:00 PST 2003 0 XP L&F: JFileChooser resizing problems committed 4765299 5 5 sky Fri Oct 18 00:10:00 PDT 2002 0 componentResized() not always called with nested JSplitPanes accepted 4471760 4 2 sky Tue Jun 19 13:10:00 PDT 2001 0 JLabel has shaggy text when disabled accepted 4459137 4 4 leif Tue May 15 18:05:00 PDT 2001 0 Displaying position is wrong for BorderFactorytest evaluated 4860345 4 3 leif Thu May 08 06:00:00 PDT 2003 0 JTree folder icon in WinXP LAF is not similar to WinXP committed 4765241 3 3 joutwate Fri Oct 18 11:25:00 PDT 2002 0 1.4 REGRESSION: ContainerOrderFocusTraversal prevents InputVerifier.verify() evaluated 4707457 4 4 zav@sparc.spb.su Mon Jun 24 21:17:00 PDT 2002 10 focusGained and focusLost methods under FcousListener in 1.4 do not work as 1.3 accepted 4835327 4 3 joutwate Thu Mar 20 00:09:00 PST 2003 0 componentShown only received for first doc in MDI evaluated 4803478 4 3 leif Wed Jan 15 06:45:00 PST 2003 0 Regression .../JComboBox/4465533/bug4465533.java fails on WinXP committed 4430777 4 4 idk Tue Mar 27 15:25:00 PST 2001 0 GlyphPainter2 requires AbstractDocument evaluated 4226243 4 2 shannonh Thu Apr 01 18:13:00 PST 1999 9 Can't navigate within a radio button group using arrow keys evaluated 4778281 4 4 joutwate Wed Nov 13 00:06:00 PST 2002 0 Alt-Tab while resizing JInternalFrame results in wrong cursor committed 4861002 4 4 bchristi Fri May 09 02:04:00 PDT 2003 0 JFileChosser does not have resize restrictions as in native XP evaluated 4311805 4 5 leif Thu Feb 10 20:57:00 PST 2000 0 Dragged out JToolBar ocupates unexpected position on screen accepted 4804690 3 3 joutwate Thu Jan 16 22:55:00 PST 2003 0 SwingSet2/JInternalFrame/GTK:the background of the generator has a problem committed 4431395 4 4 idk Wed Mar 28 17:20:00 PST 2001 2 JTextPane in JScrollPanel with large component not drawn properly accepted 4825949 4 5 leif Fri Feb 28 17:46:00 PST 2003 3 JToolTip in JApplet will place tooltip in wrong monitor evaluated 4473401 5 5 sdv@sparc.spb.su Fri Jun 22 10:34:00 PDT 2001 1 Forms should generate a hyperlink event, not directly post/get the data evaluated 4520228 4 4 sky Fri Oct 26 18:01:00 PDT 2001 27 Lightweight swing containers do not print their nested (child) components accepted 4671612 5 5 dalem Fri Apr 19 00:08:00 PDT 2002 6 JTable reporting invalid selected row count accepted 4862834 2 3 monsanto Mon May 12 22:19:00 PDT 2003 0 REGRESSION: api/javax_swing/JMenuBar/AccessibleJMenuBar/index.html#AccessibleSel dispatched 4642061 5 5 sky Fri Feb 22 16:11:00 PST 2002 29 JTreeTable evaluated 4759312 3 3 joutwate Mon Oct 07 17:52:00 PDT 2002 1 JInternalFrame Not Being Finalized After Closing evaluated 4869885 4 5 idk Tue May 27 09:47:00 PDT 2003 0 JEditorPane can't detect < in HTML if it is followed by a character dispatched 4398733 4 3 joutwate Fri Dec 15 16:06:00 PST 2000 11 MouseClicked event not delivered when switched between 2 Internal frames evaluated 4706813 3 4 leif Sun Jun 23 06:50:00 PDT 2002 0 jdk1.4.1-b14, JFileChooser fails to display contents of "My Computer" under XP committed 4472830 4 5 shannonh Thu Jun 21 11:30:00 PDT 2001 2 Drag sensitivity should be adjustable accepted 4480335 4 3 shannonh Mon Jul 16 15:10:00 PDT 2001 0 editable JComboBox changes newlines into spaces accepted 4486496 4 4 idk Tue Jul 31 14:08:00 PDT 2001 4 ParserDelegator().parse() gives tags out of order accepted 4486741 4 5 naoto Tue Jul 31 21:32:00 PDT 2001 0 Swing text components don't store the attributes of input method committed text accepted 4859570 4 5 aep@sparc.spb.su Wed May 07 04:14:00 PDT 2003 0 SwingUtilities.sharedOwnerFrame is never disposed evaluated 4207472 4 3 naa@sparc.spb.su Sun Jan 31 11:39:00 PST 1999 6 Space added after named anchors evaluated 4479363 4 3 sky Thu Jul 12 17:34:00 PDT 2001 14 Swing does not handle fractional font metrics correctly accepted 4678049 5 4 leif Wed May 01 13:14:00 PDT 2002 1 Selecting a new filter causes the filename field to blank out in JFileChooser accepted 4787979 4 4 sky Tue Dec 03 17:02:00 PST 2002 0 JComboBox getToolTipLocation does not work evaluated 4853739 5 5 shannonh Thu Apr 24 16:39:00 PDT 2003 0 In JOptionPane, selectInitialValue() is not called when first focusing dialog accepted 4740419 3 3 moa@sparc.spb.su Mon Sep 02 08:13:00 PDT 2002 1 Selecting unselected tab doesn't get the focus, under some condition. committed 4301200 4 2 null Wed Dec 22 04:16:00 PST 1999 0 Text widths are calculated incorrect accepted 4733651 4 4 leif Mon Aug 19 16:43:00 PDT 2002 1 File[] returned by FileSystemView.getRoots() should never be modifed on Win32 evaluated 4865503 5 5 leif Fri May 16 00:26:00 PDT 2003 0 Win L&F: JFileChooser: Save In label alignment not consistent with XP committed 4826627 5 5 joutwate Mon Mar 03 16:30:00 PST 2003 0 swingset: canceling InputDialog should not produce response accepted 4674040 3 3 sky Wed Apr 24 15:20:00 PDT 2002 0 JComponent exposes internal Dimension data with setPreferredSize() and friends committed 4711996 3 3 kve@sparc.spb.su Tue Jul 09 04:16:00 PDT 2002 0 IllegalArgumentException when updating color chooser ui committed 4760481 4 5 sky Wed Oct 09 10:30:00 PDT 2002 2 DefaultTreeCellRenderer icons and colors aren't updated in updateUI() accepted 4861969 4 5 aep@sparc.spb.su Fri May 09 16:59:00 PDT 2003 1 JSplitPane within another disabled JSplitPane does not display cursor accepted 4783068 5 5 idk Thu Nov 21 19:14:00 PST 2002 4 Components with HTML text should gray out the text when disabled accepted 4760102 4 4 leif Tue Oct 08 18:00:00 PDT 2002 0 Request JFileChooser allow dislay of files but selection only of directories accepted 4488581 4 2 zpm@sparc.spb.su Mon Aug 06 11:50:00 PDT 2001 1 JPopupMenu.setVisible throws NullPointerException evaluated 4621323 4 2 joutwate Wed Jan 09 13:41:00 PST 2002 0 Some Swing "constants" aren't constant committed 4195955 4 5 leif Tue Dec 08 18:07:00 PST 1998 2 FileChooser needs to react to Exceptions thrown by alternate FileSystem(View) accepted 4867005 3 3 joutwate Tue May 20 16:01:00 PDT 2003 3 When removing a JPanel, child JButton gets a FOCUS_GAINED dispatched 4449362 4 4 kyuka Mon Apr 23 00:53:00 PDT 2001 0 Box doesn't support ComponentOrientation committed 4837807 3 3 leif Wed Mar 26 01:23:00 PST 2003 0 JCK1.4a api/javax_swing/interactive/JFileChooserTests.html#JFileChooser fails evaluated 4279934 4 5 joutwate Mon Oct 11 09:55:00 PDT 1999 0 Add alt. form of InputVerifier.shouldYieldFocus() with "to" comp as 2nd param evaluated 4354925 4 5 leif Thu Jul 20 11:49:00 PDT 2000 0 JMenu/JMenuItem UI (JLF/Metal) does not comply with JLF specification evaluated 4769773 4 4 joutwate Mon Oct 28 11:04:00 PST 2002 1 JInternalFrame.setMaximum(true) before adding it to JDesktopPane causes NPE evaluated 4108708 4 5 joutwate Mon Feb 02 11:12:00 PST 1998 5 ImageIcon(...) is incredibly slow evaluated 4871413 4 4 leif Thu May 29 14:56:00 PDT 2003 0 ToolTipManager.setEnabled(...) doc. refers to unknown tooltip dispatched 4311629 4 4 naoto Thu Feb 10 00:59:00 PST 2000 1 Text components should allow for contextual component orientation evaluated 4291881 4 5 joutwate Tue Nov 16 10:23:00 PST 1999 2 Add JInternalDialog, and add public 'setModal' method to JIntrnlFrame evaluated 4785269 4 5 leif Tue Nov 26 16:40:00 PST 2002 1 JFileChooser filter problem when using wildcards evaluated 4761529 4 3 leif Thu Oct 10 16:47:00 PDT 2002 0 Folder Icon disappears while renaming it in the details view of JFileChooser evaluated 4736918 4 5 davidson@eng Mon Aug 26 14:17:00 PDT 2002 0 WindowsUtils is redundant and should be removed accepted 4705698 4 3 joutwate Thu Jun 20 16:35:00 PDT 2002 1 Cursor not correctly being reset when entering/exiting JInternalFrame accepted 4760089 3 4 leif Tue Oct 08 17:44:00 PDT 2002 6 1.4 REGRESSION: Compound TitledBorder not opaque evaluated 4676748 4 3 zav@sparc.spb.su Mon Apr 29 16:42:00 PDT 2002 3 A JTextArea inside a heavyweight JPopupMenu can't get focus if outside of Frame committed 4479990 4 3 idk Sat Jul 14 13:24:00 PDT 2001 2 RTFReader saves tab stops to attribute set incorrectly accepted 4855377 2 3 leif Tue Apr 29 01:43:00 PDT 2003 0 JCK1.4a-runtime api/javax_swing/interactive/JFileChooserTests.html#JFileChooser committed 4844477 4 5 joutwate Mon Apr 07 15:49:00 PDT 2003 0 RFE: Necessary extensibility method in BasicProgressBarUI is private committed 4668615 3 3 zpm@sparc.spb.su Mon Apr 15 18:54:00 PDT 2002 0 HopperB08:SwingSet2 Demo:IllegalArgumentException in FileChooser and Table demos evaluated 4760098 3 3 sky Tue Oct 08 17:56:00 PDT 2002 1 JTable fails with large tables: more and more CPU time consumed as table grows committed 4801840 4 5 joutwate Fri Jan 10 15:38:00 PST 2003 0 JInternalFrame should have setLocationRelativeTo method committed 4315196 4 4 shannonh Thu Feb 24 09:32:00 PST 2000 15 AbstractButton.setModel() doesn't remove ItemListener from old model accepted 4829588 3 2 shannonh Sun Mar 09 19:54:00 PST 2003 0 showConfirmDialog behavior of 1.4.X is diff. from 1.3.1 with long text string evaluated 4748757 3 3 joutwate Tue Sep 17 11:46:00 PDT 2002 0 1.4.1 REGRESSION: JInternalFrame does not always minimize with CTRL+F9 evaluated 4631925 3 4 shannonh Fri Feb 01 11:07:00 PST 2002 0 JColor Chooser is not fully accessible committed 4806485 4 4 leif Wed Jan 22 00:28:00 PST 2003 0 The JFileChooser sees a binary file format as a directory evaluated 4151338 4 5 null Mon Jun 22 17:02:00 PDT 1998 24 Row oriented JTable evaluated 4724061 4 3 idk Wed Jul 31 16:26:00 PDT 2002 11 Misspacing in Printer Output of Styled Text accepted 4395097 4 5 joutwate Tue Dec 05 11:31:00 PST 2000 0 Modification of getDesktipPane() and show() in JinternalFrame evaluated 4479139 4 3 leif Thu Jul 12 11:10:00 PDT 2001 4 Canceling JFileChooser "freezes" keyboard input in chooser and other JComponents accepted 4697065 3 4 joutwate Tue Jun 04 14:30:00 PDT 2002 0 Selected Tab in JTabbedPane often gets painted twice accepted 4486554 5 5 null Tue Jul 31 15:19:00 PDT 2001 0 RFE: Allow single selection models to be used with JList evaluated 4779930 4 3 aim Fri Nov 15 16:22:00 PST 2002 0 windows look&feel: scrollbar arrows are off by one pixel committed 4267065 4 5 sky Mon Aug 30 16:43:00 PDT 1999 23 JTreeTable and related classes included with official Swing release evaluated 4753150 4 3 leif Wed Sep 25 00:14:00 PDT 2002 0 No error on renaming a folder to blank/duplicate folder name in JFileChooser accepted 4438933 4 4 leif Tue Apr 10 21:18:00 PDT 2001 0 JFileChooser Windows Look & Feel is not consistent with the native platform accepted 4758891 4 3 aep@sparc.spb.su Mon Oct 07 10:35:00 PDT 2002 0 RFE: Want to use German characters (,,,) as mnemonics evaluated 4304287 4 5 sky Wed Jan 12 14:51:00 PST 2000 13 Swing components should require the use of Collections and not Vectors evaluated 4869239 3 5 sky Fri May 23 17:00:00 PDT 2003 0 GTK L&F: stock icons need to pick up the same graphics as gtk/gnome stock icons evaluated 4151155 4 5 null Mon Jun 22 11:20:00 PDT 1998 0 Default Table Model setEditable() accepted 4249570 4 3 sherman@japan Thu Jun 24 19:35:00 PDT 1999 0 JEditorPane can not display correctly accepted 4633159 4 5 joutwate Mon Feb 04 20:19:00 PST 2002 0 BasicTabbedPaneUI.requestFocusForVisibleComponent causes NPE evaluated 4667614 5 4 leif Fri Apr 12 14:14:00 PDT 2002 3 Slider in JColorChooser's HSB tab looks strange in Windows Look & Feel evaluated 4346256 5 5 sky Fri Jun 16 16:36:00 PDT 2000 3 Provide an AbstractTreeModel for the TreeModel hierarchy committed 4652898 4 3 naa@sparc.spb.su Thu Mar 14 00:15:00 PST 2002 6 Impossible to disable HTML Rendering in a JLabel accepted 4688168 5 3 sky Mon May 20 14:30:00 PDT 2002 0 AuxiliaryLAF test fails in Linux_ia64 as "java.lang.NumberFormatException" committed 4865016 4 5 aep@sparc.spb.su Thu May 15 16:39:00 PDT 2003 0 RFE: JSplitPane default divider size too big using Metal LNF evaluated 4432398 4 4 joutwate Fri Mar 30 15:25:00 PST 2001 1 Keyboard navigation doesn't respond in certain cases for Internal Frames evaluated 4466993 4 4 leif Wed Jun 06 16:30:00 PDT 2001 1 getAbsolutePath() returns incorrect path on Windows special folders evaluated 4503658 4 5 idk Mon Sep 17 13:04:00 PDT 2001 0 rfe: tweak height of text components for fonts with zero leading evaluated 4715271 4 4 joutwate Mon Jul 15 22:22:00 PDT 2002 1 Focus problem in MDI when using the right mouse button committed 4782925 5 4 idk Thu Nov 21 15:48:00 PST 2002 3 RFE: Can't override HTMLReader used for insertBeforeStart, insertAfterEnd, etc. accepted 4841188 4 4 idk Tue Apr 01 17:47:00 PST 2003 0 The caret is displayed on the character after the bold Japanese text. evaluated 4673850 4 4 shannonh Wed Apr 24 11:28:00 PDT 2002 0 Painting of MotifRadioButton (and other radio buttons) is faulty. accepted 4781412 4 3 shannonh Tue Nov 19 16:40:00 PST 2002 1 JSlider does not honor JLabels mnemonics accepted 4752713 4 4 leif Tue Sep 24 18:20:00 PDT 2002 11 Cannot sort on properties displayed on JFileChooser detailed view evaluated 4518448 4 4 leif Tue Oct 23 17:14:00 PDT 2001 0 JFileChooser: ShellFolder returns wrong volumeID after changing CDs accepted 4370709 4 5 joutwate Wed Sep 13 00:05:00 PDT 2000 0 JTabbedPane: add "visible" property to individual tabs evaluated 4737788 3 3 joutwate Tue Aug 27 17:23:00 PDT 2002 1 jframe undecorated cover taskbar when maximized evaluated 4203899 4 5 zav@sparc.spb.su Mon Jan 18 15:36:00 PST 1999 5 can't left-justify icons in a JMenuItem (need setDefaultTextIconGap()...) accepted 4776296 4 3 idk Fri Nov 08 00:40:00 PST 2002 0 Right justified text in JLabel prints badly aligned accepted 4166185 4 5 shannonh Thu Aug 13 09:59:00 PDT 1998 0 Metal: JRadioButton and JCheckBox has wrong border style evaluated 4822401 4 4 zav@sparc.spb.su Fri Feb 21 17:31:00 PST 2003 0 Disabled JMenuItem appearance is incorrect under Windows Look and Feel evaluated 4821426 4 4 kve@sparc.spb.su Thu Feb 20 11:57:00 PST 2003 1 JColorChooser doesn't pass "X" to cancel ActionListener accepted 4525630 4 4 dalem Fri Nov 09 16:15:00 PST 2001 0 Rename JTable get/setSurrenderFocusOnKeystroke accepted 4104452 4 5 shannonh Thu Jan 15 18:04:00 PST 1998 4 Proper keyboard navigation must be verified on JRadioButton for Windows LAF evaluated 4870789 4 4 sky Wed May 28 14:32:00 PDT 2003 0 RFE: UIDefaults.getUIError() hides real error accepted 4779988 4 4 aim Fri Nov 15 17:06:00 PST 2002 1 windows look&feel: standard button size is wrong committed 4778462 4 5 shannonh Wed Nov 13 16:06:00 PST 2002 3 RFE: JOptionPane.showConfirmDialog missing parameter for changing initialValue accepted 4745048 4 5 sky Tue Sep 10 16:33:00 PDT 2002 1 RFE: JFormattedTextField should allow null value/empty text accepted 4804458 3 3 joutwate Thu Jan 16 14:57:00 PST 2003 4 REGRESSION: Cancel doesn't work on ProgressMonitor started from Modal Dialog committed 4760077 4 3 sky Tue Oct 08 17:34:00 PDT 2002 0 Font sizes in JDK1.4 differ in table cells for editing and rendering committed 4469554 4 3 davidson@eng Wed Jun 13 15:05:00 PDT 2001 2 Toolbar Icon Buttons in 1.4 are too large committed 4292228 4 4 naoto Wed Nov 17 03:30:00 PST 1999 1 Hebrew and Arabic diacritical marks can not be edited in JTextComponents accepted 4839979 4 5 zpm@sparc.spb.su Mon Mar 31 04:34:00 PST 2003 0 TEST_BUG: RegTest javax/swing/text/View/4353673/bug4353673.java failed, Win32 evaluated 4866279 4 3 leif Mon May 19 14:50:00 PDT 2003 0 JInternalFrame XP L&F title bar height not machine OS settings committed 4820080 4 5 aep@sparc.spb.su Tue Feb 18 15:28:00 PST 2003 0 RFE: Cannot Change the JSplitPane Divider Color while dragging accepted 4513261 4 4 sky Wed Oct 10 17:48:00 PDT 2001 0 TreePath is inefficient and cannot be subclassed because ... evaluated 4191211 4 5 null Wed Nov 18 17:27:00 PST 1998 3 Allow editable JTable headers (e.g., to support database queries) evaluated 4194883 4 5 joutwate Thu Dec 03 19:17:00 PST 1998 4 Need API for setting default button for JOptionPane.show[Internal]ConfirmDialog evaluated 4456912 4 4 joutwate Thu May 10 05:33:00 PDT 2001 0 Demo SwingApplet failed to reload when the option start is choosed from the menu accepted 4778988 4 5 leif Thu Nov 14 11:59:00 PST 2002 0 CompoundBorder.isBorderOpaque() has incorrect documentation. evaluated 4481516 5 5 null Wed Jul 18 17:28:00 PDT 2001 16 RFE: JTable should have Excel's "Freeze Panes" feature evaluated 4816960 4 4 idk Tue Feb 11 15:47:00 PST 2003 0 1.3.0 Regression: BasicTextUI should check return value of getVisibleEditorRect committed 4730415 4 4 joutwate Mon Aug 12 17:49:00 PDT 2002 0 ProgressMonitor does not work properly when negative minimum is used evaluated 4863860 4 5 bchristi Wed May 14 10:38:00 PDT 2003 0 Windows LAF label foreground color is wrong accepted 4773488 4 3 leif Mon Nov 04 15:11:00 PST 2002 0 XP L&F: No hover effects for scrollbar controls committed 4802640 4 3 kyuka Mon Jan 13 17:34:00 PST 2003 2 JComboBox inconsistent with RIGHT_TO_LEFT Component Orientation committed 4765271 4 4 sdv@sparc.spb.su Fri Oct 18 11:47:00 PDT 2002 15 JEditorPane displays text larger than it should accepted 4783472 4 4 zpm@sparc.spb.su Fri Nov 22 00:30:00 PST 2002 0 HTMLEditorKit.read() uses the wrong parser accepted 4593054 4 5 dalem Tue Dec 11 14:42:00 PST 2001 7 dragging column in JTable should force scroll if needed accepted 4843574 3 3 leif Sun Apr 06 22:59:00 PDT 2003 0 GTK+ JFileChooser doesn't open multiple files evaluated 4298770 4 4 idk Sun Dec 12 03:01:00 PST 1999 2 RTFEditorKit.write(OutputStream, Document, int, int) works wrong for Cp037 accepted 4508043 4 3 joutwate Thu Sep 27 11:26:00 PDT 2001 5 cannot access JInternalFrame system menu via keyboard evaluated 4860100 3 3 bchristi Wed May 07 17:58:00 PDT 2003 0 XP L&F: Navigation bar icon spacing issues in JFileChooser evaluated 4855671 3 4 idk Tue Apr 29 00:10:00 PDT 2003 0 REGRESSION 1.4: Incorrect layout in JOptionPane when using custom component evaluated 4523678 4 4 dalem Tue Nov 06 00:32:00 PST 2001 2 Shared TableColumnModel resizing is faulty. accepted 4145308 4 5 null Wed Jun 03 00:11:00 PDT 1998 6 JTable hide/show columns evaluated 4723743 4 5 sky Wed Jul 31 11:52:00 PDT 2002 6 Java (Metal) Look And Feel Needs Makeover accepted 4852316 4 5 aep@sparc.spb.su Tue Apr 22 17:29:00 PDT 2003 0 JTree with DefaultTreeModel, asksAllowsChildren = true, expands root on updateUI evaluated 4549174 4 4 sky Wed Dec 05 18:38:00 PST 2001 2 RFE: DefaultListModel should have an addAll(Collection c) accepted 4202291 4 5 idk Mon Jan 11 18:38:00 PST 1999 40 long lines in wrapped JTextArea causes severe performance degradation evaluated 4486185 4 3 idk Mon Jul 30 18:49:00 PDT 2001 7 Provide method to return number of soft lines in JTextArea evaluated 4855860 4 5 idk Tue Apr 29 15:34:00 PDT 2003 1 JTextPane returns too large preferredSize in some specific cases evaluated 4760426 4 3 shannonh Wed Oct 09 10:00:00 PDT 2002 3 JTree DnD conflicts with JTree.setUI(..) committed 4702175 4 3 sky Thu Jun 13 19:11:00 PDT 2002 0 JScrollBar provide no focus feedback committed 4804344 4 5 sky Thu Jan 16 00:17:00 PST 2003 0 JTree should support + and - to expand and collapse nodes. committed 4526194 4 3 dalem Mon Nov 12 15:50:00 PST 2001 0 In JTable, Write headers vertically as well as multiline. evaluated 4841881 3 4 zav@sparc.spb.su Wed Apr 02 17:34:00 PST 2003 2 Alt tab with Windows L&F moves focus to the application menubar committed 4176095 4 5 moa@sparc.spb.su Thu Sep 24 09:34:00 PDT 1998 1 Clarification that no 2 Tabs in JTabbedPane can have same component evaluated 4127926 4 5 null Fri Apr 10 14:04:00 PDT 1998 14 Multi Line Column Headers in JTable evaluated 4315039 4 4 kyuka Wed Feb 23 17:46:00 PST 2000 1 Component Orientation: Text in textfield and list in combobox not right-to-left accepted 4286037 4 3 zpm@sparc.spb.su Thu Oct 28 17:54:00 PDT 1999 9 add styled text system clipboard support evaluated 4801881 3 3 shannonh Fri Jan 10 16:20:00 PST 2003 0 RFE: JTable can't (apparently) have varying CellEditors in a column evaluated 4826789 3 3 leif Mon Mar 03 21:10:00 PST 2003 0 Swing problems in supporting XPs DPI scaling committed 4202002 4 5 sky Sun Jan 10 17:19:00 PST 1999 15 JScrollPane: row header autoscrolling not reflected in content evaluated 4516633 4 4 shannonh Thu Oct 18 15:54:00 PDT 2001 0 Merlinb83: Metalworks Demo: Text not visible in Charcoal theme evaluated 4715176 4 5 sky Mon Jul 15 18:39:00 PDT 2002 0 RFE: PopupFactory difficult to customize, it has a bad interface accepted 4340338 5 5 joutwate Tue May 23 09:34:00 PDT 2000 0 rebuild of Swingset2 Demo performs un needed steps accepted 4682386 4 4 davidson@eng Thu May 09 10:41:00 PDT 2002 0 SwingPropertyChangeSupport and PropertyChangeSupport refactor project committed 4809538 3 3 zav@sparc.spb.su Tue Jan 28 16:09:00 PST 2003 3 Editable JComboBox may require two Enter keys to fire default button committed 4678007 4 3 sky Wed May 01 00:26:00 PDT 2002 10 JFormattedTextField with NumberFormatter - Backspace not working properly accepted 4835500 4 4 bchristi Thu Mar 20 15:06:00 PST 2003 0 JFileChooser/WindowsL&F: Enter key behaves incorrectly in Details view accepted 4079882 4 4 shannonh Wed Sep 17 15:32:00 PDT 1997 12 Request for JTristateCheckbox implementation evaluated 4765360 4 4 zav@sparc.spb.su Fri Oct 18 00:51:00 PDT 2002 10 JMenuItem.add(Action) does not handle Action.SHORT_DESCRIPTION properly committed 4404754 4 5 null Mon Jan 15 15:16:00 PST 2001 2 JTableHeader can incorrectly determine its height accepted 4799813 4 4 naa@sparc.spb.su Tue Jan 07 15:05:00 PST 2003 3 Leading HTML entities cause JEditorPane to eat following whitespace committed 4192877 4 5 joutwate Wed Nov 25 09:48:00 PST 1998 7 Solaris JDialog initial FOCUS prob...(was "setDefaultButton() won't work") evaluated 4404456 5 2 leif Fri Jan 12 15:27:00 PST 2001 0 Merlinb46:JFileChsr:In WinL&F File/Folder icon disappers when you try to rename evaluated 4860986 4 4 leif Thu May 08 23:33:00 PDT 2003 0 XP L&F: JTable headers are not showing roll over effect unlike native XP evaluated 4448318 4 5 joutwate Thu Apr 19 15:36:00 PDT 2001 0 ProgressMonitor does not make use of new JProgressBar indeterminate capability evaluated 4242649 4 3 shannonh Sun May 30 23:50:00 PDT 1999 0 Specify component used for JOptionPane.showInputDialog evaluated 4750270 4 3 shannonh Thu Sep 19 00:07:00 PDT 2002 0 1.4.0 REGRESSION: Action/Mouse event was lost after right-click popup menu committed 4469098 4 2 sky Tue Jun 12 17:45:00 PDT 2001 1 JOption pane does not provide HELP option evaluated 4487462 4 3 joutwate Thu Aug 02 11:17:00 PDT 2001 1 undocked JToolBar is not internal with JDesktop accepted 4275635 4 5 zpm@sparc.spb.su Sun Sep 26 16:27:00 PDT 1999 0 MenuDragMouseListener doesn't fire "exit" if drag moves to a JMenu accepted 4286335 4 4 kyuka Fri Oct 29 14:52:00 PDT 1999 1 TreeView in a ComboBox appears only as list in Right-to-Left orientation accepted 4849188 4 4 joutwate Wed Apr 16 04:11:00 PDT 2003 0 Tab traversing and selection border in GTK are not proper in SwingSet2 committed 4066394 4 5 shannonh Tue Jul 22 13:01:00 PDT 1997 5 ButtonGroup - cannot reset the model to the initial unselected state evaluated 4765246 5 5 sky Fri Oct 18 11:29:00 PDT 2002 1 JSpinner needs better ChangeEvent or better Event handling accepted 4406598 4 5 shannonh Sun Jan 21 13:00:00 PST 2001 7 Background attribute in JTextPane is not resolved to the parent style accepted 4811532 4 5 leif Fri Jan 31 16:27:00 PST 2003 0 The scrollbar width is not read in XP L&F committed 4791649 4 3 idk Tue Dec 10 15:35:00 PST 2002 0 Text components need printing support committed 4484185 5 5 joutwate Wed Jul 25 00:42:00 PDT 2001 0 ProgressMonitor popup won't back up, revisited accepted 4394642 4 3 zav@sparc.spb.su Mon Dec 04 08:35:00 PST 2000 0 JPopupMenu should implement isShowing() method committed 4757624 4 3 joutwate Thu Oct 03 15:25:00 PDT 2002 1 fonts truncated in multi line tabbed panel (windows & motif lnf) evaluated 4128116 4 5 null Sat Apr 11 00:11:00 PDT 1998 9 There is no JTable.ensureCellIsVisible analog evaluated 4131119 4 5 idk Tue Apr 21 11:58:00 PDT 1998 36 Add option to turn off/on word wrap in JTextPane evaluated 4799336 3 4 zav@sparc.spb.su Mon Jan 06 15:54:00 PST 2003 0 REGRESSION: JPopupMenu focus bug, inconsistent behaviour committed 4150635 4 3 davidson@eng Fri Jun 19 08:33:00 PDT 1998 0 Multiple problems with Separator in dynamic GUI environment evaluated 4298479 4 3 naoto Thu Dec 09 23:30:00 PST 1999 0 JEditorPane needs to by sync'd with other text fixes accepted 4310721 4 4 null Mon Feb 07 19:05:00 PST 2000 2 ViewportLayout does not stretch components, search: JTable background color accepted 4250070 4 3 naa@sparc.spb.su Mon Jun 28 09:53:00 PDT 1999 4 javax.swing.DefaultCaret's private API makes it very difficult to extend evaluated 4870679 4 4 sky Wed May 28 11:55:00 PDT 2003 0 JScrollPane w/ embedded JPanel and Graphics2D paintComponent accepted 4776221 4 4 shannonh Fri Nov 08 10:58:00 PST 2002 0 AbstractButton performance/footprint bugs accepted 4446468 4 5 joutwate Tue Apr 17 11:36:00 PDT 2001 2 Moving JInternalFrame over JDesktopPane's border in JScrollPane shows PixelTrash accepted 4712284 4 3 joutwate Tue Jul 09 15:05:00 PDT 2002 0 MouseListeners excited white moving frame with JDesktopPane OUTLINE_DRAG evaluated 4723782 4 4 joutwate Wed Jul 31 00:32:00 PDT 2002 0 JDesktopPane consumes every ESCAPE KeyEvent committed 4798757 4 4 zav@sparc.spb.su Fri Jan 03 00:23:00 PST 2003 0 Proposal for AbstractComboBoxModel committed 4337119 4 5 null Wed May 10 14:39:00 PDT 2000 0 SelectAll and RemoveAll in Jlist alters anchor and lead evaluated 4481910 4 4 leif Thu Jul 19 00:48:00 PDT 2001 0 Merlinb71:FileChooserDemo:Problem in "Files of Type" combobox evaluated 4473075 4 5 null Thu Jun 21 17:12:00 PDT 2001 12 JTable header rendering problem (after setting preferred size) accepted 4768841 3 3 joutwate Fri Oct 25 06:47:00 PDT 2002 1 Internal Frames are not operable via keyboard operations committed 4518295 4 3 zpm@sparc.spb.su Tue Oct 23 14:19:00 PDT 2001 5 JMenu not displayed correctly when number of JMenuItems is huge accepted 4690120 4 3 leif Wed May 22 16:26:00 PDT 2002 0 Network Access denied if there is a password protection accepted 4348167 4 5 leif Mon Jun 26 00:09:00 PDT 2000 0 Adding a JButton to a JToolBar sets RolloverEnabed to false. accepted 4674172 4 3 joutwate Wed Apr 24 17:39:00 PDT 2002 0 JDesktopPane icon layering does not persist correctly accepted 4684488 4 5 kyuka Mon May 13 21:35:00 PDT 2002 0 Some mnemonics in JColorChooser and JFileChooser can't be localized. committed 4804925 4 5 idk Fri Jan 17 00:20:00 PST 2003 0 RFE: DocumentEvent should subclass EventObject evaluated 4285225 4 5 joutwate Tue Oct 26 21:23:00 PDT 1999 7 Regression: JInternalFrame not activated on mouse clicks if glassPane replaced evaluated 4780631 4 3 sky Mon Nov 18 14:21:00 PST 2002 0 GTKLookAndFeel does not reverse buttons in JOptionPane with a RTL orientation committed 4664885 3 3 sharonz Mon Apr 08 23:21:00 PDT 2002 0 JCK1.4,interactive: api/javax_swing/interactive/BorderFactoryTests.html#BorderFa committed 4810921 4 5 gafter Thu Jan 30 17:35:00 PST 2003 0 in Tiger(1.5), enum is a keyword committed 4847025 3 5 zpm@sparc.spb.su Fri Apr 11 05:00:00 PDT 2003 0 RegTest-test javax/swing/JTextArea/4697612/bug4697612.java failed committed 4139092 4 5 joutwate Fri May 15 14:35:00 PDT 1998 0 Windows L&F: "move" & "size" in JInternalFrame-Icon-PopupMenu always disabled evaluated 4491591 5 5 sky Tue Aug 14 01:00:00 PDT 2001 0 Java2D Demo - Arcs_Curves - Choice box is not painted correctly (Solsparc) evaluated 4712078 4 5 leif Tue Jul 09 08:54:00 PDT 2002 0 JFileChooser: Truncation in Windows Look and Feel evaluated 4869035 5 5 sky Fri May 23 00:16:00 PDT 2003 0 GTK L&F: Some colors which make up a wiget are not the same color as the platfor accepted 4172008 4 3 zav@sparc.spb.su Tue Sep 08 13:17:00 PDT 1998 0 getLocation() for first menu item overlaps menu header evaluated 4624069 4 4 zpm@sparc.spb.su Tue Jan 15 15:41:00 PST 2002 0 JLabel with HTML text uses improper line spacing. accepted 4335575 4 2 zav@sparc.spb.su Wed May 03 19:17:00 PDT 2000 0 Set unlisted item in JComboBox does not work for Windows L&F evaluated 4823912 4 4 sdv@sparc.spb.su Tue Feb 25 17:57:00 PST 2003 0 JTextPane getText() discards embedded HTML Stylesheet information evaluated 4466014 4 4 sky Mon Jun 04 16:09:00 PDT 2001 1 BasicUI delegates explicitly mention BasicLookAndFeel evaluated 4478121 4 4 dalem Tue Jul 10 10:44:00 PDT 2001 0 Descenders get cut off by DefaultCellEditor accepted 4607161 4 3 leif Thu Dec 13 11:59:00 PST 2001 0 File system level information not available through the ShellFolder class evaluated 4869100 5 5 sky Fri May 23 13:58:00 PDT 2003 0 GTK L&F: ColorChooser: Java PLAF does not have "paint dropper" accepted 4214074 4 5 joutwate Tue Feb 23 00:29:00 PST 1999 1 JInternalFrame not closable in Windows L&F doesn't look right evaluated 4836639 2 2 joutwate Mon Mar 24 11:10:00 PST 2003 0 Creating components in XP L&F throws OutOfMemoryError. committed 4817453 4 5 shannonh Wed Feb 12 00:13:00 PST 2003 0 Selecting all rows in JTable using mouse is inconsistent evaluated 4326639 4 5 leif Thu Mar 30 18:53:00 PST 2000 4 JFileChooser does not handle Security Exceptions on Windows platform accepted 4700552 5 4 sky Tue Jun 11 00:01:00 PDT 2002 0 RFE: Can't inherit the icons of a LookAndFeel for a custom LookAndFeel evaluated 4813403 4 5 sky Wed Feb 05 11:16:00 PST 2003 0 Enter key binding not working for JTree evaluated 4410401 4 5 zav@sparc.spb.su Wed Jan 31 14:08:00 PST 2001 1 JComboBox: ListCellRenderer and the KeySelectionManager must use the same values evaluated 4129681 4 5 leif Thu Apr 16 13:27:00 PDT 1998 2 Cannot get a title border to display its label as disabled evaluated 4475576 4 4 zav@sparc.spb.su Wed Jun 27 18:11:00 PDT 2001 5 PopupMenuUI.isPopupTrigger() does not behave in a L&F dependant way accepted 4811528 4 3 leif Fri Jan 31 16:25:00 PST 2003 0 Sorting support in swing filedialog evaluated 4732198 4 4 zav@sparc.spb.su Thu Aug 15 11:54:00 PDT 2002 1 Extra MouseDrag Events cause JPopupMenu flicker committed 4778929 4 4 leif Thu Nov 14 10:48:00 PST 2002 1 javax.swing.ToolTipManager memory leak. accepted 4811075 4 3 sky Thu Jan 30 20:39:00 PST 2003 0 Optimize swing UI latency accepted 4863821 4 4 kwalrath Wed May 14 09:53:00 PDT 2003 0 Documentation for "MetalTheme" class is inaccurate committed 4748141 4 4 joutwate Mon Sep 16 14:47:00 PDT 2002 15 First JInternalFrame added to a JDesktop causes memory leak evaluated 4693132 5 4 leif Wed May 29 11:38:00 PDT 2002 0 RFE: Add functionality to show invisible elements of Toolbar accepted 4499556 5 5 joutwate Tue Sep 04 15:41:00 PDT 2001 37 Use arbitrary (J)Components as JTabbedPane tab labels. evaluated 4774895 4 3 naa@sparc.spb.su Wed Nov 06 14:51:00 PST 2002 1 Adding whitespace when displaying arabic characters with HTML tag evaluated 4222149 4 4 null Fri Mar 19 13:23:00 PST 1999 5 JTable : starting to type should overwrite cell contents evaluated 4243496 4 3 idk Wed Jun 02 19:28:00 PDT 1999 0 JTextComponent margin is bound to components border accepted 4765367 3 3 bchristi Fri Oct 18 13:00:00 PDT 2002 0 Crash in JFileChooser when twice show after setCurrentDirectory not canonical evaluated 4683398 4 4 joutwate Fri May 10 16:41:00 PDT 2002 2 WindowsDesktopManager mantains a strong reference to currentFrame evaluated 4737210 4 3 zav@sparc.spb.su Tue Aug 27 00:59:00 PDT 2002 0 Wrong Menu Behavior on Solaris evaluated 4636235 4 3 idk Mon Feb 11 16:14:00 PST 2002 2 HTMLEditorKit.create() cannot handle some element types. accepted 4147468 4 5 zav@sparc.spb.su Wed Jun 10 00:48:00 PDT 1998 0 Combo-box with no drop-down entries should disable the drop-down control evaluated 4616052 4 4 dalem Wed Dec 19 11:09:00 PST 2001 0 JListGetVisibleIndexTest.java, Last visible index is not calculated correctly accepted 4760463 4 4 zav@sparc.spb.su Wed Oct 09 10:20:00 PDT 2002 0 MetalComboBoxUI computes wrong sizes if user-defined ArrowButton is used. accepted 4697750 4 3 naa@sparc.spb.su Wed Jun 05 15:16:00 PDT 2002 0 HTMLEditorKit: Caret doesn't move into table when using BS just outside the end accepted 4531811 4 3 joutwate Tue Nov 27 00:12:00 PST 2001 4 JInternalFrame.setFrameIcon() mis-positions/sizes icons in Win L&F accepted 4860691 4 4 leif Thu May 08 14:39:00 PDT 2003 0 Win L&F: Focus cursor doesn't dim on JTree nodes when tree loses focus with Win evaluated 4730041 4 3 sky Mon Aug 12 10:22:00 PDT 2002 1 Request a Date Selector or DateChooser feature that works like JColorChooser. evaluated 4242016 4 4 idk Thu May 27 16:16:00 PDT 1999 0 the UndoAction (undo) in the Notepad.java not work well evaluated 4821584 4 4 sky Thu Feb 20 14:56:00 PST 2003 0 javax.swing.UIDefaults does not comply with Collection API accepted 4855131 3 3 leif Mon Apr 28 15:28:00 PDT 2003 0 XP L&F: JSlider should not be surrounded by dashed box with focus committed 4774766 4 5 joutwate Wed Nov 06 11:50:00 PST 2002 0 Ability to register event handler for tabpane's header, add buttons, components accepted 4212722 4 5 idk Thu Feb 18 00:16:00 PST 1999 13 Swing JEditorPane + HTMLEditorKit bombs on complex layouts accepted 4868032 3 5 zpm@sparc.spb.su Wed May 21 21:37:00 PDT 2003 0 TEST_BUG: RegTest-test javax/swing/JPopupMenu/PopupTest/MenuTester.java fails evaluated 4527906 4 2 dalem Thu Nov 15 16:07:00 PST 2001 0 JList: Page-up/Page-down scrolling of JFileChooser: not even close... evaluated 4767368 4 4 sky Wed Oct 23 10:29:00 PDT 2002 0 RFE: javax.swing.DefaultListModel lacks toArray(Object[]) accepted 4154448 4 5 joutwate Thu Jul 02 16:46:00 PDT 1998 106 JInternalFrame needs Heavy Implementation evaluated 4488430 4 4 kyuka Mon Aug 06 01:23:00 PDT 2001 0 JList.getLastVisibleIndex() returns -1 for a HORIZONTAL_WRAP list accepted 4188876 4 2 joutwate Tue Nov 10 16:48:00 PST 1998 0 Command buttons are centered at bottom of JL&F dialogs evaluated 4135408 4 3 sky Tue May 05 16:56:00 PDT 1998 0 Should be able to suppress undo/redo temporarily evaluated 4816922 4 4 shannonh Tue Feb 11 14:58:00 PST 2003 2 No way to set drag icon: TransferHandler.getVisualRepresentation() is not used evaluated 4615460 3 5 leif Tue Dec 18 14:25:00 PST 2001 1 Enhancements to Swing/JFileChooser for IDE tools committed 4760086 4 3 sky Tue Oct 08 17:41:00 PDT 2002 0 Navigation restrictions in JFormattedTextField are ignored by Home key accepted 4736167 5 5 idk Fri Aug 23 00:07:00 PDT 2002 0 RFE: DefaultEditorKit should expose nested class for select-all action accepted 4225831 4 4 sky Wed Mar 31 17:41:00 PST 1999 1 The JTree and JTable ActionEvent evaluated 4519335 5 5 zpm@sparc.spb.su Thu Oct 25 11:09:00 PDT 2001 0 JPopupMenu api needs getItemCount() and getItem(int) as in JMenu accepted 4706304 3 4 zav@sparc.spb.su Fri Jun 21 00:19:00 PDT 2002 0 REGRESSION: JPopupMenu doesn't highlight selection on initial click evaluated 4519482 4 4 idk Thu Oct 25 14:26:00 PDT 2001 10 RFE: Enhancement to TableView in HTMLEditorKit by subclassing evaluated 4199382 4 3 zpm@sparc.spb.su Tue Dec 22 14:27:00 PST 1998 9 Swing Menus - text/icon/checkmark alignment schemes severely broken evaluated 4756152 4 4 leif Tue Oct 01 11:58:00 PDT 2002 0 JFileChooser Does trim() Only for Single Selection Mode evaluated 4860982 4 4 leif Thu May 08 23:16:00 PDT 2003 0 XP L&F: tool tip does not show the fading effect as native evaluated 4302560 4 5 naa@sparc.spb.su Tue Jan 04 14:13:00 PST 2000 1 AsynchronousMovement property of DefaultCaret not accessible evaluated 4273479 4 5 idk Mon Sep 20 10:16:00 PDT 1999 1 Make TagElement members and default constructor protected evaluated 4717365 4 3 leif Fri Jul 19 02:34:00 PDT 2002 0 JVM Crashes during stressed file access evaluated 4765238 5 5 sky Fri Oct 18 11:21:00 PDT 2002 0 SingleSelectionModel as JList selection model accepted 4841760 4 4 idk Wed Apr 02 15:00:00 PST 2003 0 No HTML tags shown for StyleEditorKit.ForegroundAction() in JTextPane output. accepted 4607364 3 5 sky Thu Dec 13 15:53:00 PST 2001 3 Improve default L&F of Swing. committed 4786415 3 3 zav@sparc.spb.su Thu Nov 28 23:33:00 PST 2002 0 JCK1.4a-runtime api/javax_swing/interactive/JPMenuTests.html#JPMenuTests fails evaluated 4722445 4 5 sky Mon Jul 29 15:56:00 PDT 2002 1 RFE: Ability to specify constraints on center of components in a SpringLayout accepted 4198130 4 5 null Wed Dec 16 22:16:00 PST 1998 8 JTable selection model accepted 4779001 4 4 sky Thu Nov 14 00:15:00 PST 2002 0 Unexpected behavior of javax.swing.Spring.max() evaluated 4239028 4 2 kyuka Mon May 17 22:01:00 PDT 1999 10 setMnemonic(char) must support non-english characters evaluated 4862398 4 4 shannonh Mon May 12 10:24:00 PDT 2003 3 RFE: New ways for specifying table column width in JTable evaluated 4175150 4 4 leif Mon Sep 21 13:11:00 PDT 1998 0 api/javax_swing/border/BevelBorder/index.html#Ctor fails on MP in runtime "K" accepted 4843282 3 3 sky Fri Apr 04 15:57:00 PST 2003 1 UIManager.getInstalledLookAndFeels() returns bogus info on Linux. committed 4795374 4 4 sky Tue Dec 17 19:29:00 PST 2002 0 GTK+ L&F doesn't change on-the-fly committed 4358979 4 5 davidson@eng Wed Aug 02 18:33:00 PDT 2000 0 javax.swing.border should have a DashedBorder evaluated 4425860 4 5 idk Wed Mar 14 18:35:00 PST 2001 1 RFE: please make TextLayoutStrategy, GlyphPainter2 public or protected evaluated 4459452 4 5 null Wed May 16 11:03:00 PDT 2001 0 SizeRequirements.calculateTiledPositions() overflows allocated space accepted 4362633 4 5 leif Tue Aug 15 08:16:00 PDT 2000 0 Frame window overrides dropped down menu, when gets the focus. accepted 4722579 4 4 shannonh Mon Jul 29 18:18:00 PDT 2002 1 Autoscroll during drag-and-drop sometimes does not scroll. committed 4772326 4 3 sky Thu Oct 31 16:40:00 PST 2002 0 copy to clipboard from JList fails committed 4792931 4 4 joutwate Thu Dec 12 11:23:00 PST 2002 0 First key press not being recognized with InputVerifier, JOptionPane, and Tab committed 4198272 5 5 sky Thu Dec 17 10:48:00 PST 1998 6 JScrollPane has setColumnHeader but not a setColumnFooter evaluated 4400417 4 4 zav@sparc.spb.su Thu Dec 21 20:21:00 PST 2000 0 JComboBox in the table has some strange behavior evaluated 4863833 4 5 zav@sparc.spb.su Wed May 14 10:08:00 PDT 2003 1 JComboBox loses focus when change to HighContrast mode evaluated 4790519 4 3 shannonh Mon Dec 09 04:47:00 PST 2002 0 GTK L&F : Table Column Headers do not show rollover effects evaluated 4802383 4 4 leif Mon Jan 13 00:03:00 PST 2003 0 JFileChooser makes unecessary security checks accepted 4846416 4 5 sky Thu Apr 10 11:47:00 PDT 2003 0 RFE: Provide UIDefault for a PLAF's Menu Shortcut mask accepted 4413530 4 4 joutwate Thu Feb 08 15:24:00 PST 2001 0 Merlinb50:SwingSet2 Demo:Maximizable, Iconifiable checkboxes missing in MotifL&F evaluated 4852215 5 5 shannonh Tue Apr 22 15:34:00 PDT 2003 0 NullPointerException inside of TableCellEditor.stopCellEditing evaluated 4736666 4 5 idk Mon Aug 26 06:29:00 PDT 2002 0 RFE: Improvements to javax.swing.text.html.parser accepted 4419001 4 5 leif Mon Feb 26 00:10:00 PST 2001 4 ToolTip should not _always_ be on top evaluated 4531899 4 4 joutwate Tue Nov 27 14:54:00 PST 2001 0 JInternalFrame changes size first time an element is added to a list accepted 4681682 4 4 sky Wed May 08 11:32:00 PDT 2002 0 RFE: Include SwingWorker with the JDK evaluated 4748383 4 4 leif Mon Sep 16 20:04:00 PDT 2002 2 Selecting "My Computer" in the JFileChooser fails if no disk in Zip Drive accepted 4737751 4 2 leif Tue Aug 27 16:40:00 PDT 2002 1 jfilechooser should ask for cdrom evaluated 4806616 4 4 sky Wed Jan 22 14:45:00 PST 2003 0 No documentation for MetalLookAndFeel.setCurrentTheme() committed 4479072 4 3 idk Thu Jul 12 08:48:00 PDT 2001 1 HTMLEditorKit uses always default editor kit for rendering of frames evaluated 4732785 4 4 sky Fri Aug 16 11:51:00 PDT 2002 1 RFE: provide implementation for StateEdit.isSignificant() accepted 4223089 4 1 idk Tue Mar 23 00:28:00 PST 1999 10 Add ability to print a multi-page HTML document from an off-screen JEditorPane committed 4749723 4 4 sky Wed Sep 18 15:48:00 PDT 2002 1 The javax.swing.Spring class needs a "scale" operator to make centering easier. accepted 4836615 4 4 sky Mon Mar 24 10:28:00 PST 2003 0 JRootPane.getGlassPane.getName() returns null.glassPane instead of null accepted 4869029 5 5 leif Fri May 23 00:08:00 PDT 2003 0 GTK L&F: Internal Frames Crux graphics do not match platforms graphics committed 4351798 4 5 leif Mon Jul 10 00:57:00 PDT 2000 0 print a panel on more than one page i.e(clipping the panel) evaluated 4703127 4 5 zpm@sparc.spb.su Mon Jun 17 06:11:00 PDT 2002 0 1.4.0 REGRESSION: JEditorPane does not work as expected evaluated 4857700 3 4 leif Fri May 02 10:04:00 PDT 2003 0 JFileChooser: Not showing some folders in "Look In:" combo box after L&F change committed 4468566 4 5 shannonh Mon Jun 11 18:09:00 PDT 2001 6 Swing DnD should not use selection to show drop location evaluated 4760082 4 3 naa@sparc.spb.su Tue Oct 08 17:38:00 PDT 2002 13 AbstractDocument.remove(int,int) breaks HTMLDocument structure evaluated 4862115 4 3 leif Sun May 11 05:00:00 PDT 2003 0 No title shown on minimized JInternalFrame - GTK LAF evaluated 4862679 3 3 leif Mon May 12 16:31:00 PDT 2003 0 XP L&F: JTabbedPane selected tab background color is wrong committed 4651849 4 3 dalem Tue Mar 12 18:51:00 PST 2002 3 After Clicking in JComboBox Table Cell, Arrow and Enter Key cannot select. accepted 4727030 5 5 joutwate Tue Aug 06 00:00:00 PDT 2002 0 RFE: Provide Scrollbar without Buttons accepted 4775789 3 3 sky Thu Nov 07 16:38:00 PST 2002 1 REGRESSION: JTable rendering/editing problem with JComboBox committed 4841903 4 3 shannonh Wed Apr 02 17:58:00 PST 2003 0 JTable.setEnabled(false) does not alter its visual representation accepted 4512626 4 3 shannonh Tue Oct 09 16:20:00 PDT 2001 1 Non-editable JTextArea provides no visual indication of keyboard focus committed 4220821 4 3 null Tue Mar 16 00:05:00 PST 1999 0 table keyboard focus uses incorrect color in JLF evaluated 4487103 4 3 joutwate Wed Aug 01 16:21:00 PDT 2001 6 Focus issues with JInternalframe accepted 4765316 4 5 leif Fri Oct 18 00:21:00 PDT 2002 0 REGRESSION: FileSystemView.getFiles() no longer works with relative paths evaluated 4860104 3 3 joutwate Wed May 07 18:06:00 PDT 2003 1 REGRESSION: JInternalFrame icons not resized correctly in Windows LAF evaluated 4354065 4 5 leif Tue Jul 18 00:25:00 PDT 2000 12 JFileChooser multifile selection behaves incorrectly accepted 4690812 4 3 sdv@sparc.spb.su Thu May 23 15:53:00 PDT 2002 0 poor formatting of complex pages by JEditorPane, e.g. java.sun.com accepted 4530474 4 3 sdv@sparc.spb.su Wed Nov 21 13:47:00 PST 2001 0 background-color CSS attribute in HTML font tag works in style but not class accepted 4713905 4 2 naoto Thu Jul 11 23:56:00 PDT 2002 0 Cannot display some strings in JTextField in RTL component orientation. accepted 4861882 3 5 leif Fri May 09 15:34:00 PDT 2003 0 JFileChooser UI code cleanup committed 4866958 5 5 joutwate Tue May 20 15:08:00 PDT 2003 0 Focus bug with JList in a scrollpane accepted 4498679 4 4 leif Fri Aug 31 09:11:00 PDT 2001 2 Separator line between JMenu and JToolBar displays incorrect in Windows L&F accepted 4854826 4 3 sky Mon Apr 28 07:26:00 PDT 2003 0 Painting - Border, ContentAreaFill, Focus cannot be supressed in GTK - Button evaluated 4715510 4 3 shannonh Tue Jul 16 11:38:00 PDT 2002 0 DefaultTableColumnModel#propertyChange() should use String.equals() not == evaluated 4859578 4 5 bchristi Wed May 07 04:37:00 PDT 2003 0 Enter key does not work for JFileChooser buttons accepted 4395239 5 5 leif Tue Dec 05 15:24:00 PST 2000 2 JFileChooser setup performance bad evaluated 4710675 4 5 kyuka Wed Jul 03 03:01:00 PDT 2002 0 JTextArea.setComponentOrientation does not work with correct timing accepted 4799833 4 4 sharonz Tue Jan 07 15:25:00 PST 2003 0 JOptionPane show dialog methods have bad doc for first parameter evaluated 4412522 4 3 sdv@sparc.spb.su Tue Feb 06 17:17:00 PST 2001 0 HTML that has comments inside of tables is not rendered correctly evaluated 4138755 4 5 null Thu May 14 17:21:00 PDT 1998 14 No focus lost event in JTable when editing evaluated 4696824 5 5 sky Tue Jun 04 08:47:00 PDT 2002 0 In MetalLookAndFeel Button.focusInputMap, CheckBox.focusInputMap ... are same accepted 4413412 4 5 leif Thu Feb 08 00:27:00 PST 2001 6 Mouse Events intercepted by Tooltip accepted 4823064 4 4 sky Mon Feb 24 14:30:00 PST 2003 1 RFE: Additional Constructor for AbstractUndoableEdit to allow for undone edits. accepted 4760078 4 5 zav@sparc.spb.su Tue Oct 08 17:35:00 PDT 2002 0 JComboBox with empty item list generates spurious ActionEvent when focus lost accepted 4673445 4 4 zav@sparc.spb.su Tue Apr 23 18:02:00 PDT 2002 0 No scroll bar in menu if there are more than 30 menu items accepted 4665148 3 4 sky Tue Apr 09 00:27:00 PDT 2002 0 JavaDoc for JScrollPane.isValidateRoot is wrong. committed 4811086 4 4 leif Thu Jan 30 21:48:00 PST 2003 1 Support use of native Filedialogs in Swing evaluated 4103470 5 4 leif Mon Jan 12 16:20:00 PST 1998 7 JToolBar should control visibility of Labels/Icons/Tooltips of contained buttons evaluated 4853604 4 5 sky Thu Apr 24 13:43:00 PDT 2003 0 Add IconFactory to Swing accepted 4770133 4 4 leif Mon Oct 28 17:36:00 PST 2002 0 JFileChooser.addChoosableFileFilter documentation should mention multithreading evaluated 4463508 4 4 leif Sun May 27 03:06:00 PDT 2001 0 JToolTip fails to execute under WindowsLookAndFeel if .pack() method is used evaluated 4267730 4 5 mca Wed Sep 01 11:55:00 PDT 1999 0 lack of cross platform general icons evaluated 4144757 4 5 shannonh Tue Jun 02 06:48:00 PDT 1998 4 Dialog dismissing by Escape key evaluated 4819813 4 5 joutwate Tue Feb 18 09:51:00 PST 2003 0 JLF window decorations are focusable (bad for InputVerifier) accepted 4250999 4 5 leif Wed Jun 30 17:19:00 PDT 1999 3 Capability to disable directory traversal in JFileChooser evaluated 4869950 3 3 leif Tue May 27 11:07:00 PDT 2003 0 NPE if JFileChooser.setCurrentDirectory() called twice with non-canonical file evaluated 4711700 4 4 leif Mon Jul 08 15:54:00 PDT 2002 2 NullPointerException in JFileChooser when accessing system level icons evaluated 4334733 4 4 leif Mon May 01 15:34:00 PDT 2000 0 Incomplete API Documentation for JToolbar Drag Properties accepted 4502804 5 5 shannonh Thu Sep 13 15:51:00 PDT 2001 1 FontSmoothing/AntiAlias not utilized by default despite OS setting committed 4752911 3 3 joutwate Wed Sep 25 05:43:00 PDT 2002 0 JInternalFrame's controlling buttons are not exposed committed 4526682 5 5 shannonh Tue Nov 13 13:12:00 PST 2001 0 Add two showInternalInputDialog() convenience methods to JOptionPane evaluated 4143856 4 5 sky Fri May 29 10:25:00 PDT 1998 26 JList does not have cell editors committed 4479331 4 3 idk Thu Jul 12 16:30:00 PDT 2001 0 Swing JTextComponents not clearing primary clipboard after text deselection evaluated 4729669 3 3 zav@sparc.spb.su Fri Aug 09 18:06:00 PDT 2002 0 1.4 REGRESSION: Text edge of different types of JMenuItems are not aligned committed 4663490 5 5 sky Fri Apr 05 00:43:00 PST 2002 0 Swing's .properties files should be written in better way for L10N engineers. accepted 4812431 3 3 zav@sparc.spb.su Mon Feb 03 23:57:00 PST 2003 0 REGRESSION: Metal JMenuItem text rendered with wrong color evaluated 4857254 4 4 bchristi Thu May 01 15:29:00 PDT 2003 0 REGRESSION: JFileChooser: ListSelectionModel displays wrong selection accepted 4365952 4 5 leif Fri Aug 25 14:17:00 PDT 2000 0 Cannot disable JFileChooser accepted 4760081 3 3 sky Tue Oct 08 17:37:00 PDT 2002 1 1.4 REGRESSION: JTree, JTable: rowHeight is too small to fit large fonts. committed 4845945 4 3 kyuka Wed Apr 09 16:28:00 PDT 2003 0 JScrollPane does not layout properly with RTL (RIGHT_TO_LEFT) committed 4302970 4 5 joutwate Thu Jan 06 09:30:00 PST 2000 1 WindowsDesktopManager does not look and feel like Windows evaluated 4865071 3 2 leif Thu May 15 17:51:00 PDT 2003 1 XP L&F: REGRESSION: setBackground has no effect on JTextField in Windows XP committed 4310802 4 4 idk Tue Feb 08 06:27:00 PST 2000 1 HTMLEditorKit does not parse TAGs for Cp037 character encoding accepted 4751990 5 4 zav@sparc.spb.su Mon Sep 23 18:52:00 PDT 2002 0 PopupMenuListener.popupMenuCancelled refactoring accepted 4760094 4 4 shannonh Tue Oct 08 17:54:00 PDT 2002 3 JTable-AUTO_RESIZE_ LAST_COLUMN works only for fixed table width accepted 4715272 4 4 joutwate Mon Jul 15 22:30:00 PDT 2002 2 Focus problem when poping up a menu and selecting a JInternalFrame committed 4287891 4 4 kyuka Thu Nov 04 02:17:00 PST 1999 0 JFileChooser fails to identify RTL encoded directory name accepted 4765336 4 4 joutwate Fri Oct 18 00:34:00 PDT 2002 1 JDesktopPane.getSelectedFrame() should return null after removing selected frame committed 4854174 5 3 bchristi Fri Apr 25 11:30:00 PDT 2003 0 FileSystemView.getSystemIcon throws NPE for bad soft links evaluated 4866977 3 3 idk Tue May 20 15:33:00 PDT 2003 0 RTL HTML Table fails under JDK1.4.1 and JDK1.4.2, DIR TAG is not supported dispatched 4794122 3 2 joutwate Mon Dec 16 04:14:00 PST 2002 0 GTK L&F : Minimized internal Frames do not have title border evaluated 4738983 4 5 shannonh Thu Aug 29 09:46:00 PDT 2002 0 JMenuItem.setIconTextGap does nothing accepted 4860669 4 3 naoto Thu May 08 14:22:00 PDT 2003 0 Bugs with \n and \t characters when committing composed text evaluated 4864304 3 3 sky Wed May 14 18:08:00 PDT 2003 0 Improve memory consumption of Swing apps committed 4831322 5 5 joutwate Wed Mar 12 11:21:00 PST 2003 0 JDesktopPane.setDesktopManager should update the desktop manager at the UI. accepted 4859017 2 1 zav@sparc.spb.su Tue May 06 08:31:00 PDT 2003 0 JMenu.add now requires AWTPermission listenToAllAWTEvents dispatched 4840271 4 5 leif Mon Mar 31 14:20:00 PST 2003 0 TitledBorder Bug of API Documentation or Bug of Specification evaluated 4138555 4 3 shannonh Thu May 14 00:04:00 PDT 1998 1 JDK1.2Beta4-F,Win95,window look: buttons not painting focus evaluated 4519484 4 3 shannonh Thu Oct 25 14:27:00 PDT 2001 1 please allow setting a TransferHandler for a JFrame evaluated 4644241 4 4 idk Wed Feb 27 14:32:00 PST 2002 0 Need API to set BreakIterator of JTextComponent accepted 4180963 4 5 zav@sparc.spb.su Tue Oct 13 08:19:00 PDT 1998 0 DefaultComboBoxModel enhancements evaluated 4805829 4 4 joutwate Tue Jan 21 11:54:00 PST 2003 0 Tabbing from single focusable field doesn't trigger verify committed 4834399 4 4 naa@sparc.spb.su Tue Mar 18 19:20:00 PST 2003 0 invokeLater causes JScrollPane to scroll to bottom at creation committed 4465795 4 4 null Mon Jun 04 10:57:00 PDT 2001 0 javax.swing.JTable.isRowSelected() does not throw IAE accepted 4835469 4 4 bchristi Thu Mar 20 14:38:00 PST 2003 0 JFileChooser/Windows L&F: Newly created directories should appear at end of list accepted 4200554 4 5 joutwate Mon Jan 04 17:27:00 PST 1999 1 Please make canceled property of ProgressMonitor bound accepted 4208273 4 3 null Wed Feb 03 01:33:00 PST 1999 5 JTable.getScrollableUnitIncrement(...) returns incorrect value accepted 4491747 4 4 davidson@eng Tue Aug 14 11:02:00 PDT 2001 3 RFE: Use of Action still needs work committed 4045249 4 4 idk Tue Apr 15 14:07:00 PDT 1997 5 rfe: JTextArea should be capable of printing entire contents by default evaluated 4743544 4 4 naoto Sun Sep 08 20:33:00 PDT 2002 1 Paste with mouse button to JTextField during converiosn causes Exception. committed 4850302 4 4 idk Thu Apr 17 14:49:00 PDT 2003 0 JEditorPane fails on HTML Frames with java.lang.ArrayIndexOutOfBoundsException accepted 4580622 5 4 joutwate Sun Dec 09 18:02:00 PST 2001 0 JSlider has "getInverted"method instead of "isInverted" evaluated 4714237 4 5 shannonh Fri Jul 12 00:15:00 PDT 2002 7 RFE: Ability to set row height in a JTable to zero evaluated 4133566 5 5 aep@sparc.spb.su Wed Apr 29 00:10:00 PDT 1998 6 DefaultListSelectionModel: buggy insertIndexInterval() accepted 4622892 4 4 leif Fri Jan 11 18:21:00 PST 2002 9 FileSystemView.getSystemIcon crashes Windows accepted 4865605 4 5 leif Fri May 16 14:49:00 PDT 2003 0 XP L&F: Java Tooltips and Menus do not have drop shadow evaluated 4833524 4 4 aep@sparc.spb.su Mon Mar 17 11:49:00 PST 2003 19 BasicTreeUI.isToggleSelectionEvent() does not properly handle popup triggers accepted 4858661 4 5 bchristi Mon May 05 16:35:00 PDT 2003 0 JFileChooser cant select drives with FILES_AND_DIRECTORIES mode accepted 4836408 4 5 sharonz Sun Mar 23 17:51:00 PST 2003 0 Incorrect description in demo/jfc/TableExample/README.txt committed 4449413 4 3 shannonh Mon Apr 23 14:31:00 PDT 2001 10 JCheckBox can't show check when the background color is black accepted 4860546 2 3 leif Thu May 08 00:06:00 PDT 2003 0 Swing Bug with JToolBar and focus committed 4465732 4 4 null Mon Jun 04 09:09:00 PDT 2001 0 javax.swing.JTable.isCellSelected() does not throw IAE accepted 4509382 4 3 zav@sparc.spb.su Mon Oct 01 16:51:00 PDT 2001 0 up/down arrow selection doesn't work for options menu on alarm tab accepted 4711979 4 4 katakai Tue Jul 09 03:36:00 PDT 2002 0 Cannot select a multibyte character in the right hand side of the line. evaluated 4765279 4 3 shannonh Fri Oct 18 11:54:00 PDT 2002 1 DefaultTableCellRenderer.getTableCellRendererComponent() throws NullPointerExc. accepted 4429033 4 5 leif Thu Mar 22 00:57:00 PST 2001 2 ToolTip location stipulation requested (JComponent.setToolTipLocation(Point)) evaluated 4486696 4 2 sky Tue Jul 31 19:44:00 PDT 2001 2 JViewport does not scroll diagonally efficiently accepted 4706356 4 5 sky Fri Jun 21 13:09:00 PDT 2002 0 DefaultTableCellRenderer should override more methods accepted 4850870 4 4 aep@sparc.spb.su Fri Apr 18 13:09:00 PDT 2003 0 Apparent bug in Box layout accepted 4784677 3 2 joutwate Tue Nov 26 01:05:00 PST 2002 0 XP L&F: JSliders do not show rollover and drag effects evaluated 4716935 3 3 sky Thu Jul 18 11:20:00 PDT 2002 0 JLayeredPane should override removeAll to avoid leak committed 4521075 4 4 shannonh Tue Oct 30 11:19:00 PST 2001 117 Drag gesture in JAVA different from Windows committed 4298811 4 5 shannonh Sun Dec 12 22:26:00 PST 1999 0 Improve JOptionPane's layout when adding a resizable Component evaluated 4685800 4 3 joutwate Wed May 15 16:07:00 PDT 2002 8 JTabbedPane.setOpaque(false) does not follow opacity rules evaluated 4740942 4 4 zav@sparc.spb.su Tue Sep 03 15:17:00 PDT 2002 1 First MenuItem on JPopupMenu is Highlighted accepted 4760512 4 4 zav@sparc.spb.su Wed Oct 09 11:05:00 PDT 2002 1 JComboBox.KeySelectionManager should not register a shift key evaluated 4318672 4 4 leif Fri Mar 03 00:12:00 PST 2000 1 double clicking on directory entries occasionally opens the directory as a file accepted 4802656 4 4 zav@sparc.spb.su Mon Jan 13 18:02:00 PST 2003 0 Problem with keyboard navigation in JMenus JMenuItems if setVisible(false) committed 4203037 4 5 leif Thu Jan 14 06:14:00 PST 1999 0 JToolBar drag operation must support key for cancelling drag evaluated 4856008 4 4 aep@sparc.spb.su Tue Apr 29 19:06:00 PDT 2003 0 Metal LAF borders should return copies when asked for BorderInsets. accepted 4781723 4 3 leif Wed Nov 20 06:46:00 PST 2002 0 XP L&F: JTabbedPane does not change color on Mouse Over evaluated 4316829 4 5 joutwate Sun Feb 27 00:46:00 PST 2000 1 JDesktopPane.setSelectedFrame should fire PropertyChangeEvent evaluated 4676880 4 3 sky Mon Apr 29 19:20:00 PDT 2002 2 JFormattedtextField setValue(Double) getValue()->Long accepted 4548873 3 4 kve@sparc.spb.su Wed Dec 05 00:04:00 PST 2001 1 Mismatches in JFileChooser behavior in accessing remote machines on Windows committed 4850631 3 3 aa121308 Fri Apr 18 06:38:00 PDT 2003 0 1.3.1_07 REGRESSION: Tooltip on JFileChooser is not displayed correctly committed 4495331 4 3 joutwate Wed Aug 22 18:06:00 PDT 2001 0 Swing and swing demos should not use default version of InputStreamReader() evaluated 4607516 5 3 joutwate Thu Dec 13 18:50:00 PST 2001 6 Japanese strings in JOptionPane are not wrapped. accepted 4844422 4 5 leif Mon Apr 07 14:44:00 PDT 2003 0 XP L&F: JOptionpane uses wrong icons with XP L&F committed 4172937 4 5 leif Fri Sep 11 06:07:00 PDT 1998 11 JToolBar features that would be nice evaluated 4292511 4 3 null Wed Nov 17 16:54:00 PST 1999 8 JTableHeader height determined by first column given HTML text accepted 4488439 4 4 leif Mon Aug 06 02:31:00 PDT 2001 0 There have some space square box when drag the JToolBar accepted 4746835 3 3 zpm@sparc.spb.su Thu Sep 12 20:42:00 PDT 2002 3 REGRESSION: In SDK1.4.1, pasting into JEditorPane creates a new paragraph evaluated 4820053 4 5 shannonh Tue Feb 18 15:09:00 PST 2003 0 getDisabledIcon() only works for ImageIcons evaluated 4260723 4 5 joutwate Sat Aug 07 14:21:00 PDT 1999 1 JTabbedPane does unnecessary layout work evaluated 4741545 4 5 shannonh Wed Sep 04 11:58:00 PDT 2002 0 EOU: BasicTransferable is package protected so not extensible accepted 4795368 3 4 sky Tue Dec 17 19:20:00 PST 2002 0 GTK+ theme keynav for JTree expand/collapse doesn't confirm with GTK+2 standard committed 4853984 5 5 naa@sparc.spb.su Fri Apr 25 01:11:00 PDT 2003 0 1.5b04 REGRESSION: caret doesn't flash in Motif LAF text evaluated 4762705 4 3 leif Mon Oct 14 13:25:00 PDT 2002 1 Tooltip Flickers and Doesn't Show evaluated 4793761 3 2 idk Fri Dec 13 15:15:00 PST 2002 0 Password in JPasswordField can be copied and pasted via middle mouse button evaluated 4623342 4 3 idk Mon Jan 14 13:22:00 PST 2002 2 InlineView causes extra spacing around images in JTable accepted 4821959 3 2 sky Fri Feb 21 04:52:00 PST 2003 0 GTK LAF : Int Frame in Motif not proper committed 4172022 4 5 null Tue Sep 08 13:47:00 PDT 1998 14 Need JTable Option to Set Column Widths Based On Width of Contents evaluated 4137653 4 5 leif Tue May 12 15:40:00 PDT 1998 2 JFileChooser: can't use delete key to delete files and directories evaluated 4144274 4 5 zpm@sparc.spb.su Mon Jun 01 02:12:00 PDT 1998 3 RowHeader/ColumnHeader has not the same height/width as JScrollPa= evaluated 4864718 3 3 joutwate Thu May 15 10:54:00 PDT 2003 1 After minimizing all JInternalFrames the Menu can't be activated by F10 evaluated 4723383 4 3 idk Tue Jul 30 19:43:00 PDT 2002 7 Incomplete RTF support in javax.swing.text.rtf.RTFEditorKit accepted 4656461 4 4 dalem Thu Mar 21 15:35:00 PST 2002 0 Cannot Ctrl-Shift-Click to create disjoint selection interval in list accepted 4389730 4 5 leif Wed Nov 15 17:56:00 PST 2000 0 In JFileChooser, the Save button should disable when no filename is selected accepted 4307147 4 5 null Tue Jan 25 16:12:00 PST 2000 5 Programmatically TAB within a JTable evaluated 4205410 4 5 null Sun Jan 24 16:11:00 PST 1999 3 Need setSelectedRow() method in JTable evaluated 4130823 4 5 shannonh Mon Apr 20 15:50:00 PDT 1998 0 Not painting focus when the radio button has only icon evaluated 4128979 4 5 shannonh Tue Apr 14 19:41:00 PDT 1998 0 JToggleButton with lineBorder doesn't show hilight in Windows L&F evaluated 4811291 4 3 leif Fri Jan 31 10:30:00 PST 2003 0 Windows L&F quality committed 4765357 4 5 leif Fri Oct 18 00:49:00 PDT 2002 0 BasicToolBarUI throws NPE on first call to setFloating(false,..) accepted 4138111 4 5 null Wed May 13 15:14:00 PDT 1998 21 JTable selection model should allow multiple selection of any cells evaluated 4846660 5 5 moa@sparc.spb.su Thu Apr 10 15:19:00 PDT 2003 15 JTabbedPane - Tabs have wider margins under 1.4 incomplete 4816146 4 3 shannonh Mon Feb 10 15:02:00 PST 2003 1 1.4.0 REGRESSION: JTable - Sharing TableColumnModels disables resizing of column accepted 4296946 4 5 sky Sat Dec 04 17:11:00 PST 1999 9 TreeModel insertNodeInto/removeNodeFromParent shouldn't chg tree's expand state evaluated 4464167 4 4 null Wed May 30 10:25:00 PDT 2001 0 JTable.editCellAt() methods does not throw IllegalArgumentException accepted 4235976 4 3 leif Thu May 06 10:49:00 PDT 1999 7 JFileChooser: let files be listed before directories? evaluated 4738541 3 3 shannonh Wed Aug 28 17:31:00 PDT 2002 0 1.4.0 REGRESSION: NullPointerException in WindowsRadioButtonUI.getPreferredSize( committed 4866320 4 4 idk Mon May 19 15:35:00 PDT 2003 0 JTextPane insertIcon doesn't insert if setEditable(false) dispatched 4860985 4 4 leif Thu May 08 23:26:00 PDT 2003 0 Win L&F: tool tip appears even if the windows has no focus evaluated 4782216 4 3 leif Wed Nov 20 16:57:00 PST 2002 1 JToolBar remains floating due to mouse click evaluated 4486444 4 4 null Tue Jul 31 00:34:00 PDT 2001 6 Enter key causes change in JTable row selection accepted 4718657 4 4 shannonh Mon Jul 22 16:54:00 PDT 2002 0 RFE: JOptionPane should provide showPasswordDialog() evaluated 4747079 3 5 shannonh Fri Sep 13 10:16:00 PDT 2002 3 Add sorting ability to JTable committed 4822786 3 4 kve@sparc.spb.su Mon Feb 24 06:33:00 PST 2003 0 ArrayIndexOutOfBounds exception caused by MetalFileChooserUI.setFileSelected() evaluated 4499528 4 3 shannonh Tue Sep 04 14:50:00 PDT 2001 0 JTabbedPane should recognize DnD by default evaluated 4675786 4 3 sky Fri Apr 26 15:21:00 PDT 2002 2 getPreferredSize() in BasicListUI reporting stale size accepted 4765245 4 4 shannonh Fri Oct 18 11:28:00 PDT 2002 0 sizeWidthToFit() isn't sensitive to table header font size accepted 4730055 4 3 shannonh Mon Aug 12 10:40:00 PDT 2002 11 getSelectedRows return non-existing rows in JTable accepted 4489252 4 4 null Tue Aug 07 14:44:00 PDT 2001 1 Box with glue has alignment, repaint problems accepted 4253171 4 5 moa@sparc.spb.su Sat Jul 10 17:19:00 PDT 1999 4 white JTabbedPane on a white JPanel in windows L&F does not paint correctly evaluated 4865948 4 3 bchristi Mon May 19 03:51:00 PDT 2003 0 jdk1.5.0/sparc/demo/jfc/FileChooserDemo doesn't work as expected w/ Motif L&F accepted 4463500 4 3 joutwate Sat May 26 18:57:00 PDT 2001 0 ColorChooser Demo in the SwingSet 2 Demo does not repaint correctly on Dual CPUs accepted 4353669 4 4 null Mon Jul 17 11:51:00 PDT 2000 9 JTable.processKeyBinding does pass KeyEvent to editCellAt handler evaluated 4760072 4 4 leif Tue Oct 08 17:31:00 PDT 2002 0 JFileChooser Icon placement does not match native OS accepted 4498704 4 4 dalem Fri Aug 31 10:13:00 PDT 2001 10 JTable.tableChanged rebuilds columns when header changes. accepted 4386783 4 5 null Tue Nov 07 11:31:00 PST 2000 18 Add setSelectedColumns/Rows(int[]) to JTable committed 4723742 3 3 shannonh Wed Jul 31 11:52:00 PDT 2002 2 1.4.0 REGRESSION: setIntercellSpacing affects the JTable header appearance committed 4687245 4 4 sky Fri May 17 11:51:00 PDT 2002 1 On TAB, JSpinner first turns focus, then calls ChangeListener accepted 4243389 4 4 joutwate Wed Jun 02 14:55:00 PDT 1999 0 Should Swing 1.1.1X JDesktopPane dragMode - faster use outline resizing?#4193162 evaluated 4302764 4 1 joutwate Wed Jan 05 14:15:00 PST 2000 17 focus is not set in JInternalFrame committed 4753366 4 4 joutwate Wed Sep 25 16:05:00 PDT 2002 2 JInternalFrame Navigation: F6 and CTRL+F10 versus open or minimized state evaluated 4527633 4 4 zpm@sparc.spb.su Thu Nov 15 09:33:00 PST 2001 1 No way to get JPopupMenu location accepted 4765347 4 3 zav@sparc.spb.su Fri Oct 18 00:40:00 PDT 2002 0 JPopupMenu invoker slot prevents UI objects being GC'd committed 4502744 4 4 leif Thu Sep 13 14:30:00 PDT 2001 0 ToolTip is completly white on mouse over from initial display accepted 4825411 3 4 leif Thu Feb 27 21:20:00 PST 2003 0 JFileChooser issues in details view committed 4618201 4 5 joutwate Thu Dec 27 04:15:00 PST 2001 0 Metalworks demo under OpenWin windows manager for Sol-IA8 doesn't work properly accepted 4630761 4 3 naa@sparc.spb.su Wed Jan 30 13:58:00 PST 2002 0 HTMLDocument not serializable accepted 4160465 4 5 leif Fri Jul 24 00:02:00 PDT 1998 2 javax.swing.filechooser.FileFilter should implement java.io.FileFilter evaluated 4849868 4 4 idk Wed Apr 16 20:34:00 PDT 2003 0 JTextArea.getSelectionEnd does not work correctly evaluated 4708165 4 4 zpm@sparc.spb.su Wed Jun 26 02:34:00 PDT 2002 0 Swing text editor pane: problems for line distance when resize font size evaluated 4269913 4 3 joutwate Wed Sep 08 15:24:00 PDT 1999 3 Ctrl-Tab sequence should change JInternalFrame focus w/in JDesktopPane evaluated 4765342 3 3 leif Fri Oct 18 00:38:00 PDT 2002 0 NPE in Win32ShellFolder when disconnected from Network evaluated 4492484 4 4 null Wed Aug 15 15:44:00 PDT 2001 5 JTable fails to draw header containing empty string under Windows Look-and-Feel accepted 4515027 4 3 shannonh Tue Oct 16 02:35:00 PDT 2001 1 JOptionPane a11y problems committed 4834223 2 3 aep@sparc.spb.su Tue Mar 18 13:26:00 PST 2003 0 Win L&F: JList highlighting and pick area do not match native committed 4803145 4 3 sdv@sparc.spb.su Tue Jan 14 14:53:00 PST 2003 0 Bullets for HTML