Вы находитесь на странице: 1из 54

Java Swing Tutorial

What is Swings in java ? A part of The JFC Swing Java consists of: Look and feel Accessibility Java 2D Dra and Drop! etc Co"pilin # r$nnin pro ra"s %f yo$ do not e&plicitly add a '(% co"ponent to a container! the '(% co"ponent )ill not be displayed )hen the container appears on the screen* +)in ! )hich is an e&tension library to the AWT! incl$des ne) and i"proved co"ponents that enhance the look and f$nctionality of '(%s* +)in can be $sed to b$ild +tandalone s)in $i Apps as )ell as +ervlets and Applets* %t e"ploys a "odel,vie) desi n architect$re* +)in is "ore portable and "ore fle&ible than AWT* +)in -odel,vie) desi n: The .vie) part. of the -/ desi n is i"ple"ented )ith a co"ponent ob0ect and the (% ob0ect* The ."odel part. of the -/ desi n is i"ple"ented by a "odel ob0ect and a chan e listener ob0ect* +)in is b$ilt on top of AWT and is entirely )ritten in Java! $sin AWT1s li ht)ei ht co"ponent s$pport* %n partic$lar! $nlike AWT! t he architect$re of +)in co"ponents "akes it easy to c$sto"i2e both their appearance and behavior* Co"ponents fro" AWT and +)in can be "i&ed! allo)in yo$ to add +)in s$pport to e&istin AWT-based pro ra"s* For e&a"ple! s)in co"ponents s$ch as J+lider! J3$tton and JCheckbo& co$ld be $sed in the sa"e pro ra" )ith standard AWT labels! te&tfields and scrollbars* 4o$ co$ld s$bclass the e&istin +)in (%! "odel! or chan e listener classes )itho$t havin to reinvent the entire i"ple"entation* +)in also has the ability to replace these ob0ects on-the-fly* 5667 Java i"ple"entation of co"ponents 8l$ able Look # Feel Li ht)ei ht co"ponents Uses MVC Architecture -odel represents the data /ie) as a vis$al representation of the data Controller takes inp$t and translates it to chan es in data Three parts Co"ponent set 9s$bclasses of JCo"ponent: +$pport classes %nterfaces

%n +)in ! classes that represent '(% co"ponents have na"es be innin )ith the letter J* +o"e e&a"ples are J3$tton! JLabel! and J+lider* Alto ether there are "ore than 2;6 ne) classes and <; interfaces in +)in = t)ice as "any as in AWT* Java Swing class hierarchy The class JCo"ponent! descended directly fro" Container! is the root class for "ost of +)in 1s $ser interface co"ponents*

+)in contains co"ponents that yo$1ll $se to b$ild a '(%* % a" listin yo$ so"e of the co""only $sed +)in co"ponents* To learn and $nderstand these s)in pro ra"s! AWT 8ro ra""in kno)led e is not re>$ired*

Java Swing Examples


3elo) is a 0ava s)in code for the traditional ?ello World pro ra"* 3asically! the idea behind this ?ello World pro ra" is to learn ho) to create a 0ava pro ra"! co"pile and r$n it* To create yo$r 0ava so$rce code yo$ can $se any editor9 Te&t pad,@dit pl$s are "y favorites: or yo$ can $se an %D@ like @clipse*
import javax.swing.JFrame; import javax.swing.JLabel; //import statements //Check if window closes automaticall . !therwise add suitable code public class "ello#orldFrame extends JFrame $ public static void main%&tring args'() $

new "ello#orldFrame%); * "ello#orldFrame%) $ JLabel jlb"ello#orld + new JLabel%,"ello #orld,); add%jlb"ello#orld); this.set&i-e%.//0 .//); // pack%); set1isible%true); *

Output

J8anel is +)in 1s version of the AWT class 8anel and $ses the sa"e defa$lt layo$t! Flo)Layo$t* J8anel is descended directly fro" JCo"ponent* J rame is +)in 1s version of Fra"e and is descended directly fro" that class* The co"ponents added to the fra"e are referred to as its contentsA these are "ana ed by the content8ane* To add a co"ponent to a JFra"e! )e "$st $se its content8ane instead* J!nternal rame is confined to a visible area of a container it is placed in* %t can be iconified ! "a&i"i2ed and layered* J"in#ow is +)in 1s version of Windo) and is descended directly fro" that class* Like Windo)! it $ses 3orderLayo$t by defa$lt* JDialo is +)in 1s version of Dialo and is descended directly fro" that class* Like Dialo ! it $ses 3orderLayo$t by defa$lt* Like JFra"e and JWindo)! JDialo contains a root8ane hierarchy incl$din a content8ane! and it allo)s layered and lass panes* All dialo s are "odal! )hich "eans the c$rrent thread is blocked $ntil $ser interaction )ith it has been co"pleted* JDialo class is intended as the basis for creatin c$sto" dialo sA ho)ever! so"e of the "ost co""on dialo s are provided thro$ h static "ethods in the class JBption8ane* J$a%el! descended fro" JCo"ponent! is $sed to create te&t labels* The abstract class Abstract3$tton e&tends class JCo"ponent and provides a fo$ndation for a fa"ily of b$tton classes! incl$din J&utton* JText iel# allo)s editin of a sin le line of te&t* Ce) feat$res incl$de the ability to 0$stify the te&t left! ri ht! or center! and to set the te&t1s font* J'asswor# iel# 9a direct s$bclass of JTe&tField: yo$ can s$ppress the display of inp$t* @ach character entered can be replaced by an echo character* This allo)s confidential inp$t for pass)ords! for e&a"ple* 3y defa$lt! the echo character is the asterisk! D* JTextArea allo)s editin of "$ltiple lines of te&t* JTe&tArea can be $sed in con0$nction )ith class J+croll8ane to achieve scrollin * The $nderlyin J+croll8ane can be forced to al)ays or never

have either the vertical or hori2ontal scrollbarA J3$tton is a co"ponent the $ser clicks to tri er a specific action* J(a#io&utton is si"ilar to JCheckbo&! e&cept for the defa$lt icon for each class* A set of radio b$ttons can be associated as a ro$p in )hich only one b$tton at a ti"e can be selected* JChec)&ox is not a "e"ber of a checkbo& ro$p* A checkbo& can be selected and deselected! and it also displays its c$rrent state* JCom%o&ox is like a drop do)n bo&* 4o$ can click a drop-do)n arro) and select an option fro" a list* For e&a"ple! )hen the co"ponent has foc$s! pressin a key that corresponds to the first character in so"e entry1s na"e selects that entry* A vertical scrollbar is $sed for lon er lists* J$ist provides a scrollable set of ite"s fro" )hich one or "ore "ay be selected* JList can be pop$lated fro" an Array or /ector* JList does not s$pport scrollin directly! instead! the list "$st be associated )ith a scrollpane* The vie) port $sed by the scroll pane can also have a $ser-defined border* JList actions are handled $sin List+electionListener* JTa%%e#'ane contains a tab that can have a tool tip and a "ne"onic! and it can display both te&t and an i"a e* JTool%ar contains a n$"ber of co"ponents )hose type is $s$ally so"e kind of b$tton )hich can also incl$de separators to ro$p related co"ponents )ithin the toolbar* low$ayout )hen $sed arran es s)in co"ponents fro" left to ri ht $ntil there1s no "ore space available* Then it be ins a ne) ro) belo) it and "oves fro" left to ri ht a ain* @ach co"ponent in a Flo)Layo$t ets as "$ch space as it needs and no "ore* &or#er$ayout places s)in co"ponents in the Corth! +o$th! @ast! West and center of a container* 4o$ can add hori2ontal and vertical aps bet)een the areas* *ri#$ayout is a layo$t "ana er that lays o$t a container1s co"ponents in a rectan $lar rid* The container is divided into e>$al-si2ed rectan les! and one co"ponent is placed in each rectan le* *ri#&ag$ayout is a layo$t "ana er that lays o$t a container1s co"ponents in a rid of cells )ith each co"ponent occ$pyin one or "ore cells! called its display area* The display area ali ns co"ponents vertically and hori2ontally! )itho$t re>$irin that the co"ponents be of the sa"e si2e* JMenu%ar can contain several J-en$1s* @ach of the J-en$1s can contain a series of J-en$%te" 1s that yo$ can select* +)in provides s$pport for p$ll-do)n and pop$p "en$s* Scrolla%le J'opupMenu is a scrollable pop$p "en$ that can be $sed )henever )e have so "any ite"s in a pop$p "en$ that e&ceeds the screen visible hei ht*

+, Java J rame class example


J rame The co"ponents added to the fra"e are referred to as its contentsA these are "ana ed by the content8ane* To add a co"ponent to a JFra"e! )e "$st $se its content8ane instead*JFra"e is a Windo) )ith border! title and b$ttons* When JFra"e is set visible! an event dispatchin thread is started* JFra"e ob0ects store several ob0ects incl$din a Container ob0ect kno)n as the content pane* To add a co"ponent to a JFra"e! add it to the content pane* J rame eatures %tEs a )indo) )ith title! border! 9optional: "en$ bar and $ser-specified co"ponents* %t can be "oved! resi2ed! iconified* %t is not a s$bclass of JCo"ponent* Dele ates responsibility of "ana in $ser-specified co"ponents to a content pane! an instance of J8anel* Centering J rame-s 3y defa$lt! a Jfra"e is displayed in the $pper-left corner of the screen* To display a fra"e at a specified location! yo$ can $se the setLocation9&! y: "ethod in the JFra"e class* This "ethod places the $pper-left corner of a fra"e at location 9&! y:* The +)in A8% keeps i"provin )ith abstractions s$ch as the setDefa$ltCloseBperation "ethod for the JFra"e Crating a J rame "in#ow +tep 5: Constr$ct an ob0ect of the JFra"e class* +tep 2: +et the si2e of the Jfra"e* +tep F: +et the title of the Jfra"e to appear in the title bar 9title bar )ill be blank if no title is set:* +tep G: +et the defa$lt close operation* When the $ser clicks the close b$tton! the pro ra" stops r$nnin * +tep ;: -ake the Jfra"e visible* ?o) to position JFra"e on +creen? fra"e*setLocationHelativeTo9 n$ll :A

J rame Source Co#e


import java.awt.2;

import java.awt.event.2; import javax.swing.2; public class JFrame3emo $ public static void main%&tring s'() $ JFrame frame + new JFrame%,JFrame &ource 3emo,); // 4dd a window listner for close button frame.add#indowListener%new #indow4dapter%) $ public void windowClosing%#indow5vent e) $ & stem.exit%/); *

*); // 6his is an empt content area in the frame JLabel jlbempt + new JLabel%,,); jlbempt .set7referred&i-e%new 3imension%.890 .//)); frame.getContent7ane%).add%jlbempt 0 :orderLa out.C5;65<); frame.pack%); frame.set1isible%true); *

Output

Java JFrame Hierarchy


0ava&*s)in Class JFra"e 0ava*lan *Bb0ect 0ava*a)t*Co"ponent 0ava*a)t*Container 0ava*a)t*Windo) 0ava*a)t*Fra"e 0ava&*s)in *JFra"e All %"ple"ented %nterfaces: Accessible! %"a eBbserver! -en$Container! Hoot8aneContainer! +eriali2able! Windo)Constants

J rame Constructor
JFra"e9:: Constr$cts a ne) fra"e that is initially invisible*

JFra"e9'raphicsConfi $ration c: Creates a Fra"e in the specified 'raphicsConfi $ration of a screen device and a blank title* JFra"e9+trin title:: Creates a ne)! initially invisible Fra"e )ith the specified title* JFra"e9+trin title! 'raphicsConfi $ration c: Creates a JFra"e )ith the specified title and the specified 'raphicsConfi $ration of a screen device*

., Java J!nternal rame class example


J!nternal rame Java +)in T$torial @&plainin the J%nternalFra"e class* A J%nternalFra"e is confined to a visible area of a container it is placed in* J%nternalFra"e a top level s)in co"ponent that has a contentpane* I I I I %t can be iconified -- in this case the icon re"ains in the "ain application container* %t can be "a&i"i2ed -- Fra"e cons$"es the "ain application %t can be closed $sin standard pop$p )indo) controls %t can be layered

J!nternal rame Source Co#e


import import import import import import import import javax.swing.J=nternalFrame; javax.swing.J3esktop7ane; javax.swing.J>enu; javax.swing.J>enu=tem; javax.swing.J>enu:ar; javax.swing.JFrame; java.awt.event.2; java.awt.2;

public class J=nternalFrame3emo extends JFrame $ J3esktop7ane jdp3esktop; static int openFrameCount + /; public J=nternalFrame3emo%) $ super%,J=nternalFrame ?sage 3emo,); // >ake the main window positioned as 9/ pixels from each edge of the // screen. int inset + 9/; 3imension screen&i-e + 6oolkit.get3efault6oolkit%).get&creen&i-e%); set:ounds%inset0 inset0 screen&i-e.width @ inset 2 A0 screen&i-e.height @ inset 2 A); // 4dd a #indow 5xit Listener add#indowListener%new #indow4dapter%) $

*); // Create and &et up the B?=. jdp3esktop + new J3esktop7ane%); // 4 speciali-ed la ered pane to be used with J=nternalFrames createFrame%); // Create first window setContent7ane%jdp3esktop); setJ>enu:ar%create>enu:ar%)); // >ake dragging faster b setting drag mode to !utline jdp3esktop.putClient7ropert %,J3esktop7ane.drag>ode,0 ,outline,); * protected J>enu:ar create>enu:ar%) $ J>enu:ar menu:ar + new J>enu:ar%); J>enu menu + new J>enu%,Frame,); menu.set>nemonic%Ce 5vent.1CD;); J>enu=tem menu=tem + new J>enu=tem%,;ew =Frame,); menu=tem.set>nemonic%Ce 5vent.1CD;); menu=tem.add4ctionListener%new 4ctionListener%) $ public void action7erformed%4ction5vent e) $ createFrame%); * *); menu.add%menu=tem); menu:ar.add%menu); return menu:ar; * protected void createFrame%) $ > =nternalFrame frame + new > =nternalFrame%); frame.set1isible%true); // 5ver J=nternalFrame must be added to content pane using J3esktop7ane jdp3esktop.add%frame); tr $ frame.set&elected%true); * catch %java.beans.7ropert 1eto5xception e) $ * * public static void main%&tring'( args) $ J=nternalFrame3emo frame + new J=nternalFrame3emo%); frame.set1isible%true); * class > =nternalFrame extends J=nternalFrame $ static final int x7osition + E/0 7osition + E/; public > =nternalFrame%) $ super%,=Frame F, G %GGopenFrameCount)0 true0 // resi-able true0 // closable true0 // maximi-able true);// iconifiable set&i-e%E//0 E//); // &et the windowHs location. setLocation%x7osition 2 openFrameCount0 7osition 2 openFrameCount); *

public void windowClosing%#indow5vent e) $ & stem.exit%/); *

Output

Java JInternalFrame Hierarchy


0ava&*s)in Class J%nternalFra"e 0ava*lan *Bb0ect J K--0ava*a)t*Co"ponent J K--0ava*a)t*Container J K--0ava&*s)in *JCo"ponent J K--0ava&*s)in *J%nternalFra"e All !mplemente# !nter/aces0 Accessible! %"a eBbserver! -en$Container! Hoot8aneContainer! +eriali2able! Windo)Constants

J!nternal rame Constructor


J%nternalFra"e9: Creates a non-resi2able! non-closable! non-"a&i"i2able! non-iconifiable J%nternalFra"e )ith no title* J%nternalFra"e9+trin title: Creates a non-resi2able! non-closable! non-"a&i"i2able! non-iconifiable J%nternalFra"e )ith the specified title* J%nternalFra"e9+trin title! boolean resi2able: Creates a non-closable! non-"a&i"i2able! non-iconifiable J%nternalFra"e )ith the specified title and resi2ability* J%nternalFra"e9+trin title! boolean resi2able! boolean closable: Creates a non-"a&i"i2able! non-iconifiable J%nternalFra"e )ith the specified title! resi2ability! and closability* J%nternalFra"e9+trin title! boolean resi2able! boolean closable! boolean "a&i"i2able: Creates a non-iconifiable J%nternalFra"e )ith the specified title! resi2ability! closability! and "a&i"i2ability* J%nternalFra"e9+trin title! boolean resi2able! boolean closable! boolean "a&i"i2able! boolean iconifiable: Creates a J%nternalFra"e )ith the specified title! resi2ability! closability! "a&i"i2ability

1, Java J"in#ow class example


J"in#ow
Java +)in T$torial @&plainin the JWindo) Co"ponent* J"in#ow is +)in 1s version of Windo) and is descended directly fro" that class* Like Windo)! it $ses 3orderLayo$t by defa$lt* Al"ost all +)in co"ponents are li ht)ei ht e&cept JApplet! JFra"e! JDialo ! and JWindo)* J"in#ow Source Co#e

public class J#indow3emo extends J#indow $ private int I + /; private int J + /; public J#indow3emo%) $ set:ounds%K/0 K/0 .//0 .//); add#indowListener%new #indow4dapter%) $ public void windowClosing%#indow5vent e) $ & stem.exit%/); // 4n 5xit Listener *

*); // 7rint %I0J) coordinates on >ouse Click add>ouseListener%new >ouse4dapter%) $

*); add>ouse>otionListener%new >ouse>otion4dapter%) $

public void mouse7ressed%>ouse5vent e) $ I + e.getI%); J + e.getJ%); & stem.out.println%,6he %I0J) coordinate of window is %, G I G ,0, G J G ,),); *

public void mouse3ragged%>ouse5vent e) $ setLocation%getLocation%).x G %e.getI%) @ I)0 getLocation%). G %e.getJ%) @ J)); * *); set1isible%true); * public static void main%&tring'( args) $ new J#indow3emo%); *

Output

Java JWindow Hierarchy


0ava&*s)in Class JWindo) 0ava*lan *Bb0ect 0ava*a)t*Co"ponent 0ava*a)t*Container 0ava*a)t*Windo)

All !mplemente# !nter/aces0 Accessible! %"a eBbserver! -en$Container! +eriali2able 2irect 3nown Su%classes0 3asicTool3ar(%*Dra Windo)! Dialo ! Fra"e! JWindo)

J"in#ow Constructor
Windo)9Fra"e o)ner: Constr$cts a ne) invisible )indo) )ith the specified Fra"e as its o)ner* Windo)9Windo) o)ner: Constr$cts a ne) invisible )indo) )ith the specified Windo) as its o)ner* Windo)9Windo) o)ner! 'raphicsConfi $ration c: Constr$cts a ne) invisible )indo) )ith the specified )indo) as its o)ner and a 'raphicsConfi $ration of a screen device*

4, Java J$a%el class example


J$a%els
Java +)in T$torial @&plainin the JLabel Co"ponent* JLabel! descended fro" JCo"ponent! is $sed to create te&t labels* A JLabel ob0ect provides te&t instr$ctions or infor"ation on a '(% = display a sin le line of read-only te&t! an i"a e or both te&t and i"a e* We $se a +)in JLabel )hen )e need a $ser interface co"ponent that displays a "essa e or an i"a e* JLLabels I 8rovide te&t instr$ctions on a '(% I lHead-only te&t I l8ro ra"s rarely chan e a label1s contents I lClass J$a%el 9s$bclass of JComponent: J$a%el Source Co#e
import =mport import import import import import java.awt.BridLa out; java.awt.event.#indow4dapter; java.awt.event.#indow5vent; javax.swing.JLabel; javax.swing.J7anel; javax.swing.JFrame; javax.swing.=mage=con;

public class Jlabel3emo extends J7anel $ JLabel jlbLabel.0 jlbLabelA0 jlbLabelE; public Jlabel3emo%) $ =mage=con icon + new =mage=con%,java@swing@tutorial.J7B,0 ,> #ebsite,); // Creating an =con setLa out%new BridLa out%E0 .)); // E rows0 . column 7anel having Brid La out jlbLabel. + new JLabel%,=mage with 6ext,0 icon0 JLabel.C5;65<); // #e can position of the text0 relative to the iconL jlbLabel..set1ertical6ext7osition%JLabel.:!66!>); jlbLabel..set"ori-ontal6ext7osition%JLabel.C5;65<); jlbLabelA + new JLabel%,6ext !nl Label,); jlbLabelE + new JLabel%icon); // Label of =con !nl // 4dd labels to the 7anel add%jlbLabel.); add%jlbLabelA); add%jlbLabelE); * public static void main%&tring'( args) $ JFrame frame + new JFrame%,jLabel ?sage 3emo,); frame.add#indowListener%new #indow4dapter%) $ // &hows code to 4dd #indow Listener public void windowClosing%#indow5vent e) $ & stem.exit%/); *

*); frame.setContent7ane%new Jlabel3emo%)); frame.pack%); frame.set1isible%true);

Output

Java JLabel Hierarchy


0ava&*s)in Class J$a%el

0ava*lan *Bb0ect 0ava*a)t*Co"ponent 0ava*a)t*Container 0ava&*s)in *JCo"ponent 0ava&*s)in *JLabel All !mplemente# !nter/aces0 Accessible! %"a eBbserver! -en$Container! +eriali2able! +)in Constants 2irect 3nown Su%classes0 3asicCo"bo3o&Henderer! Defa$ltListCellHenderer! Defa$ltTableCellHenderer! Defa$ltTreeCellHenderer

J$a%el Constructor
J$a%el560 Creates a JLabel instance )ith no i"a e and )ith an e"pty strin for the title* J$a%el5!con image60 Creates a JLabel instance )ith the specified i"a e* J$a%el5!con image7 int hori8ontalAlignment6 Creates a JLabel instance )ith the specified i"a e and hori2ontal ali n"ent* J$a%el5String text60 Creates a JLabel instance )ith the specified te&t* J$a%el5String text7 !con icon7 int hori8ontalAlignment6 Creates a JLabel instance )ith the specified te&t! i"a e! and hori2ontal ali n"ent* J$a%el5String text7 int hori8ontalAlignment6 Creates a JLabel instance )ith the specified te&t and hori2ontal ali n"ent*

9, Java J&utton class example


J&utton
Java +)in T$torial @&plainin the J3$tton Co"ponent* The abstract class Abstract3$tton e&tends class JCo"ponent and provides a fo$ndation for a fa"ily of b$tton classes! incl$din J3$tton* A b$tton is a co"ponent the $ser clicks to tri er a specific action* There are several types of b$ttons in Java! all are s$bclasses of Abstract3$tton* I I I I co""and b$ttons: is created )ith class J3$tton* %t enerates Action@vent* to le b$ttons: have on,off or tr$e,false val$es* check bo&es: a ro$p of b$ttons* %t enerates %te"@vent* radio b$ttons: a ro$p of b$ttons in )hich only one can be selected* %t enerates %te"@vent*

J&utton Source Co#e


import java.awt.event.4ction5vent; import java.awt.event.4ctionListener; import java.awt.event.Ce 5vent; import java.net.?<L; import javax.swing.4bstract:utton; import javax.swing.=mage=con; import javax.swing.J:utton; import javax.swing.JFrame; import javax.swing.J7anel; public class J:utton3emo extends J7anel implements 4ctionListener $ protected static J:utton jbnLeft0 jbn>iddle0 jbn<ight; public J:utton3emo%) $ // Create =cons that can be used with the j:uttons =mage=con left:utton=con + create=mage=con%,rightarrow.J7B,); =mage=con middle:utton=con + create=mage=con%,java@swing@tutorial.J7B,); =mage=con right:utton=con + create=mage=con%,leftarrow.J7B,); jbnLeft + new J:utton%,3isable centre button,0 left:utton=con); jbnLeft.set1ertical6ext7osition%4bstract:utton.C5;65<); jbnLeft.set"ori-ontal6ext7osition%4bstract:utton.L543=;B); jbnLeft.set>nemonic%Ce 5vent.1CD3); // 4lt@3 clicks the button jbnLeft.set4ctionCommand%,disable,); jbnLeft.set6ool6ip6ext%,disable the Centre button.,); // 4dding 6ool // tips jbn>iddle + new J:utton%,Centre button,0 middle:utton=con); jbn>iddle.set1ertical6ext7osition%4bstract:utton.:!66!>); jbn>iddle.set"ori-ontal6ext7osition%4bstract:utton.C5;65<); jbn>iddle.set>nemonic%Ce 5vent.1CD>); // 4lt@> clicks the button jbn>iddle.set6ool6ip6ext%,Centre button,); jbn<ight + new J:utton%,5nable centre button,0 right:utton=con); // ?se the default text position of C5;65<0 6<4=L=;B %<=B"6). jbn<ight.set>nemonic%Ce 5vent.1CD5); // 4lt@5 clicks the button jbn<ight.set4ctionCommand%,enable,); jbn<ight.set5nabled%false); // 3isable the :utton at creation time // Listen for actions on Left and <oght :uttons jbnLeft.add4ctionListener%this); jbn<ight.add4ctionListener%this); jbn<ight.set6ool6ip6ext%,5nable the Centre button.,); // 4dd Components to the frame0 using the default FlowLa out. add%jbnLeft); add%jbn>iddle); add%jbn<ight); * public void action7erformed%4ction5vent e) $ if %,disable,.eMuals%e.get4ctionCommand%))) $ jbn>iddle.set5nabled%false); jbnLeft.set5nabled%false); jbn<ight.set5nabled%true); * else $

* * // <eturns an =mage=con0 or null if the path was invalid. protected static =mage=con create=mage=con%&tring path) $ ?<L img?<L + J:utton3emo.class.get<esource%path); if %img?<L N+ null) $ return new =mage=con%img?<L); * else $ & stem.err.println%,CouldnHt find image in s stemL , G path); return null; * * // Create the B?= and show it. private static void createB?=%) $ JFrame.set3efaultLook4ndFeel3ecorated%true); // Create and set up the frame. JFrame frame + new JFrame%,j:utton usage demo,); frame.set3efaultClose!peration%JFrame.5I=6D!;DCL!&5); // Create and set up the content pane. J:utton3emo buttonContent7ane + new J:utton3emo%); buttonContent7ane.set!paMue%true); // content panes must be opaMue frame.get<oot7ane%).set3efault:utton%jbnLeft); frame.setContent7ane%buttonContent7ane); // 3ispla the window. frame.pack%); frame.set1isible%true); * public static void main%&tring'( args) $ javax.swing.&wing?tilities.invokeLater%new <unnable%) $ public void run%) $ createB?=%); * * *);

jbn>iddle.set5nabled%true); jbnLeft.set5nabled%true); jbn<ight.set5nabled%false);

Output

Another Example0 J&utton Source Co#e

import java.awt.2; import java.awt.event.2; import javax.swing.2; public class J:utton3emoA $ JFrame jtf>ainFrame; J:utton jbn:utton.0 jbn:uttonA; J6extField jtf=nput; J7anel jpl7anel; public J:utton3emoA%) $ jtf>ainFrame + new JFrame%,#hich :utton 3emo,); jtf>ainFrame.set&i-e%9/0 9/); jbn:utton. + new J:utton%,:utton .,); jbn:uttonA + new J:utton%,:utton A,); jtf=nput + new J6extField%A/); jpl7anel + new J7anel%); jbn:utton..set>nemonic%Ce 5vent.1CD=); //&et &hortCut Ce s jbn:utton..add4ctionListener%new 4ctionListener%) $ public void action7erformed%4ction5vent e) $ jtf=nput.set6ext%,:utton .N,); *

*); jbn:uttonA.set>nemonic%Ce 5vent.1CD=); jbn:uttonA.add4ctionListener%new 4ctionListener%) $

public void action7erformed%4ction5vent e) $ jtf=nput.set6ext%,:utton AN,); * *); jpl7anel.setLa out%new FlowLa out%)); jpl7anel.add%jtf=nput); jpl7anel.add%jbn:utton.); jpl7anel.add%jbn:uttonA); jtf>ainFrame.getContent7ane%).add%jpl7anel0 :orderLa out.C5;65<); jtf>ainFrame.set3efaultClose!peration%JFrame.5I=6D!;DCL!&5); jtf>ainFrame.pack%); jtf>ainFrame.set1isible%true);

* public static void main%&tring'( args) $ // &et the look and feel to Java &wing Look tr $ ?=>anager.setLook4ndFeel%?=>anager .getCross7latformLook4ndFeelClass;ame%)); * catch %5xception e) $ * J:utton3emoA application + new J:utton3emoA%); *

Output

Java JButton Hierarchy


0ava&*s)in Class J&utton 0ava*lan *Bb0ect 0ava*a)t*Co"ponent 0ava*a)t*Container 0ava&*s)in *JCo"ponent 0ava&*s)in *Abstract3$tton 0ava&*s)in *J3$tton All !mplemente# !nter/aces0 Accessible! %"a eBbserver! %te"+electable! -en$Container! +eriali2able! +)in Constants 2irect 3nown Su%classes0 3asicArro)3$tton! -etalCo"bo3o&3$tton

J&utton Constructor
J3$tton9:: Creates a b$tton )ith no set te&t or icon* J3$tton9Action a:: Creates a b$tton )here properties are taken fro" the Action s$pplied* J3$tton9%con icon:: Creates a b$tton )ith an icon* J3$tton9+trin te&t:: Creates a b$tton )ith te&t* J3$tton9+trin te&t! %con icon:: Creates a b$tton )ith initial te&t and an icon*

:, Java JText iel# class example


JText iel#
Java +)in T$torial @&plainin the JTe&tField Co"ponent* JTe&tField allo)s editin ,displayin of a sin le line of te&t* Ce) feat$res incl$de the ability to 0$stify the te&t left! ri ht! or center! and to set the te&t1s font* When the $ser types data into the" and presses the @nter key! an action event occ$rs* %f the pro ra" re isters an event listener! the listener processes the event and can $se the data in the te&t field at the ti"e of the event in the pro ra"* JTe&tField is an inp$t area )here the $ser can type in characters* %f yo$ )ant to let the $ser enter "$ltiple lines of te&t! yo$ cannot $se Jte&tfield1s $nless yo$ create several of the"* The sol$tion is to $se JTextArea! )hich enables the $ser to enter "$ltiple lines of te&t*

JText iel# Source Co#e


// 4 program to demonstrate the use of J6extFieldsHs //=mport &tatements import javax.swing.2; import java.awt.2; import java.awt.event.2; public class J6extField3emo extends JFrame $ //Class 3eclarations J6extField jtf6ext.0 jtf?neditable6ext; &tring disp + ,,; 6ext"andler handler + null; //Constructor public J6extField3emo%) $ super%,6extField 6est 3emo,); Container container + getContent7ane%); container.setLa out%new FlowLa out%)); jtf6ext. + new J6extField%./); jtf?neditable6ext + new J6extField%,?neditable text field,0 A/); jtf?neditable6ext.set5ditable%false); container.add%jtf6ext.); container.add%jtf?neditable6ext); handler + new 6ext"andler%); jtf6ext..add4ctionListener%handler); jtf?neditable6ext.add4ctionListener%handler); set&i-e%EA90 .//); set1isible%true); * //=nner Class 6ext"andler private class 6ext"andler implements 4ctionListener $ public void action7erformed%4ction5vent e) $ if %e.get&ource%) ++ jtf6ext.) $ disp + ,text. L , G e.get4ctionCommand%); * else if %e.get&ource%) ++ jtf?neditable6ext) $ disp + ,textE L , G e.get4ctionCommand%); * J!ption7ane.show>essage3ialog%null0 disp); *

* //>ain 7rogram that starts 5xecution public static void main%&tring args'() $ J6extField3emo test + new J6extField3emo%); test.set3efaultClose!peration%JFrame.5I=6D!;DCL!&5); * *// 5nd of class 6extField6est

Output

Another Example0 JText iel# Source Co#e


public class J6extField3emoA extends JFrame implements 4ctionListener $ J6extField jtf=nput; J6ext4rea jt4rea!utput; &tring newline + ,On,; public J6extField3emoA%) $ createBui%); * public void createBui%) $ jtf=nput + new J6extField%A/); jtf=nput.add4ctionListener%this); jt4rea!utput + new J6ext4rea%90 A/); jt4rea!utput.set5ditable%false); J&croll7ane scroll7ane + new J&croll7ane%jt4rea!utput0 J&croll7ane.15<6=C4LD&C<!LL:4<D4L#4J&0 J&croll7ane."!<=P!;64LD&C<!LL:4<D4L#4J&); Brid:agLa out grid:ag + new Brid:agLa out%); Container content7ane + getContent7ane%); content7ane.setLa out%grid:ag); Brid:agConstraints gridCons. + new Brid:agConstraints%); gridCons..gridwidth + Brid:agConstraints.<5>4=;35<; gridCons..fill + Brid:agConstraints."!<=P!;64L; content7ane.add%jtf=nput0 gridCons.); Brid:agConstraints gridConsA + new Brid:agConstraints%); gridConsA.weightx + ../; gridConsA.weight + ../; content7ane.add%scroll7ane0 gridConsA); * public void action7erformed%4ction5vent evt) $ &tring text + jtf=nput.get6ext%); jt4rea!utput.append%text G newline); jtf=nput.select4ll%); * public static void main%&tring'( args) $ J6extField3emoA jtf6f3emo + new J6extField3emoA%); jtf6f3emo.pack%); jtf6f3emo.add#indowListener%new #indow4dapter%) $ public void windowClosing%#indow5vent e) $ & stem.exit%/); * *); jtf6f3emo.set1isible%true); *

Output

Java JTextField Hierarchy


0ava&*s)in 0ava*lan *Bb0ect 0ava*a)t*Co"ponent 0ava*a)t*Container 0ava&*s)in *JCo"ponent 0ava&*s)in *te&t*JTe&tCo"ponent 0ava&*s)in *JTe&tField All !mplemente# !nter/aces0 Accessible! %"a eBbserver! -en$Container! +crollable! +eriali2able! +)in Constants 2irect 3nown Su%classes0 Defa$ltTreeCell@ditor*Defa$ltTe&tField! JFor"attedTe&tField! J8ass)ordField

JText iel# Constructor


JTe&tField9:: Constr$cts a ne) Te&tField* JTe&tField9Doc$"ent doc! +trin te&t! int col$"ns: Constr$cts a ne) JTe&tField that $ses the iven te&t stora e "odel and the iven n$"ber of col$"ns* JTe&tField9int col$"ns:: Constr$cts a ne) e"pty Te&tField )ith the specified n $"ber of col$"ns* JTe&tField9+trin te&t:: Constr$cts a ne) Te&tField initiali2ed )ith the specified te&t* JTe&tField9+trin te&t! int col$"ns:: Constr$cts a ne) Te&tField initiali2ed )ith the specified te&t and col$"ns*

;, Java J'asswor# iel# class example

J'asswor# iel# Java +)in T$torial @&plainin the J8ass)ordField Co"ponent* J8ass)ordField 9a direct s$bclass of JTe&tField: yo$ can s$ppress the display of inp$t* @ach character entered can be replaced by an echo character* This allo)s confidential inp$t for pass)ords! for e&a"ple* 3y defa$lt! the echo character is the asterisk! D* When the $ser types data into the" and presses the @nter key! an action event occ$rs* %f the pro ra" re isters an event listener! the listener processes the event and can $se the data in the te&t field at the ti"e of the event in the pro ra"* %f yo$ need to provide an editable te&t field that doesnEt sho) the characters the $ser types M $se the J8ass)ordField class*

J'asswor# iel# Source Co#e

public class J7asswordField3emo $ public static void main%&tring'( argv) $ final JFrame frame + new JFrame%,J7assword ?sage 3emo,); JLabel jlb7assword + new JLabel%,5nter the passwordL ,); J7asswordField jpw;ame + new J7asswordField%./); jpw;ame.set5choChar%H2H); jpw;ame.add4ctionListener%new 4ctionListener%) $ public void action7erformed%4ction5vent e) $ J7asswordField input + %J7asswordField) e.get&ource%); char'( password + input.get7assword%); if %is7asswordCorrect%password)) $ J!ption7ane.show>essage3ialog%frame0 ,Correct password.,); * else $ J!ption7ane.show>essage3ialog%frame0 ,&orr . 6r again.,0 ,5rror >essage,0 J!ption7ane.5<<!<D>5&&4B5); * *

*); J7anel jplContent7ane + new J7anel%new :orderLa out%)); jplContent7ane.set:order%:orderFactor .create5mpt :order%A/0 A/0 A/0 A/)); jplContent7ane.add%jlb7assword0 :orderLa out.#5&6); jplContent7ane.add%jpw;ame0 :orderLa out.C5;65<); frame.setContent7ane%jplContent7ane); frame.add#indowListener%new #indow4dapter%) $ public void windowClosing%#indow5vent e) $ & stem.exit%/); *

*); frame.pack%); frame.set1isible%true);

* private static boolean is7asswordCorrect%char'( input7assword) $ char'( actual7assword + $ HhH0 HeH0 HmH0 HaH0 HnH0 HtH0 HhH *;

if %input7assword.length N+ actual7assword.length) return false; // <eturn false if lengths are uneMual for %int i + /; i Q input7assword.length; iGG) if %input7assword'i( N+ actual7assword'i() return false; return true; *

Output

Java JPasswordField Hierarchy


0ava&*s)in Class J'asswor# iel# 0ava*lan *Bb0ect 0ava*a)t*Co"ponent 0ava*a)t*Container 0ava&*s)in *JCo"ponent 0ava&*s)in *te&t*JTe&tCo"ponent 0ava&*s)in *JTe&tField 0ava&*s)in *J8ass)ordField All !mplemente# !nter/aces0 %"a eBbserver! -en$Container! +eriali2able! Accessible! +crollable! +)in Constants

J'asswor# iel# Constructor


J8ass)ordField9: Constr$cts a ne) J8ass)ordField! )ith a defa$lt doc$"ent! n$ll startin te&t strin ! and 6 col$"n )idth* J8ass)ordField9Doc$"ent doc! +trin t&t! int col$"ns: Constr$cts a ne) J8ass)ordField that $ses the iven te&t stora e "odel and the iven n$"ber of col$"ns* J8ass)ordField9int col$"ns:: Constr$cts a ne) e"pty J8ass)ordField )ith the specified n$"ber of cols* J8ass)ordField9+trin te&t: Constr$cts a ne) J8ass)ordField initiali2ed )ith the specified te&t* J8ass)ordField9+trin te&t! int col$"ns: Constr$cts a ne) J8ass)ordField initiali2ed )ith the specified te&t and col$"ns*

<, Java JTextArea class example

JTextArea
Java +)in T$torial @&plainin the JTe&tArea Co"ponent* JTe&tArea allo)s editin of "$ltiple lines of te&t* JTe&tArea can be $sed in con0$nction )ith class J+croll8ane to achieve scrollin * The $nderlyin J+croll8ane can be forced to al)ays or never have either the vertical or hori2ontal scrollbar* JTextArea Source Co#e
import java.awt.2; import java.awt.event.2; import javax.swing.2; public class J6ext4rea3emo extends JFrame implements 4ctionListener $ J6extField jtf=nput; J6ext4rea jt4rea!utput; &tring newline + ,On,; public J6ext4rea3emo%) $ createBui%); * public void createBui%) $ jtf=nput + new J6extField%A/); jtf=nput.add4ctionListener%this); jt4rea!utput + new J6ext4rea%90 A/); jt4rea!utput.setCaret7osition%jt4rea!utput.get3ocument%) .getLength%)); jt4rea!utput.set5ditable%false); J&croll7ane scroll7ane + new J&croll7ane%jt4rea!utput0 J&croll7ane.15<6=C4LD&C<!LL:4<D4L#4J&0 J&croll7ane."!<=P!;64LD&C<!LL:4<D4L#4J&); Brid:agLa out grid:ag + new Brid:agLa out%); Container content7ane + getContent7ane%); content7ane.setLa out%grid:ag); Brid:agConstraints gridCons. + new Brid:agConstraints%); gridCons..gridwidth + Brid:agConstraints.<5>4=;35<; gridCons..fill + Brid:agConstraints."!<=P!;64L; content7ane.add%jtf=nput0 gridCons.); Brid:agConstraints gridConsA + new Brid:agConstraints%); gridConsA.weightx + ../; gridConsA.weight + ../; content7ane.add%scroll7ane0 gridConsA); * public void action7erformed%4ction5vent evt) $ &tring text + jtf=nput.get6ext%); jt4rea!utput.append%text G newline); jtf=nput.select4ll%); * public static void main%&tring'( args) $ J6ext4rea3emo jtf6f3emo + new J6ext4rea3emo%); jtf6f3emo.pack%); jtf6f3emo.add#indowListener%new #indow4dapter%) $ public void windowClosing%#indow5vent e) $ & stem.exit%/);

* *); jtf6f3emo.set1isible%true);

Output

Java JTextArea Hierarchy


0ava&*s)in Class JTextArea 0ava*lan *Bb0ect 0ava*a)t*Co"ponent 0ava*a)t*Container 0ava&*s)in *JCo"ponent 0ava&*s)in *te&t*JTe&tCo"ponent 0ava&*s)in *JTe&tField All !mplemente# !nter/aces0 Accessible! %"a eBbserver! -en$Container! +crollable! +eriali2able! +)in Constants 2irect 3nown Su%classes0 Defa$ltTreeCell@ditor*Defa$ltTe&tField! JFor"attedTe&tField! J8ass)ordField

JTextArea Constructor
JTe&tArea9:: Constr$cts a ne) Te&tArea* JTe&tArea9Doc$"ent doc:: Constr$cts a ne) JTe&tArea )ith the iven doc$"ent "odel! and defa$lts for all of the other ar $"ents 9n$ll! 6! 6:* JTe&tArea9Doc$"ent doc! +trin te&t! int ro)s! int col$"ns: Constr$cts a ne) JTe&tArea )ith the specified n$"ber of ro)s and col$"ns! and the iven "odel* JTextArea5int rows7 int columns60 Constr$cts a ne) e"pty Te&tArea )ith the specified n$"ber of ro)s and col$"ns* JTextArea5String text60 Constr$cts a ne) Te&tArea )ith the specified te&t displayed*

JTextArea5String text7 int rows7 int columns6 Constr$cts a ne) Te&tArea )ith the specified te&t and n$"ber of ro)s and col$"ns*

=, Java J(a#io&utton class example


J(a#io&utton
Java +)in T$torial @&plainin the JHadio3$tton Co"ponent* JHadio3$tton is si"ilar to JCheckbo&! e&cept for the defa$lt icon for each class* A set of radio b$ttons can be associated as a ro$p in )hich only one b$tton at a ti"e can be selected* J(a#io&utton Source Co#e
import java.awt.2; import java.awt.event.2; import javax.swing.2; public class J<adio:utton3emo extends J7anel $ static JFrame frame; JLabel jlb7icture; <adioListener m Listener + null; public J<adio:utton3emo%) $ // Create the radio buttons and assign Ce board shortcuts using // >nemonics J<adio:utton jrb;umbers + new J<adio:utton%,;umbers,); jrb;umbers.set>nemonic%Ce 5vent.1CD;); jrb;umbers.set4ctionCommand%,numbers,); jrb;umbers.set&elected%true); J<adio:utton jrb4lphabets + new J<adio:utton%,4lphabets,); jrb4lphabets.set>nemonic%Ce 5vent.1CD4); jrb4lphabets.set4ctionCommand%,alphabets,); J<adio:utton jrb& mbols + new J<adio:utton%,& mbols,); jrb& mbols.set>nemonic%Ce 5vent.1CD&); jrb& mbols.set4ctionCommand%,s mbols,); // Broup the radio buttons. :uttonBroup group + new :uttonBroup%); group.add%jrb;umbers); group.add%jrb4lphabets); group.add%jrb& mbols); // <egister an action listener for the radio buttons. m Listener + new <adioListener%); jrb;umbers.add4ctionListener%m Listener); jrb4lphabets.add4ctionListener%m Listener); jrb& mbols.add4ctionListener%m Listener); // &et up the picture label jlb7icture + new JLabel%new =mage=con%,, G ,numbers, G ,.jpg,)); // &et the 3efault =mage jlb7icture.set7referred&i-e%new 3imension%.880 .AA));

// 7ut the radio buttons in a column in a panel J7anel jpl<adio + new J7anel%); jpl<adio.setLa out%new BridLa out%/0 .)); jpl<adio.add%jrb;umbers); jpl<adio.add%jrb4lphabets); jpl<adio.add%jrb& mbols); setLa out%new :orderLa out%)); add%jpl<adio0 :orderLa out.#5&6); add%jlb7icture0 :orderLa out.C5;65<); set:order%:orderFactor .create5mpt :order%A/0 A/0 A/0 A/)); * /22 Listens to the radio buttons. 2/ class <adioListener implements 4ctionListener $ public void action7erformed%4ction5vent e) $ jlb7icture.set=con%new =mage=con%,, G e.get4ctionCommand%) G ,.jpg,)); * * public static void main%&tring s'() $ frame + new JFrame%,J<adio:utton ?sage 3emo,); frame.add#indowListener%new #indow4dapter%) $ public void windowClosing%#indow5vent e) $ & stem.exit%/); * *); frame.getContent7ane%).add%new J<adio:utton3emo%)0 :orderLa out.C5;65<); frame.pack%); frame.set1isible%true);

Output

Java JRadioButton Hierarchy


0ava&*s)in Class J(a#io&utton 0ava*lan *Bb0ect

0ava*a)t*Co"ponent 0ava*a)t*Container 0ava&*s)in *JCo"ponent 0ava&*s)in *Abstract3$tton 0ava&*s)in *JTo le3$tton 0ava&*s)in *JHadio3$tton All %"ple"ented %nterfaces: Accessible! %"a eBbserver! %te"+electable! -en$Container! +eriali2able! +)in Constants

J(a#io&utton Constructor
J(a#io&utton560 Creates an initially $nselected radio b$tton )ith no set te&t* J(a#io&utton5Action a60 Creates a radiob$tton )here properties are taken fro" the Action s$pplied* J(a#io&utton5!con icon60 Creates an initially $nselected radio b$tton )ith the specified i"a e b$t no te&t* J(a#io&utton5!con icon7 %oolean selecte#60 Creates a radio b$tton )ith the specified i"a e and selection state! b$t no te&t* J(a#io&utton5String text60 Creates an $nselected radio b$tton )ith the specified te&t* J(a#io&utton5String text7 %oolean selecte#60 Creates a radio b$tton )ith the specified te&t and selection state* J(a#io&utton5String text7 !con icon6 Creates a radio b$tton that has the specified te&t and i"a e! and that is initially $nselected* J(a#io&utton5String text7 !con icon7 %oolean selecte#6 Creates a radio b$tton that has the specified te&t! i"a e! and selection state*

+>, Java JChec)&ox class example


JChec)&ox
Java +)in T$torial @&plainin the JCheck3o& Co"ponent* JCheck3o& is not a "e"ber of a checkbo& ro$p* A checkbo& can be selected and deselected! and it also displays its c$rrent state*

JChec)&ox Source Co#e


import java.awt.2; import java.awt.event.2; import javax.swing.2; public class JCheck:ox3emo extends J7anel $ //Four accessor choices provide for .K different combinations JCheck:ox jcbChin; JCheck:ox jcbBlasses; JCheck:ox jcb"air; JCheck:ox jcb6eeth; /2 6he image for each combination is contained in a separate image file whose name indicates the accessories. 6he filenames are ,geek@IIII.gif, where IIII can be one 2 of the following .K choices. 2/ &tring:uffer choices; JLabel jlb7icture; Check:oxListener m Listener + null; public JCheck:ox3emo%) $ // 4dd an item listener for each of the check boxes. // 6his is the listener class which contains business logic m Listener + new Check:oxListener%); // Create check boxes with default selection true jcbChin + new JCheck:ox%,Chin,); jcbChin.set>nemonic%Ce 5vent.1CDC); //4ltGC Checks/?nchecks the check :ox jcbChin.set&elected%true); jcbChin.add=temListener%m Listener); jcbBlasses + new JCheck:ox%,Blasses,); jcbBlasses.set>nemonic%Ce 5vent.1CDB); //4ltGB Checks/?nchecks the check :ox jcbBlasses.set&elected%true); jcbBlasses.add=temListener%m Listener); jcb"air + new JCheck:ox%,"air,); jcb"air.set>nemonic%Ce 5vent.1CD"); //4ltG" Checks/?nchecks the check :ox jcb"air.set&elected%true); jcb"air.add=temListener%m Listener); jcb6eeth + new JCheck:ox%,6eeth,); jcb6eeth.set>nemonic%Ce 5vent.1CD6); //4ltG6 Checks/?nchecks the check :ox jcb6eeth.set&elected%true); jcb6eeth.add=temListener%m Listener);

// =ndicates whatHs on the geek. choices + new &tring:uffer%,cght,);//3efault =mage has all the parts. // &et up the picture label jlb7icture + new JLabel%new =mage=con%,geek@, G choices.to&tring%).trim%) G ,.gif,)); jlb7icture.set6ool6ip6ext%choices.to&tring%).trim%)); // 7ut the check boxes in a column in a panel J7anel jplCheck:ox + new J7anel%); jplCheck:ox.setLa out%new BridLa out%/0 .)); jplCheck:ox.add%jcbChin); jplCheck:ox.add%jcbBlasses); jplCheck:ox.add%jcb"air); jplCheck:ox.add%jcb6eeth);

/// rows0 . Column

setLa out%new :orderLa out%)); add%jplCheck:ox0 :orderLa out.#5&6); add%jlb7icture0 :orderLa out.C5;65<); set:order%:orderFactor .create5mpt :order%A/0A/0A/0A/));

//Listens to the check boxes events class Check:oxListener implements =temListener $ public void item&tateChanged%=tem5vent e) $ int index + /; char c + H@H; !bject source + e.get&ource%); if %source ++ jcbChin) $ index + /; c + HcH; * else if %source ++ jcbBlasses) $ index + .; c + HgH; * else if %source ++ jcb"air) $ index + A; c + HhH; * else if %source ++ jcb6eeth) $ index + E; c + HtH; * if %e.get&tateChange%) ++ =tem5vent.35&5L5C653) c + H@H; choices.setChar4t%index0 c); jlb7icture.set=con%new =mage=con%,geek@, G choices.to&tring%).trim%) G ,.gif,)); jlb7icture.set6ool6ip6ext%choices.to&tring%));

* *

public static void main%&tring s'() $ JFrame frame + new JFrame%,JCheck:ox ?sage 3emo,); frame.add#indowListener%new #indow4dapter%) $ public void windowClosing%#indow5vent e) $ & stem.exit%/); * *); frame.setContent7ane%new JCheck:ox3emo%)); frame.pack%); frame.set1isible%true);

Output

++, Java JCom%o&ox class example


JCom%o&ox
Java +)in T$torial @&plainin the JCo"bo3o& Co"ponent* JCo"bo3o& is like a drop do)n bo& = yo$ can click a drop-do)n arro) and select an option fro" a list* %t enerates %te"@vent* For e&a"ple! )hen the co"ponent has foc$s! pressin a key that corresponds to the first character in so"e entry1s na"e selects that entry* A vertical scrollbar is $sed for lon er lists*

JCom%o&ox Source Co#e


import java.awt.2;

import java.awt.event.2; import javax.swing.2; public class JCombo:ox3emo extends J7anel $ JLabel jlb7icture; public JCombo:ox3emo%) $ &tring'( combo6 pes + $ ,;umbers,0 ,4lphabets,0 ,& mbols, *; // Create the combo box0 and set And item as 3efault JCombo:ox combo6 pesList + new JCombo:ox%combo6 pes); combo6 pesList.set&elected=ndex%A); combo6 pesList.add4ctionListener%new 4ctionListener%) $ public void action7erformed%4ction5vent e) $ JCombo:ox jcmb6 pe + %JCombo:ox) e.get&ource%); &tring cmb6 pe + %&tring) jcmb6 pe.get&elected=tem%); jlb7icture.set=con%new =mage=con%,, G cmb6 pe.trim%).toLowerCase%) G ,.jpg,)); *

*); // &et up the picture jlb7icture + new JLabel%new =mage=con%,, G combo6 pes'combo6 pesList.get&elected=ndex%)( G ,.jpg,)); jlb7icture.set:order%:orderFactor .create5mpt :order%./0 /0 /0 /)); jlb7icture.set7referred&i-e%new 3imension%.880 .AA G ./)); // La out the demo setLa out%new :orderLa out%)); add%combo6 pesList0 :orderLa out.;!<6"); add%jlb7icture0 :orderLa out.&!?6"); set:order%:orderFactor .create5mpt :order%A/0 A/0 A/0 A/)); * public static void main%&tring s'() $ JFrame frame + new JFrame%,JCombo:ox ?sage 3emo,); frame.add#indowListener%new #indow4dapter%) $ public void windowClosing%#indow5vent e) $ & stem.exit%/); * *); frame.setContent7ane%new JCombo:ox3emo%)); frame.pack%); frame.set1isible%true); *

Output

Another Example0 JCom%o&ox Source Co#e


import java.awt.2; import java.awt.event.2; import javax.swing.2; import javax.swing.border.2; import java.util.2; import java.text.2; public class 3ateCombo:ox3emo extends J7anel $ static JLabel &tring public JFrame frame; jlb<esult; date7atternDCurrent; 3ateCombo:ox3emo%) $ &tring'( date7atterns + $ ,dd >>>>> ,0 ,dd.>>. ,0 ,>>/dd/ , .>>.dd B HatH hhLmmLss -,0 ,5550 >>> d0 HH ,hLmm a,0 ,"LmmLssL&&&,0 ,CLmm a0-,0 , .>>>>>.dd BBB hhLmm aaa, *; date7atternDCurrent + date7atterns'/(; // &et up the ?= for selecting a pattern. JLabel jlb"eading + new JLabel% ,5nter 3ate pattern /&elect from listL,); JCombo:ox patternList + new JCombo:ox%date7atterns); patternList.set5ditable%true); patternList.set4lignmentI%Component.L5F6D4L=B;>5;6); patternList.add4ctionListener%new 4ctionListener%) $

,0 ,0

public void action7erformed%4ction5vent e) $ JCombo:ox jcmb3ates + %JCombo:ox) e.get&ource%); &tring seleted3ate + %&tring) jcmb3ates.get&elected=tem%); date7atternDCurrent + seleted3ate; show3ateinLabel%); * *); // Create the ?= for displa ing result

JLabel jlb<esult"eading + new JLabel%,Current 3ate/6ime,0 JLabel.L5F6); jlb<esult + new JLabel%, ,); jlb<esult.setForeground%Color.black); jlb<esult.set:order%:orderFactor .createCompound:order% :orderFactor .createLine:order%Color.black)0 :orderFactor .create5mpt :order%90 90 90 9))); // La out ever thing J7anel jpn3ate + new J7anel%); jpn3ate.setLa out%new :oxLa out%jpn3ate0 :oxLa out.JD4I=&)); jpn3ate.add%jlb"eading); jpn3ate.add%patternList); J7anel jpn<esults + new J7anel%); jpn<esults.setLa out%new BridLa out%/0 .)); jpn<esults.add%jlb<esult"eading); jpn<esults.add%jlb<esult); setLa out%new :oxLa out%this0 :oxLa out.JD4I=&)); jpn3ate.set4lignmentI%Component.L5F6D4L=B;>5;6); jpn<esults.set4lignmentI%Component.L5F6D4L=B;>5;6); add%jpn3ate); add%:ox.create<igid4rea%new 3imension%/0 ./))); add%jpn<esults); set:order%:orderFactor .create5mpt :order%./0 ./0 ./0 ./)); show3ateinLabel%); * // constructor /22 Formats and displa s toda Hs date. 2/ public void show3ateinLabel%) $ 3ate toda + new 3ate%); &imple3ateFormat formatter + new &imple3ateFormat% date7atternDCurrent); tr $ &tring date&tring + formatter.format%toda ); jlb<esult.setForeground%Color.black); jlb<esult.set6ext%date&tring); * catch %=llegal4rgument5xception e) $ jlb<esult.setForeground%Color.red); jlb<esult.set6ext%,5rrorL , G e.get>essage%)); * * public static void main%&tring s'() $ frame + new JFrame%,JCombo:ox ?sage 3emo,); frame.add#indowListener%new #indow4dapter%) $ public void windowClosing%#indow5vent e) $ & stem.exit%/); * *); frame.setContent7ane%new 3ateCombo:ox3emo%)); frame.pack%); frame.set1isible%true); *

Output

Java J omboBox Hierarchy


0ava&*s)in Class JCo"bo3o& 0ava*lan *Bb0ect 0ava*a)t*Co"ponent 0ava*a)t*Container 0ava&*s)in *JCo"ponent 0ava&*s)in *JCo"bo3o& All !mplemente# !nter/aces0 Accessible! ActionListener! @ventListener! %"a eBbserver! %te"+electable! ListDataListener! -en$Container! +eriali2able

JCom%o&ox Constructor
JCom%o&ox560 Creates a JCo"bo3o& )ith a defa$lt data "odel* JCom%o&ox5Com%o&oxMo#el aMo#el6 Creates a JCo"bo3o& that takes it1s ite"s fro" an e&istin Co"bo3o&-odel* JCom%o&ox5O%ject?@ items60 Creates a JCo"bo3o& that contains the ele"ents in the specified array* JCom%o&ox5Vector items60 Creates a JCo"bo3o& that contains the ele"ents in the specified /ector*

+.,Java J$ist class example


J$ist
Java +)in T$torial @&plainin the JList Co"ponent* JList provides a scrollable set of ite"s fro" )hich one or "ore "ay be selected* JList can be pop$lated fro" an Array or /ector* JList does not s$pport scrollin directly=instead! the list "$st be associated )ith a scrollpane* The vie) port $sed by the scrollpane can also have a $ser-defined border* JList actions are handled $sin List+electionListener*

J$ist Source Co#e


import javax.swing.2; import javax.swing.event.List&election5vent; import javax.swing.event.List&electionListener; import java.awt.2; import java.awt.event.2; pu public class JList3emo extends JFrame $ JList list; &tring'( listColor;ames + $ ,black,0 ,blue,0 ,green,0 , ellow,0 ,white, *; Color'( listColor1alues + $ Color.:L4CC0 Color.:L?50 Color.B<55;0 Color.J5LL!#0 Color.#"=65 *; Container contentpane; public JList3emo%) $ super%,List &ource 3emo,); contentpane + getContent7ane%); contentpane.setLa out%new FlowLa out%)); list + new JList%listColor;ames); list.set&elected=ndex%/); list.set&election>ode%List&election>odel.&=;BL5D&5L5C6=!;); contentpane.add%new J&croll7ane%list)); list.addList&electionListener%new List&electionListener%) $ public void valueChanged%List&election5vent e) $ contentpane.set:ackground%listColor1alues'list .get&elected=ndex%)(); * *); set&i-e%A//0 A//); set1isible%true);

* public static void main%&tring'( args) $ JList3emo test + new JList3emo%); test.set3efaultClose!peration%JFrame.5I=6D!;DCL!&5); *

Output

Java JList

lass

0ava&*s)in Class Class JList 0ava*lan *Bb0ect 0ava*a)t*Co"ponent 0ava*a)t*Container 0ava&*s)in *JCo"ponent 0ava&*s)in *JList All %"ple"ented %nterfaces: Accessible! %"a eBbserver! -en$Container! +crollable! +eriali2able

J$ist Constructor
JList9:: Constr$cts a JList )ith an e"pty "odel* JList9List-odel data-odel:: Constr$cts a JList that displays the ele"ents in the specified! non-n$ll "odel* JList9Bb0ectNO listData:: Constr$cts a JList that displays the ele"ents in the specified array* JList9/ector listData:: Constr$cts a JList that displays the ele"ents in the specified /ector*

+1, Java JTa%%e#'ane class example


JTa%%e#'ane
Java +)in T$torial @&plainin the JTabbed8ane Co"ponent* A JTabbed8ane contains a tab that can have a tool tip and a "ne"onic! and it can display both te&t and an i"a e* The shape o/ a ta% an# the way in which the selecte# ta% is #isplaye# varies %y $oo) an# eel,

JTa%%e#'ane Source Co#e


import javax.swing.J6abbed7ane; import javax.swing.=mage=con; import javax.swing.JLabel; import javax.swing.J7anel; import javax.swing.JFrame; import java.awt.2; import java.awt.event.2; public class J6abbed7ane3emo extends J7anel $

public J6abbed7ane3emo%) $ =mage=con icon + new =mage=con%,java@swing@tutorial.J7B,); J6abbed7ane jtb5xample + new J6abbed7ane%); J7anel jpl=nner7anel. + create=nner7anel%,6ab . Contains 6ooltip and =con,); jtb5xample.add6ab%,!ne,0 icon0 jpl=nner7anel.0 ,6ab .,); jtb5xample.set&elected=ndex%/); J7anel jpl=nner7anelA + create=nner7anel%,6ab A Contains =con onl ,); jtb5xample.add6ab%,6wo,0 icon0 jpl=nner7anelA); J7anel jpl=nner7anelE + create=nner7anel%,6ab E Contains 6ooltip and =con,); jtb5xample.add6ab%,6hree,0 icon0 jpl=nner7anelE0 ,6ab E,); J7anel jpl=nner7anelR + create=nner7anel%,6ab R Contains 6ext onl ,); jtb5xample.add6ab%,Four,0 jpl=nner7anelR); // 4dd the tabbed pane to this panel. setLa out%new BridLa out%.0 .)); add%jtb5xample); * protected J7anel create=nner7anel%&tring text) $ J7anel jpl7anel + new J7anel%); JLabel jlb3ispla + new JLabel%text); jlb3ispla .set"ori-ontal4lignment%JLabel.C5;65<); jpl7anel.setLa out%new BridLa out%.0 .)); jpl7anel.add%jlb3ispla ); return jpl7anel; * public static void main%&tring'( args) $ JFrame frame + new JFrame%,6abbed7ane &ource 3emo,); frame.add#indowListener%new #indow4dapter%) $ public void windowClosing%#indow5vent e) $ & stem.exit%/); * *); frame.getContent7ane%).add%new J6abbed7ane3emo%)0 :orderLa out.C5;65<); frame.set&i-e%R//0 .A9); frame.set1isible%true);

Output

JTabbed8ane >$estion

When % $se a JTabbed8ane and )ant to listen to )hich tab is bein clicked! )hich listerner sho$ld % $se? Ans)er: Chan eListener

Java JTabbedPane Hierarchy


0ava&*s)in Class JTabbed8ane 0ava*lan *Bb0ect 0ava*a)t*Co"ponent 0ava*a)t*Container 0ava&*s)in *JCo"ponent 0ava&*s)in *JTabbed8ane All %"ple"ented %nterfaces: Accessible! %"a eBbserver! -en$Container! +eriali2able! +)in Constants

JTa%%e#'ane Constructor
JTabbed8ane9: Creates an e"pty Tabbed8ane )ith a defa$lt tab place"ent of JTabbed8ane*TB8* JTabbed8ane9int tab8lace"ent: Creates an e"pty Tabbed8ane )ith the specified tab place"ent of either: JTabbed8ane*TB8! JTabbed8ane*3BTTB-! JTabbed8ane*L@FT! or JTabbed8ane*H%'?T* JTabbed8ane9int tab8lace"ent! int tabLayo$t8olicy: Creates an e"pty Tabbed8ane )ith the specified tab place"ent and tab layo$t policy*

+4, Java JTool&ar class example


JTool%ar Java +)in T$torial @&plainin the JTool3ar Co"ponent* A JToolbar contains a n$"ber of co"ponents )hose type is $s$ally so"e kind of b$tton )hich can also incl$de separators to ro$p related co"ponents )ithin the toolbar* The toolbar can be docked a ainst any of the fo$r ed es of a container 9panel or a fra"e:* A toolbar can also be "ade to float* Toolbars $ses 3o&Layo$t! )hich arran es co"ponents in one hori2ontal ro), vertical col$"n* This layo$t "ana er does not force each co"ponent to have the sa"e hei ht or )idthA instead! it $ses their preferred hei ht or )idth! and atte"pts to ali n the"* 4o$ can ad0$st the res$ltin ali n"ent by callin class Co"ponent1s "ethods setAli n"entP9: and,or setAli n"ent49: on each co"ponent*
import javax.swing.J6ool:ar; import javax.swing.J:utton; import javax.swing.=mage=con;

import javax.swing.JFrame; import javax.swing.J6ext4rea; import javax.swing.J&croll7ane; import javax.swing.J7anel; import javax.swing.J6extField; impor t java.awt.2; import java.awt.event.2; public class J6ool:ar3emo extends JFrame $ protected J6ext4rea text4rea; protected &tring newline + ,On,; public J6ool:ar3emo%) $ super%,6ool:ar3emo,); // Create the toolbar. J6ool:ar jtb>ain6oolbar + new J6ool:ar%); // setFloatable%false) to make the toolbar non movable add:uttons%jtb>ain6oolbar); // Create the text area text4rea + new J6ext4rea%90 E/); J&croll7ane js7ane + new J&croll7ane%text4rea); // La out the content pane. J7anel jplContent7ane + new J7anel%); jplContent7ane.setLa out%new :orderLa out%)); jplContent7ane.set7referred&i-e%new 3imension%R//0 .//)); jplContent7ane.add%jtb>ain6oolbar0 :orderLa out.;!<6"); jplContent7ane.add%js7ane0 :orderLa out.C5;65<); setContent7ane%jplContent7ane); * public void add:uttons%J6ool:ar jtb6ool:ar) $ J:utton jbn6oolbar:uttons + null; // first button jbn6oolbar:uttons + new J:utton%new =mage=con%,left.gif,)); jbn6oolbar:uttons.set6ool6ip6ext%,left,); jbn6oolbar:uttons.add4ctionListener%new 4ctionListener%) $ public void action7erformed%4ction5vent e) $ displa =n6ext4rea%,6his is Left 6oolbar :utton <eporting,); *

*); jtb6ool:ar.add%jbn6oolbar:uttons); // And button jbn6oolbar:uttons + new J:utton%new =mage=con%,right.gif,)); jbn6oolbar:uttons.set6ool6ip6ext%,right,); jbn6oolbar:uttons.add4ctionListener%new 4ctionListener%) $

*); jtb6ool:ar.add%jbn6oolbar:uttons); jtb6ool:ar.add&eparator%); // Erd button jbn6oolbar:uttons + new J:utton%new =mage=con%,open.gif,)); jbn6oolbar:uttons.set6ool6ip6ext%,open,); jbn6oolbar:uttons.add4ctionListener%new 4ctionListener%) $

public void action7erformed%4ction5vent e) $ displa =n6ext4rea%,6his is right 6oolbar :utton <eporting,); *

public void action7erformed%4ction5vent e) $ displa =n6ext4rea%,6his is open 6oolbar :utton <eporting,); * *); jtb6ool:ar.add%jbn6oolbar:uttons); // Rth button jbn6oolbar:uttons + new J:utton%new =mage=con%,save.gif,)); jbn6oolbar:uttons.set6ool6ip6ext%,save,); jbn6oolbar:uttons.add4ctionListener%new 4ctionListener%) $ public void action7erformed%4ction5vent e) $ displa =n6ext4rea%,6his is save 6oolbar :utton <eporting,); * *); jtb6ool:ar.add%jbn6oolbar:uttons); // #e can add separators to group similar components jtb6ool:ar.add&eparator%); // fourth button jbn6oolbar:uttons + new J:utton%,6ext button,); jbn6oolbar:uttons.add4ctionListener%new 4ctionListener%) $ public void action7erformed%4ction5vent e) $ displa =n6ext4rea%,6ext button,); *

*); jtb6ool:ar.add%jbn6oolbar:uttons); // fifth component is ;!6 a buttonN J6extField jtf:utton + new J6extField%,6ext field,); jtf:utton.set5ditable%false); jtf:utton.add4ctionListener%new 4ctionListener%) $ public void action7erformed%4ction5vent e) $ displa =n6ext4rea%,6extField component can also be placed,); *

* protected void displa =n6ext4rea%&tring action3escription) $ text4rea.append%action3escription G newline); * public static void main%&tring'( args) $ J6ool:ar3emo jtf6oolbar + new J6ool:ar3emo%); // 5xtends Frame. jtf6oolbar.pack%); jtf6oolbar.add#indowListener%new #indow4dapter%) $ public void windowClosing%#indow5vent e) $ & stem.exit%/); *

*); jtb6ool:ar.add%jtf:utton);

*); jtf6oolbar.set1isible%true);

Output

Java JToolBar Hierarchy


0ava&*s)in Class JTool3ar 0ava*lan *Bb0ect 0ava*a)t*3orderLayo$t All %"ple"ented %nterfaces: Layo$t-ana er! Layo$t-ana er2! +eriali2able

JTool&ar Constructor
JTool3ar9:: Creates a ne) tool barA orientation defa$lts to ?BH%QBCTAL* JTool3ar9int orientation:: Creates a ne) tool bar )ith the specified orientation* JTool3ar9+trin na"e:: Creates a ne) tool bar )ith the specified na"e* JTool3ar9+trin na"e! int orientation:: Creates a ne) tool bar )ith a specified na"e and orientation*

+9, Java low$ayout class example


low$ayout
Java +)in T$torial @&plainin the Flo)Layo$t* Flo)Layo$t )hen $sed arran es s)in co"ponents fro" left to ri ht $ntil there1s no "ore space available* Then it be ins a ne) ro) belo) it and "oves fro" left to ri ht a ain* @ach co"ponent in a Flo)Layo$t ets as "$ch space as it needs and no "ore* Flo)Layo$t +o$rce Code
import import import import java.awt.Component!rientation; java.awt.Container; java.awt.3imension; java.awt.FlowLa out;

import javax.swing.J:utton; import javax.swing.JCheck:ox; import javax.swing.JFrame;

import javax.swing.JLabel; import javax.swing.J6extField; public class FlowLa out3emo $ public static boolean <=B"6D6!DL5F6 + false; public static void addComponents%Container content7ane) $ if %<=B"6D6!DL5F6) $ content7ane.setComponent!rientation% Component!rientation.<=B"6D6!DL5F6); * content7ane.setLa out%new FlowLa out%)); content7ane.add%new content7ane.add%new content7ane.add%new content7ane.add%new content7ane.add%new * private static void create4nd&howB?=%) $ JFrame.set3efaultLook4ndFeel3ecorated%true); JFrame frame + new JFrame%,FlowLa out &ource 3emo,) $ public 3imension get>inimum&i-e%) $ 3imension pref&i-e + get7referred&i-e%); return new 3imension%.//0 pref&i-e.height); * *; frame.set3efaultClose!peration%JFrame.5I=6D!;DCL!&5); //&et up the content pane and components in FlowLa out addComponents%frame.getContent7ane%)); frame.pack%); frame.set1isible%true); * public static void main%&tring'( args) $ javax.swing.&wing?tilities.invokeLater%new <unnable%) $ public void run%) $ create4nd&howB?=%); * *); * JLabel%,JLabel .,)); J:utton%,J:utton A,)); JCheck:ox%,JCheck:ox E,)); J6extField%,Long@;amed J6extField R,)); J:utton%,J:utton 9,));

Output

+:, Java &or#er$ayout class example

&or#er$ayout
Java +)in T$torial @&plainin the 3orderLayo$t * 3orderLayo$t places s)in co"ponents in the Corth! +o$th! @ast! West and center of a container* All e&tra space is placed in the center area* 4o$ can add hori2ontal and vertical aps bet)een the areas* @very content pane is initiali2ed to $se a 3orderLayo$t* Co"ponents are added to a 3orderLayo$t by $sin the add "ethod* JFra"eEs content pane defa$lt layo$t "ana er: 3orderLayo$t* %n 3orderLayo$t! a co"ponentEs position is specified by a second ar $"ent to add*

&or#er$ayout Source Co#e


2 :orderLa out3emo.java is a ..R application that reMuires no other files. import import import import import import java.awt.:orderLa out; java.awt.Container; java.awt.3imension; javax.swing.J:utton; javax.swing.JFrame; javax.swing.JLabel;

public class :orderLa out3emo $ public static boolean <=B"6D6!DL5F6 + false; // // public static void addComponents6o7ane%Container content7ane) $ ?se :orderLa out. 3efault empt constructor with no hori-ontal and vertical gaps content7ane.setLa out%new :orderLa out%909)); if %N%content7ane.getLa out%) instanceof :orderLa out)) $ content7ane.add%new JLabel%,Container doesnHt use :orderLa outN,)); return; * if %<=B"6D6!DL5F6) $ content7ane.setComponent!rientation% java.awt.Component!rientation.<=B"6D6!DL5F6); * J:utton jbn&ample:uttons + new J:utton%,:utton . %74B5D&64<6),); content7ane.add%jbn&ample:uttons0 :orderLa out.74B5D&64<6); jbn&ample:uttons + new J:utton%,:utton A %C5;65<),); jbn&ample:uttons.set7referred&i-e%new 3imension%A//0 .//)); content7ane.add%jbn&ample:uttons0 :orderLa out.C5;65<); jbn&ample:uttons + new J:utton%,:utton E %L=;5D&64<6),); content7ane.add%jbn&ample:uttons0 :orderLa out.L=;5D&64<6); jbn&ample:uttons + new J:utton%,Long@;amed :utton R %74B5D5;3),); content7ane.add%jbn&ample:uttons0 :orderLa out.74B5D5;3);

jbn&ample:uttons + new J:utton%,9 %L=;5D5;3),); content7ane.add%jbn&ample:uttons0 :orderLa out.L=;5D5;3); * private static void create4nd&howB?=%) $ JFrame.set3efaultLook4ndFeel3ecorated%true); JFrame frame + new JFrame%,:orderLa out &ource 3emo,); frame.set3efaultClose!peration%JFrame.5I=6D!;DCL!&5); //&et up the content pane and add swing components to it addComponents6o7ane%frame.getContent7ane%)); frame.pack%); frame.set1isible%true);

public static void main%&tring'( args) $ javax.swing.&wing?tilities.invokeLater%new <unnable%) $ public void run%) $ create4nd&howB?=%); * *); *

output

+;, Java *ri#$ayout class example

*ri#$ayout
Java +)in T$torial @&plainin the 'ridLayo$t* 'ridLayo$t is a layo$t "ana er that lays o$t a container1s co"ponents in a rectan $lar rid* The container is divided into e>$al-si2ed rectan les! and one co"ponent is placed in each rectan le*

*ri#$ayout Source Co#e


import java.awt.2; import javax.swing.2; public class BridLa out3emo $ public final static boolean <=B"6D6!DL5F6 + false; public static void addComponents6o7ane%Container content7ane) $ if %<=B"6D6!DL5F6) $ content7ane.setComponent!rientation% Component!rientation.<=B"6D6!DL5F6); * 4n number of rows and A columns content7ane.setLa out%new BridLa out%/0A)); content7ane.add%new content7ane.add%new content7ane.add%new content7ane.add%new content7ane.add%new JLabel%,JLabel .,)); J:utton%,J:utton A,)); JCheck:ox%,JCheck:ox E,)); J6extField%,Long@;amed J6extField R,)); J:utton%,J:utton 9,));

//

private static void create4nd&howB?=%) $ JFrame.set3efaultLook4ndFeel3ecorated%true); JFrame frame + new JFrame%,BridLa out &ource 3emo,); frame.set3efaultClose!peration%JFrame.5I=6D!;DCL!&5); //&et up the content pane and components in BridLa out addComponents6o7ane%frame.getContent7ane%)); frame.pack%); frame.set1isible%true); * public static void main%&tring'( args) $ javax.swing.&wing?tilities.invokeLater%new <unnable%) $ public void run%) $ create4nd&howB?=%); * *); *

Output

Java !ridLayout Hierarchy


0ava&*s)in Class 'ridLayo$t 0ava*lan *Bb0ect 0ava*a)t*'ridLayo$t All %"ple"ented %nterfaces: Layo$t-ana er! +eriali2able

*ri#$ayout Constructor
'ridLayo$t9:: Creates a rid layo$t )ith a defa$lt of one col$"n per co"ponent! in a sin le ro)* 'ridLayo$t9int ro)s! int cols:: Creates a rid layo$t )ith the specified n$"ber of ro)s and col$"ns* 'ridLayo$t9int ro)s! int cols! int h ap! int v ap:: Creates a rid layo$t )ith the specified n$"ber of ro)s and col$"ns*

+<, Java *ri#&ag$ayout class example


*ri#&ag$ayout
Java +)in T$torial @&plainin the 'rid3a Layo$t* 'rid3a Layo$t is a layo$t "ana er that lays o$t a container1s co"ponents in a rid of cells )ith each co"ponent occ$pyin one or "ore cells! called its display area* The display area ali ns co"ponents vertically and hori2ontally! )itho$t re>$irin that the co"ponents be of the sa"e si2e* *ri#&ag$ayout Source Co#e
import import import import import java.awt.2; javax.swing.J:utton; javax.swing.JCombo:ox; javax.swing.JFrame; javax.swing.J6extField;

public class Brid:agLa out3emo $ public static void addComponents6o7ane%Container pane) $ J:utton jbn:utton; pane.setLa out%new Brid:agLa out%)); Brid:agConstraints g:C + new Brid:agConstraints%); g:C.fill + Brid:agConstraints."!<=P!;64L; jbn:utton + new J:utton%,:utton .,); g:C.weightx + /.9; g:C.gridx + /; g:C.grid + /; pane.add%jbn:utton0 g:C); J6extField jtf + new J6extField%,6extField .,); g:C.gridx + A; g:C.grid + /; jtf.set5ditable%false); pane.add%jtf0 g:C); jbn:utton + new J:utton%,:utton E,); g:C.gridx + A; g:C.grid + /; pane.add%jbn:utton0 g:C); jbn:utton + new J:utton%,:utton R,); g:C.ipad + R/; //6his component has more breadth compared to other buttons g:C.weightx + /./; g:C.gridwidth + E; g:C.gridx + /; g:C.grid + .; pane.add%jbn:utton0 g:C); JCombo:ox jcmb&ample + new JCombo:ox%new &tring'($,Combo:ox .,0 ,hi,0 ,hello,*); g:C.ipad + /; g:C.weight + ../; g:C.anchor + Brid:agConstraints.74B5D5;3; g:C.insets + new =nsets%./0/0/0/); //7adding g:C.gridx + .; g:C.gridwidth + A; g:C.grid + A; pane.add%jcmb&ample0 g:C);

private static void create4nd&howB?=%) $ JFrame.set3efaultLook4ndFeel3ecorated%true); JFrame frame + new JFrame%,Brid:agLa out &ource 3emo,); frame.set3efaultClose!peration%JFrame.5I=6D!;DCL!&5); //&et up the content pane. addComponents6o7ane%frame.getContent7ane%));

frame.pack%); frame.set1isible%true); * public static void main%&tring'( args) $ javax.swing.&wing?tilities.invokeLater%new <unnable%) $ public void run%) $ create4nd&howB?=%); * *); *

Output

After @&pandin the Fra"e

!ridBa"Layout lass 0ava&*s)in Class 'rid3a Layo$t 0ava*lan *Bb0ect 0ava*a)t*'rid3a Layo$t All %"ple"ented %nterfaces: Layo$t-ana er! Layo$t-ana er2! +eriali2able

*ri#&ag$ayout Constructor
'rid3a Layo$t9:: Creates a rid ba layo$t "ana er**

+=, Java JMenu class example


JMenu
Java +)in T$torial @&plainin the J-en$3ar Co"ponent* +)in provides s$pport for p$ll-do)n and pop$p "en$s* A J-en$bar can contain several J-en$ 1s* @ach of the J-en$ 1s can contain a series of J-en$%te" 1s that yo$ can select* ?o) -en$1s Are Created? 5* First! A J-en$bar is created 2* Then! )e attach all of the "en$s to this J-en$bar* F* Then )e add J-en$%te" 1s to the J-en$ 1s* G* The J-en$bar is then added to the fra"e* 3y defa$lt! each J-en$%te" added to a J-en$ is enabled= that is! it can be selected* %n certain sit$ations! )e "ay need to disable a J-en$%te"* This is done by callin set@nabled9:* The set@nabled9: "ethod also allo)s co"ponents to be enabled*

JMenu Source Co#e

import java.awt.2; import java.awt.event.2; import javax.swing.J>enu; import javax.swing.J>enu=tem; import javax.swing.JCheck:ox>enu=tem; import javax.swing.J<adio:utton>enu=tem;

import javax.swing.:uttonBroup; import javax.swing.J>enu:ar; import javax.swing.Ce &troke; import javax.swing.=mage=con; import javax.swing.J7anel; import javax.swing.J6ext4rea; import javax.swing.J&croll7ane; import javax.swing.JFrame; //?sed 4ction Listner for J>enu=tem S J<adio:utton>enu=tem //?sed =tem Listner for JCheck:ox>enu=tem public class J>enu3emo implements 4ctionListener0 =temListener $ J6ext4rea jt4rea!utput; J&croll7ane jsp7ane; public J>enu:ar createJ>enu:ar%) $ J>enu:ar main>enu:ar; J>enu menu.0 menuA0 submenu; J>enu=tem plain6ext>enu=tem0 text=con>enu=tem0 icon>enu=tem0 sub>enu=tem; J<adio:utton>enu=tem rb>enu=tem; JCheck:ox>enu=tem cb>enu=tem; =mage=con icon + create=mage=con%,jmenu.jpg,); main>enu:ar + new J>enu:ar%); menu. + new J>enu%,>enu .,); menu..set>nemonic%Ce 5vent.1CD>); main>enu:ar.add%menu.); // Creating the >enu=tems plain6ext>enu=tem + new J>enu=tem%,>enu item with 7lain 6ext,0 Ce 5vent.1CD6); // can be done either wa for assigning shortcuts // menu=tem.set>nemonic%Ce 5vent.1CD6); // 4ccelerators0 offer ke board shortcuts to b pass navigating the menu // hierarch . plain6ext>enu=tem.set4ccelerator%Ce &troke.getCe &troke% Ce 5vent.1CD.0 4ction5vent.4L6D>4&C)); plain6ext>enu=tem.add4ctionListener%this); menu..add%plain6ext>enu=tem); text=con>enu=tem + new J>enu=tem%,>enu =tem with 6ext S =mage,0 icon); text=con>enu=tem.set>nemonic%Ce 5vent.1CD:); text=con>enu=tem.add4ctionListener%this); menu..add%text=con>enu=tem); // >enu =tem with just an =mage icon>enu=tem + new J>enu=tem%icon); icon>enu=tem.set>nemonic%Ce 5vent.1CD3); icon>enu=tem.add4ctionListener%this); menu..add%icon>enu=tem); menu..add&eparator%); // <adio :utton >enu items follow a seperator :uttonBroup itemBroup + new :uttonBroup%); rb>enu=tem + new J<adio:utton>enu=tem% ,>enu =tem with <adio :utton,); rb>enu=tem.set&elected%true); rb>enu=tem.set>nemonic%Ce 5vent.1CD<); itemBroup.add%rb>enu=tem); rb>enu=tem.add4ctionListener%this);

* public Container createContent7ane%) $ // Create the content@pane@to@be. J7anel jplContent7ane + new J7anel%new :orderLa out%)); jplContent7ane.setLa out%new :orderLa out%));// Can do it either wa // to set la out jplContent7ane.set!paMue%true); // Create a scrolled text area. jt4rea!utput + new J6ext4rea%90 E/); jt4rea!utput.set5ditable%false); jsp7ane + new J&croll7ane%jt4rea!utput); // 4dd the text area to the content pane. jplContent7ane.add%jsp7ane0 :orderLa out.C5;65<); return jplContent7ane; * /22 <eturns an =mage=con0 or null if the path was invalid. 2/ protected static =mage=con create=mage=con%&tring path) $ java.net.?<L img?<L + J>enu3emo.class.get<esource%path); if %img?<L N+ null) $ return new =mage=con%img?<L); * else $ & stem.err.println%,CouldnHt find image fileL , G path); return null;

menu..add%rb>enu=tem); rb>enu=tem + new J<adio:utton>enu=tem% ,>enu =tem A with <adio :utton,); itemBroup.add%rb>enu=tem); rb>enu=tem.add4ctionListener%this); menu..add%rb>enu=tem); menu..add&eparator%); // <adio :utton >enu items follow a seperator cb>enu=tem + new JCheck:ox>enu=tem%,>enu =tem with check box,); cb>enu=tem.set>nemonic%Ce 5vent.1CDC); cb>enu=tem.add=temListener%this); menu..add%cb>enu=tem); cb>enu=tem + new JCheck:ox>enu=tem%,>enu =tem A with check box,); cb>enu=tem.add=temListener%this); menu..add%cb>enu=tem); menu..add&eparator%); // &ub >enu follows a seperator submenu + new J>enu%,&ub >enu,); submenu.set>nemonic%Ce 5vent.1CD&); sub>enu=tem + new J>enu=tem%,&ub >enu=tem .,); sub>enu=tem.set4ccelerator%Ce &troke.getCe &troke%Ce 5vent.1CDA0 4ction5vent.C6<LD>4&C)); sub>enu=tem.add4ctionListener%this); submenu.add%sub>enu=tem); sub>enu=tem + new J>enu=tem%,&ub >enu=tem A,); submenu.add%sub>enu=tem); sub>enu=tem.add4ctionListener%this); menu..add%submenu); // :uild second menu in the menu bar. menuA + new J>enu%,>enu A,); menuA.set>nemonic%Ce 5vent.1CD;); main>enu:ar.add%menuA); return main>enu:ar;

* * private static void createB?=%) $ JFrame.set3efaultLook4ndFeel3ecorated%true); // Create and set up the window. JFrame frame + new JFrame%,J>enu ?sage 3emo,); frame.set3efaultClose!peration%JFrame.5I=6D!;DCL!&5); J>enu3emo app + new J>enu3emo%); frame.setJ>enu:ar%app.createJ>enu:ar%)); frame.setContent7ane%app.createContent7ane%)); frame.set&i-e%9//0 E//); frame.set1isible%true); * public void action7erformed%4ction5vent e) $ J>enu=tem source + %J>enu=tem) %e.get&ource%)); &tring s + ,>enu =tem sourceL , G source.get6ext%) G , %an instance of , G getClass;ame%source) G ,),; jt4rea!utput.append%s G ,On,); jt4rea!utput.setCaret7osition%jt4rea!utput.get3ocument%) .getLength%)); * public void item&tateChanged%=tem5vent e) $ J>enu=tem source + %J>enu=tem) %e.get&ource%)); &tring s + ,>enu =tem sourceL , G source.get6ext%) G , %an instance of , G getClass;ame%source) G ,), G ,On, G , &tate of check :oxL , G %%e.get&tateChange%) ++ =tem5vent.&5L5C653) T ,selected, L ,unselected,); jt4rea!utput.append%s G ,On,); jt4rea!utput.setCaret7osition%jt4rea!utput.get3ocument%) .getLength%)); * // <eturns the class name0 no package info protected &tring getClass;ame%!bject o) $ &tring class&tring + o.getClass%).get;ame%); int dot=ndex + class&tring.last=ndex!f%,.,); return class&tring.substring%dot=ndex G .); // <eturns onl Class name * public static void main%&tring'( args) $ javax.swing.&wing?tilities.invokeLater%new <unnable%) $ public void run%) $ createB?=%); * * *);

Output