Full text of "Core Java An Integrated Approach Covers Concepts ... [PDF]

Mr. R Nageswara Rao is teaching and interacting with more than 1000 new students every month, including software develop

7 downloads 49 Views 936KB Size

Recommend Stories


using an integrated approach
If you are irritated by every rub, how will your mirror be polished? Rumi

An Integrated Approach
In the end only three things matter: how much you loved, how gently you lived, and how gracefully you

An Integrated Approach (Concepts, Problems and Interview Questions)
Sorrow prepares you for joy. It violently sweeps everything out of your house, so that new joy can find

A Down-To-Earth Approach Core Concepts
If your life's work can be accomplished in your lifetime, you're not thinking big enough. Wes Jacks

PDF Core Java Volume I
I want to sing like the birds sing, not worrying about who hears or what they think. Rumi

PdF Core Java, Volume II
You have survived, EVERY SINGLE bad day so far. Anonymous

[PDF] Core Java Volume I
Raise your words, not voice. It is rain that grows flowers, not thunder. Rumi

PDF Core Concepts in Pharmacology
When you do things from your soul, you feel a river moving in you, a joy. Rumi

[PDF] Sociology: A Down-To-Earth Approach Core Concepts
Every block of stone has a statue inside it and it is the task of the sculptor to discover it. Mich

[PDF] Download Sociology: A Down-To-Earth Approach Core Concepts
In every community, there is work to be done. In every nation, there are wounds to heal. In every heart,

Idea Transcript


Full text of "Core Java An Integrated Approach Covers Concepts, Programs And Interview" See other formats About the Author

Mr. R Nageswara Rao has been associated with teaching Computer Science since 1993. He has worked at various colleges as HOD (Dept. of Computers) and as a free-lance developer for some time for a couple of organizations. He has been teaching Java since 2000 1 and is currently associated with JNet Solv Solutions, Hyderabad, a prestigious training division, imparting specialized training in Java. Mr. R Nageswara Rao is teaching and interacting with more than 1000 new students every month, including software developers and foreign students. Since 1998,, Mr. Rao is associated with Computer Vignanam 1 , a widely circulated monthly magazine, published in Telugu. He has been on the editorial board of this magazine for the past six years, He published several articles, including articles on Virtual Reality, Mobile communications, Blue tooth technology and Global positioning systems. He also published hundreds of articles on C/C++ and Java.

Content at a Glance Core Java - An Integrated Approach Chapter 1 - All about Networks 1 Chapter 2 - Introduction to Java 7 Chapter 3 - First Step Towards Java Programming 15 Chapter 4 - Naming Conventions and Hyderabad". The same concatenation can be done by using *+' operator which is called 'String concatenation operator'. For example, we can use V as: sl+s2+s3. Here the three strings are joined by

Strings | 97

mt length (): This method returns the length or number of characters ' of a string. For example, sldengthQ gives the number of characters in the string sL J char sbiMtliM i) : This method, returns the character at the specified location i. Suppose we call this method as: sI.charAt(5], then it gives the 5 th character in the string si . I Int. compare To (String 5} : This method is useful to compare two strings and to know which string is bigger or smaller. This should be used as: sl.cornpareTo(s2). Now si and s2 are compared. If si and s2 strings are equal, then this method gives 0. If si is greater than s2, then it returns a positive number. If si is less than s2, then it returns a negative number, nen we arrange the strings in dictionary order, which ever string comes first is lesser than the iving that comes next. Thus "Box" is lesser than w Boy'\ This method is case sensitive. This means, B 3X r and "box" are not same for this method. lJ Int compareTolgnoreCase (String s) : This is same as < compareTo.() > method but this does not take the case of strings into consideration. This means "BOX" and "box" look same for this method. boolean equals (Spring s): This method returns true if two strings are same, otherwise false. This is case sensitive, We can use this method as: si ,equals(s2), boolean equalslgnoreCase (String s): This is same as preceding but it performs case insensitive comparison, nJ boolean startsWith {String 5} : This method returns true If a string is beginning with the sub string V, To call this method, we use the format si r starts With(s2). If si starts with s2 then, it returns true, otherwise false. This method is case sensitive, boolean ends With {String s) : This method tests the ending of a string. If a string ends with the sub string %\ then it returns true, otherwise false. This method is also case sensitive. - int indexOf (String s) : This method is called in the form, si . indexof ( s2 ) y and it returns an integer value. If si contains s2 as a sub string, then the first occurrence (position) of s2 in the string si will be returned by this method. For example, sl= "This is a book", s2 = "is", to mow the position of the substring s2 in s 1 r we write

This method searches for substring "is" in the main string "This is a book". Please observe that the rSu string is found at two positions, 2 [ld and 5 th . But this method returns first position only, so it returns 2. If the substring is not found in the main string then this method returns some negative alue. int' lastliidexOf (String 9} : This method is similar to the preceding method, but returns the last occurrence of the sub string V in the main string. If V is not found, then it returns negative value, string replace [char cl, char c2 ) : This method replaces all the occurrences of character cT by a new character *c2 J , For example, si - "Hello" and we are using as sI,replace(T, then the returned string will be "Hexxo". string substring {int. t>: This method is useful to extract sub string from a main string. It returns a new string consisting of all characters starting from the position V until the end of the string. For example, s] ,substring(5) returns characters starting from 5 h character till the end of s 1 . 3 String substring (int 11, int 12): This method returns a new string consisting of all characters starting from il till i2. The character at \2 is excluded. For example, sl.substring(5,10) returns the characters of si starting from 5 th to 9 th positions. P string toLowerCase 0 : This method converts all characters of the string into lower case, and returns that lower-cased string.

98 | Chapter 9

String toUpperCase (J : This method converts all characters into upper case, and returns tha upper- cased string. U String trirr ( ) : This method removes spaces from the beginning and ending of a string. If £ string is written as 41 Ravi Kiran the spaces before ^Ravi" and after are unnecessary and should be removed. This is achieved by trim(). Note that this method does not remove tin spaces in the middle of the string. For example, the space between "Ravi" and "Kiran" is no removed. void getChars (int. il f int. i2, c:har a'rr-^ ], int. :L3) : This method copies character from a string into a character array. The characters starring from position il to i2-l in th string are copied into the array c arr' to a location starting from i3. Counting of characters in th suing will start from 0 xh position. String [ ] split (delimiter ) ; This method is useful to break a string into pieces at place represented by the delimiter. The resultant pieces are returned into a String type arrai Suppose, the delimiter is a comma, then the string is cut into pieces wherever a comma ( n , ) i found. Let us have a look on program which will help us to understand strings. Program 1: Write a program which will help us to understand how to create strings and how to us some important methods of String class.

'e' , 'c' , , h 1 , '

//Demo of Siring class methods class stroemo { public static void rnain(String args[ ]} //create strings in 3 ways String si- "a Book on ^ava' 1 ; String s2= new Strino("X like it 11 ); char arr[] = { ' d 1 , ' r 1 T T e 1 , 'a' , *m ' , ' t 1 ' , 'P' , ' r' , "e" , "s" , 's'}; String s3= nev; stringCarr) ;; //display all the 3 strings System. out .print In (si); Sy stem. out .pri ntln(s2) ; sys tew. out .print In (s3) ; //find length of first string System. out . print! nC'Lengtn of sl= "+ sl.lengthO) ; //concatenate two strings system. out . pri ntlnC'sl and s2 joined= "+ si. concat (s2)) ; //concatenate three strings with + System. out, println(sl+ tc fro*n % s3); //test if string si starts with A boolean x~ si. startswi th("A Tr ) \ if(x) System. outs print! rrC'.sl starts with \'a\' m ); else system, out .printings! does not start with VA\ ,( '); //extract substring from s2, starting from 0 th char to 6 th string p = s2 . substri ng(0, 7) ; //extract substring from s3, starting from 0 vh char to 8 ch String q = s3 , substri ng(u , 9) ; //concatenate the strings p and q System . out . pri ntln(p+q) ; //convert si into uppercase and lowercase System. out. println( 'upper si- "+sl, touppercaseC) n) ; System . out . pri ntlnC'tower sl= Th +_sl.totowercaseQ j ;

Strings | 99

Output:

C;\> javac StrDemo, java c:\> iava 5trDemo A book on Java I like it Dreamtech Press Length of si- 14 si and s2 joined^ A book on lavai like it A book on Java from Dreamtech Press si starts with 'A 1 I like Dreamtech Upper Sl= A BOOK ON IAVA Lower si- a book on java

To understand how to convert a string into a character array, we can use getChars 0 method. If ;he string is L str J and the array is 'an:', then we can use this method, for example, as: str.getChars(7 l 21 I arr f 0); '_ \ : _ : " U means we are copying from 7 Tln character to 20 th character (21* L character is not copied) into 'arr'. These characters are copied starting from the position 0 onwards in the array. Now notice the Program 2. Program 2: Let us take a string and copy some of the characters of the string into a character array ~anr' using getChars ( ) method.

//Copying a string into an array class Strcpy public static void main(String args[ ]) string str - n hfello T this is a book on Java"; char arr[ ] = new char[2G];

//copy from str into arr starting from 7 rh character to 20 th character str.getcharsC7 T 21 1 arr 3 0) ; System. out * printl n(arr) ;

Output:

C:\> ^avac Strcpy, java c:\> ;java strcpy this is a book

Let us write another program to understand how to split a string into several pieces, For this purpose, split ( ) method is used. This method is used as:

s = str.spli tC'delimi ter") ;

Here, "delimiter 15 is a string that contains a character or group of characters which represent where to split the string. For example, a space as a delimiter splits the string wherever a space is found. A comma splits it at a comma, and a colon splits it at a colon in the string. After splitting is done, the pieces are stored into a String type array V. This can be seen in the Program 3.

100 I Chapter 9

Program 3: Write a program for splitting a string into pieces wherever a space is found.

//Splitting a string class strsplit public static void mainCstring args[ ]) //take a string str which is to broken string str = "Hello, this is a book on Java"; //declare a string type array s* to store pieces string s [ ] ;

. • i n

//split the string where a space is found in .str s - str .splitC" "5 :

//display the pieces from s for(int i-0; i ;

Output:

C:\> qavac strsplit, Java c:\> java strsplit Hello, this is a book on Java

String Comparison

The relational operators like >, >=, ]ava strcompare Not same

Strings | 101

When an object is created by JVM, it returns the memory address of the object as a hexadecimal lumber, which is called object reference. When a new object is created, a new reference number is Plotted to it. It means every object will have a unique reference. What is object reference? Object reference is a unique hexadecimal number representing the memory address of the object, ft is useful to access the members of the object . Inspite of the fact that both the strings si and s2 are same, we are getting wrong output in Program 4. Let us take the first statement:

String sl^ "Hello"; Then JVM executes the preceding statement, it creates an object on heap and stores "Hello" in it. A reference number, say 3e25a5 is allotted for this object, Similarly when the following statement is executed,

String s2= new StringC"Hello M );

JVM creates another object and hence allots another reference number, say 19S21f. So the ^zatement, if(sl==s2) will compare these reference numbers, i,e., 3e25a5 and 1982 If. Both are ut same and hence the output will be "Not same". Actually, we should compare the contents of the Smng objects, not their references. This is the reason == is not used to compare the strings. See the Figure 9.1.

s2

Figure 9. I Comparing the strings using == and equalsO To compare the contents of String objects, we should use 'equals (} 'method, as shown here:

if (si. equal s(s2)) system, out -pnntlnC'Both are same"); else system. out, pri ml n("Not same");

Now, we can get the output "Both are same" which is correct.

What is the difference between --and equalsQ while comparing strings? Which one is reliable? == operator compares the references of the string objects, ft does not compere the contents of the objects. equalsQ method compares the contents. White comparing the strings, equafsQ method should be used as it yields the correct result.

102 | Chapter 9

Program S: Let us re -write the earlier program with a slight change in creation of strings.

//String comparison using = class strcompare public static void main (St ring args[ ]) String sl= "Hello"; String s2= "Hello"; if(sl=s2} System. out. print! nC'eoth are same"); else System- out , printl n qavac strcompare. java C:\> java Strcompare Both are same

In Program 5, please notice how the strings are created as well as the output of the program also The first statement in the program is:

string si = "Hello"?

Here, JVM creates a String object and stores "Hello" in it. Observe that we are not using ne\ operator to create the string. We are using assignment operator (-) for . this purpose. So, afte creating the String object, JVM uses a separate block of memory which is called string constant poo and stores the object there. What is a string constant poof? String constant poof is a separate block of memory where the string objects are held by JVM, If a string object is created directly, using assignment operator as: String s1= "Hello" then it is stored in siting constant pooL

When the next statement, String s2 ™fiello"; is executed by the JVM, it searches in the strir constant pool to know whether the object with same content is already available there or not, Sino the same object is already available there (which is si), then JVM does not create another object, simply creates another reference variable {s2) to the same object, and copies the reference numb of si into s2. So, we have same value in si and s2. Hence, the output "Both are same". Please st Figure 9.2,

Strings | 103

String constant pooJ Figure 9.2 String comparison when the strings are created using assignment

Explain the difference between the following two statements: 1. String s f "Hello"; 2. String s = new String( (t Hel!o"); In the first statement, assignment operator is used to assign the string literal to the String variable s, In this case s JVM first of ail checks whether the same object is already available in the string constant poof, if it is available, then it creates another reference to it ff the same object is not availeble f then it creates another object with the content "Hello" and stores it into the string constant poof. In the second statement, new operator is used to create the string object. In this case, JVM always creates a new object without looking in the string constant poof

~ mutability of Strings

We can divide objects broadly as, mutable and immutable objects. Mutable objects are those objects hose contents can be modified. Immutable objects are those objects, once created can not be modified. And String class objects are immutable. Let us take a program to understand whether the 5: ring objects are immutable or not. Program 6: Write a program to test the immutability of strings.

//immutable or Mutable? class Test { public static void main(String args[]) Stri ng si - "+ 1T \nIam

a learner of Java.";

//atrach file to Filewriter FileWriter fw - new Fi lewri ter("text") :

//read character wise from string and write forCint i=0; i javac CreateFilel, Java C;\> java CreateFilel c:\> c:\> type text This is a book on lava. lam a learner of Java.

(n this program, we are taking a string from where the characters are read and written into a Fi I ©Writer, which is attached to a file named text. Here, we could also use Buf ferecLWriter along" with FileWriter to improve speed of execution as:

Bufferedwriter bw - new Bufferedwriter Cfw, 1024);

Reading a File using FileReacler FileReader is useful to read name="ei" val ue="UTF-8" /> javac DrawZ.java !:\>java Draw2

mm

Let us write a Java program to see how to create a polygon. Now, a polygon has several sides and create each side, we need x and y coordinates to connect by a straight line. All the x cewrdinar and y coordinates can be stored in two arrays as:

Int * = {40,200.40,100}? int y[] - ^40,40,200,200};

Graphics Programming WdngAW^ j 423

Now, .if a polygon-is drawn, it starts at (40 , f 4t$X and connects it with (2 00:* 40), from there a line connects it to (40> 200} and finally ends at (100,200). So here, totally 4 pairs of coordinates are there, and hence the polygon can be drawn- using:

Or, to get a filled polygon, we can use:

Program 8: Write a program to create a polygon that is filled with green color. This polygon must be created inside a rounded rectangle which is filled with red color.

//Drawing a smilie in a frame import j ava . awt . : - ? import java. awt .event.*; class DrawPoly extends Frame DrawFolyO

//close the frairte this. adfkLs'i ndowLi s ten'er fn ew wi ndowAdapte r Q public void vri n dowel asing Cwi rid owEvent e)

]

system, exit (Q) ;

public void paint (Graphics g)

i

//set red color g.setcolor (color. red) ; //display a filled rounded rectangle g . f i 11 RoundRect ( 30 1 30 r 2^0, 250 , 30 , 30) ; //set green color g^setColorCcolor^greerO \ //take x and y coordinates in arrays int *[] = {40 r 200, 40 ,100}? int y[] = {4.0,40,200,200}; //there are 4 pairs of x.y coordinates Int nuj» = 4j //create filled polygon connecting the coordinates g. fill Pol ygon-C*. y, nurn);

I

public static void main (string- argsn.) //create the frame orawPoly d = new arawPoTyO i //set the size and title 3 d, 5 et size (400, 400); d , -setTi tl e ("My Poly go fi " ) ;

424 | Chapter 27

1

Output:

3.Wy My&un

Finally, another Java program to depict a small figure is shown in Program 9. Program 9: Write a program to draw a home with moon at back ground.

//My Home import iava.awt,^ import java.awt. event . class noitie extends Fra?ne { HOtneQ {

tn i 5 . addwi n dowLi s ten e r { n ew wi n dowAdaptc r CD public void windowclosinqtwindowEvent eQ

}

Sysiem.ettitCQ);

public votd p&intCG rap hies g) //store x,y coordinates in x[l and vtl int x[l - £375,275,475}; int yf] = {125,200,2003-; int n = 3^ //no. of pairs //set gray background for frame thls.setfcackgrourtdCCGlor. gray) ;

//set yellow color -Tor rectangle o ; se'tcol-orf Col dr. yellow] j g . f i 1 1 Rect £300 „ 200, 150 , 100} J

house

//set blue color for another rectangle - dc

Graphics Programming using i 42&

y.setCol or (color. blue) ; g . f ill Rent O50 , 2 10 p 50 , £0) ; //draw 3 line -n line below the door g . d r awLi T>e(350 , 2 AO , 400 , ?80) ; /nnn'n^t dark gray for polygon - roof g.setCyTartcolbr.darkGray) i g.f-ill^ulygon(x,y r t0 I //set: cyan to! or for oval - f^n : g - setColorCCol or .cyan} ; g . f i 1 1 r}val (100 , 100, 60 1 60) ; //set green for arcs - grass" g , 5istCo1or(col or . green) ? o . f i 11 ArcC50 , 2 50 , 150 , 100 , 0 .ISO"? ; g . f i 1 1 Arc {} } public static void main (string args(j) //create frame Points obj new Points Qj //set black background color for frame obj r set H&ukqroundCCQlgr\ black) \ //set the size, and title for frame ob;j.set3izeCS0Ci 3 400) ; obj ,setT"rtleC' a random dots 11 ) ; //display the frame obj , s e|V1 si bl e ( t rue) i

Output:

C : \> q a vac Poi nt s . j ava C:\> java Points

Graphics Programming using AWT | 427

Displaying text in the frame To display some text or strings in the frame, we can take the help of drawstring () method of Graphics class, as:

Here, the string *Heilo" will be displayed starting from the coordinates (x, y). If we want to set some color for the text, we can use setColor ( ) method of Graphics class, as:

There are two ways to set a color in AWT. The first way is by directly mentioning the needed color name from Color class, as Color. red, Color. yellow, Color.. cyan, etc. All the standard colors are declared as constants in Color class, as shown in the Table 27:l:_

Table 27.1

Color.black

Color.bhae

Color.cyan

GoloTrpink

Col ox, red

Color, orange

Color, magenta

Color. darkGray

Color.gray

Color.lightGray

Color.green

Color.yellow

Color.white

The second way to mention any color is by combining the three primary colors: red, green, and blue while creating Color class object, as:

Here, r,g,b values can change from 0 to 255. 0 represents no color. 10 represents low intensity whereas 200 represents high intensity of color. Thus,

color c color c

» new ColQr(255jO,0) ; //red color = new Color(25 5 1 255, 2 55) ; //white color = n ew Col o r (0 ,0,0): // b 1 a c.k col o r

428 jchapter,2Z

This Color class object c should be then passed to setColori) method to set the color. To set some font to the text, we can us# seiipSn;t;{ ) mftriCKtoS^agfcics class, as:

SetRlf'T \ FQ-rTT.

This method takes Font class object, which can be created as:

Here, "Sans Serif" represents the foat name, Font. BOLD represents the font style and represents the font size in pixels. There are totally 3 styles that we can use:

FOtlt. SOLD Font .ITALIC Font. PL AIM

We can also combine any two styles, for example, to use bold and italic, we can write Font .BOLD Font. ITALIC' Program 11: Write a program to display some text in the frame using drawstring (1 method. //FPfcrtie with background color and message import jgva-aiwt-*; import iava.awt . eVEllt. class Message extends Fraiai^ -. Messaged //close the frame when close button clicked addwi ndowLi stener(new ivi ndo^AdapteFQ £ public void windo^ClosingCwTtidowEvent weD system » exit (Q);

}//end of constructor

public void paintfGrapoics g) ' //set background color for frame thi s . s et Bat kg r un d tn ew Col o r C10Q , 2.0 , 20) ) ; //set font for the text Font f = new FcmtC'Arial " , Font .BOLD-i-Font. italic, BO) ; g.setFontCf) ; //set foreground color g-rSettolorCColor. green) \ //display the message g. drawstring ("Hallo, Mow are U? 100 a 100>?

public static void mainCString argsf]) Message TTi = new Message O; rn. sets IzretlOO, 300); nnusetTTtleC'Thls is my teat"); m,setvi sibleCtrue) ;

Graphics Programming using AWT J 429

Output:

Knowing the Available Fonts

It is possible to know which fonts are available in our system. When we know the available fonts, we can use any of the font names to create Font class object. First of all, we should get the local graphics environment, as: Graphic sEnvironment ge = GraphicsEnvironment.getLQcalGraphicsEnvironjrtent () ; Now, this ge contains the available font names which can be retrieved as:

Program 12: Write a program to know which fonts are. available irr a local system.

//knowing the available foots import java.awt. *; class Fonts I public static void mainfstring args[]) //get the local graphic 5 environment information into //GraphicsEnvi ronment object GraphicsEnvi ronment ge - Grapbi csEnvi ronment . getLocal Graphi csEnvi ronmentO //Fron! ge, get available font family names into fonts [ J String fonts [] n ge , get A vail able Font FannilyNamesO ; "System - , out. print "In ("A vallate fonts on this system: " ) ; //retreive one by one the font names From fonts [] and display foKint i=0; i java Fonts Available fonts on this system: Agency fe .Arial Arial Black Arlal Narrow' Arial Rounded MT sold AS-TTDurga Astro Elackadder rrc EM-TTDurgii Bodont MT Bodorci mt Black potibni mt ton denied Book Anl;iqua bookman Gild style Bookshelf Symbol ^ Bradley Har«d itc calisto mt Castellar Ceniuiry Gothic Co fi~ u ry sc hoc 1 bo o k. comic Sans MS Courier New

Displaying Images in the Frame

We can display images like .gif and .Jpg^ files in the frame. Fx>r this purpose, we should these steps: Load the image into Image cia$$ ; object using get Image ( ) method of Toolkit class.

-

-V_ : . image img ^ Tool ki t , getDef au I tTool ki t Q , gatlmac?^ f/' diamonds . tji f ") ; | Here, Xaol.kit.getue^auItTooIlcit () method creates a default Toolkit class object. Using object^ we call get Image O method and this method loads the image diamonds . gif into img obyfl But, loading the image into irn^ will take some time. JVM uses a separate thread to load > image into img and continues with the rest of _ the program. _S6, : there is a posBibiliqj completing the program execution before the image is completely loaded into img. In this a blank frame without any image will be displayed. To avoid this, we should make JVM \ the image is completely loaded into img object. For tmVpurpose, ive meed MediaTr ackesg i Add the image to MediaTr acker class and allot an identification number to it st MediaTrstcker track = rre*< ^ed-f ?, i n&c ^Ktrris}; " % r~~ • - . Track.adrilir»a§eCimg p G} V f/(±-is the i d ftuircber of image

Now* MediaTr aeket keeps JVM waiting till the image is loaded ;LwaEifeFoi:ID 0 method. "

This is

t FtirllHO) ;

This means wait till the image with the id number 0 is loaded into img object. Similarly several images are there, we can use waitForlD (1) , wattEorID~i2)> etb.,

cs Programming uste

i

Once the _ image is loaded and available m img, then we^janV display : the^ image using drawlma jay at linages, java c:\>java Images

Component Class Methods

A component is a graphical representation of an object on the screen. For example, push but radio buttons, menus, etc. are components. Even frame is also a component. There is Compoc class available in java.awt package which contains the following .methods which are applicable ( any component. * Font; get Font { ) : This method returns the font of the component, a void set Font (Font-r f ) : This method sets a particular font f for the text of the component, Color get Foreground ( ) : This method gives the foreground color of the component. void setForeground (Color c) : This method sets a foreground color c to the component Color getBackground O : Gets the background color of the component. void. getBackground (Color c) : Sets the background color c for the component, String get Name () : Returns the name of the component. -void setName< String name) : Sets a new name for the component.

Graphics Programmingusmg AW1S i 435

int getHeiglit () ; Returns the height of the component in pixels as an integer. int getWidth ( ) : Returns the width of the component in pixels as an integer. Dimension getSize( ) : Returns the size of the component as an object of Dimension class. Dimenison .width and Dimenis ion. height will provide the width and height of the component. int getx< ) ; Returns tlic tmtrcat x coordinate of the component's origin. int getY Returns the current y coordinate of the component's origin. Point getLoeationJO : Gets the location of the component in the form of a point specifying the component's top-left corner. void -set.Location^int x, int y) : Moves the component to a new location specified by (x,y). void set Size (int widths int height) : Resizes the component so that it has riew widtrr and height as passed to setSize C) method. void setVisible {boolean b) : Shows or hides the component depending on the value of parameter b.- f set Visible^ true) will display the component and setVisible (fals$) hides the component. void setEnab led (Boolean b) : Enables or disables the component, depending on the^value of the parameter b. setEnabled (true> will enable the component to function and setEnabled (false) will disable it". void setBounds (int x, int y, int w, int h) : This method allots a rectangular area starting at (x,y) coordinates ^nd with width w and height h+ The component is resized to this area before its display. This method is useful to specify the location of the component in the frame. After creating a component, we should add the component to the frame. For this purpose, add (1 method is used.

Similarly, to remove a component from the frame, we can use remove ( ) method, as:

Push Buttons Button class is useful to create Push buttons. A Push button is useful to perform a particular action. To create a push button with a label, we can create an object to Button class, as:

To get the label of the button, use-ge tLabel ( y :

To set the label of the button:

434 I Chapter 27

Here, the xx label" is set to the button b. When, there are several buttons, naturally the programmer should know which button J clicked by the user. For this purpose, getActionCommandO method of ActionEvent useful.

Here, s represents the label of the button clicked by the user. To know the source object which has been clicked by -the user, we can use, getSou method of ActionEvent class, as:

Object ob.i = a,e,get5o£jrceO ;

Remember that only displaying the push buttons will not perform any actions. This means cannot handle any events. To handle the events, we should use event delegation model. Ao to this model, an appropriate listener should be added to the push button. When the bui clicked, the event is passed to the listener and the listener calls a method which handles the With the push buttons, ActionListener is a suitable listener. To handle ActionListener to button, we can use addxxxListener () method, as:

b . addAc t i o lU i siene r (Act i on i_ i s te he r oh j ) ;

Similarly, to remove action listener from the button, we can use reraovexxxListener ( ) metho

5 r (Act i on Li sten e r

In the two methods, addActionListener (') and removeActionListener (-> , we are. ActionListener object. Since ActionListener is an interface, we cannot directly create an olsp to it, we should pass object of implementation class of the interface in this case. Let us write a program to create push buttons and also add some actions to the buttons- 1 following steps can be followed: First, set a layout manager using setLayout () method. In our program, we do not want to any layout, hence we can pass null to setLayout ( ) as:

s. set Layout [null);

Since our class Mybuttons extends Frame class, this represents Mybuttons % class object or Fr= class. Then create the push buttons by creating objects to Button class. Since, we are not using any layout manager, we should specify where to attach the bu the frame using sets ounds < ) method. Then add the buttons to the frame using add_(). method. Add ActionListener to the buttons so that when we click on any button, the listener handle the event by calling act ionPer formed t ) method. Program 14: Write a program that helps in creating 3 push buttons bearing the names of 3 cthN When a button is clicked, that particular color is set as background color in the frame.

.//Push buttons import javavajvty-; import java- awt. event .*? class Mybuttons extends Frame orients Act1oriuf»anfer

Graphics Program^^

Button bl n b2 1 b3; MybuttonsQ //do not set any layout thi s t sot Lay out Cnu 1 O ; //create 3 push buttons bl * nevu Button r'YeTlpw" j ; b2 = new ButTOTtC'Bluc"): Til =-.new euttOJtC n PinJi"J; ffsgt the locations of buttons in tfe Frartie bl , set Bon nd s C 100 , 10 fr, 70 ; 40} i b2 , s e t B on n d s ( 100 i 160 . 70 , 40} ; b3 . set: Bounds (100, $S , 70 , 403 f //add the buttons to, the frame thfeiaddtbi}} this-addCbZJ ; this.add(bT] f //add action listener to the burins bl,addAct'iOfH istenerCthi $) ; add Act. Iutili stengn (this} ; add Action l.i sterrerCthi s) ; //close the frame V addw I ndtfwL i stener Cnew wi ndowAuapte r O pub-lic void -AindoivClosingCwf ndoWEvent weY -% say fflfffiP system. exit (in ; }//end of constructor

/ tins public

method is called when a button is clicked void action Performed C Ac tionEvent //know the label of the button clicked by user String str= ae.^etActicniCommaridO ; //change the frame's background color depending on the button "clicked i f Cstr - equal s G'vel 1 ow'")J t-hi s , set&acktjrouhdtcol or. yel low] t i f Cstr. eQUH.lsC n ^l^e u )D th i set &&cfcg round CColor;b~Uie>; i f ' ( s t r . fiq u si s t ri Pi AOS th is . s e taa ck ground (Cbl or- , p i nk3 i

|ubl ic

static void ma in (String argsfD. . //create the frame Mybuttons - mb = new wybuttonsQ ; mb ; set si zeC40Q ,'40Gj ; mb . setf i tl a C "My but ton£ n >' ; nib .set visible (true}.; ;

436 n Chapter 27

Output:

C:\> Javac Mybuttor.s 4 a c;\> ]|ava Wyby"tt0ns

In the preceding program, observe the following statement:

tft i 5 . s etL ay o u t ( null):

Here, this represents current class object. Since the setEackground(Color .pi nk) ;

static vend 4Ttairn;si:r iny argsEJD //cr^e tfje fratne Wybuttons nib = new aybutionsQ; tnb.setTitleC'My buttons"}; rob.setVi si hie (true} ;

Output:

Listeners and Listener Methods For working with push buttons, Action-Listener is more suitable. Similarly, for other component! other listeners are also available. All listeners are available in jacva »dE#t *event package. Table 2lfl

summarizes the components r suitable listeners for the component, and the methods in the lisl interface to be implemented when using that listener

;teaJ

Check Boxes

A check box is a square shaped box which displays an option to the user. The user can select one or more options from a group of check boxes. Let us see how to work with check boxes. To create a check box, we can create an object to Checkbox class, as:

Checkbox cb = new ttieckboxO; Checkbox cb = new Checkbox C L "I abel") : //with «. label Checkbox cb =-n new checkhoxC'labEl", state'Ju// if state is true, then the che //box appears as if it is selected by default, else not selected.

//create a check box without any label new Checkbox C L label") ;

To get the state of a check box:

:t . netr ratei.

If the check box is selected, this method returns true, else false. To set the state of a check box:

The check box cb will now appear as if it is selected. To get the label of a check box:

If cb is the check box object, then getLabel { ) will give its label. void setLabel (String label) This method sets a new label to the check box. To get the selected check box label into an array we can use getSelectedObjects () method, This method returns an array of size 1 only.

Here, x [ 0 ] stores the label of the check box selected by the user, if selected. Other wise, it sto null.

For example, there are 2 check boxes as:

checkbox cl ± new checkbox C "one") ; Checkbox c2 = ne*' checkbox C"T^io ,r ) ; x = cl. get Select edObjectsO ; //k is an array of Object type ifCx[0j == null) sy stent, out,r>rintlri£ ,J The check box is not s elected" ' rintlnC

else System. out. pH

t"("»T"ec%«l check box label is : *I0D;

Program 16: Write a program to create 3 check boxes to display Bold, Italic, and Underline to the user.

//Checkbox demo import ;jav2.awt.*; 1 mpo rt ] ava . awt . even t - * ; class My checkbox extends Frame implements itepiiistener //vars String msg-"";

Graphics Projyai^

checkbox cl. c2 , c3; My checkbox O

//set Flow layout manager set Layout (new Mows, ay out Q}* //display 3 checkboxes tl m new Checkbox ("Bold" f true>; €1 = new Checkbox ( ,k italic ") ; c3 = new Checkbox( ,r UTider"Hne ri ;) ;

//add the check boxes to the frame add{cl); add; add[c3); //add itefli listener to the check boxes cl , addi t em Li s ten* r ( th i ; c2.additertiListenerCthi sj ; c3,additemL istenerCthi ; //close the frame ad d wi ndowL i s t en e r ( new wi ndo wAcf ap t e r {) pub 1 i c voi d wi n dowel os i n g (wi n dowEveri t weO system. ex i tCQ}; } //end or constructor //this method is called the user clicks on a check bo* public void i tettStateChaogedCltemilvent ie} repaintO; //call paint O method

//display current state of checkboxes public void painttGraphics g) g . drawSt ring ("-Cur rent state r ' ™ r 10 w .100) ; msg = "Bold: % cl.getstateO ; g . d rawSt ri og (ms g , 10 p 120 j ; msg n "italic: +cz . getsiate Q ; g . d rawst ri ng (ms g , 10, 140) ; msg = "underline: "+c 3, cetstnteO; n d rawst rf ricj tmsuj, 10 1 160} ; public static void main (string args[])

ni

//create the frame My checkbox mc = : riew Mythecfcbox O ; mcsetTitleC'My checkbox"); mjava Myt heck box

442 | tiha^fer ?7

£3 My checks*

Current state: Bold: true italic: false Underline: false

In this program, when the user clicks on any . check box, the event is handled by ItemLisl:€ attached to the check boxes and hence the code of itemStateCtiangedcbg, true.) ; n - new checkbox ("no 11 3 cbo, false); //add the radio buttons to frame add(y); add(n); //add item listener to the radio buttons y . add! t emLi s t e ne r fthi 5 } ; h . add 1 1 em Li s t e nc- r ( t h 1 5 1 j //close the f- rattle addwi ndowLi sten^r Cruw Vfl ndowAdapterO public void wTiidortCi.os^neWndowEvent we) System. ex 1t£0>* J) I =' } //end of" constructor //this method Is called when a radio button is clicked public void itemstatethangedCiteinEvent 1e) repaintO; //call paintQ //display the selected radio label public void paint CGraphics g) msg^ "current selection: *j msq+~ cbg. getselectedcheckboxQ .get label O; g r d rawst ft ng Ottsg y 10 , 100) ; public static void main (string args[]} //create frame My radio mr =. new MyradioO \ sir. setTi t'Se{"My radio buttons''^ ; m r , sets i (400 1 AW) J m r, set vi 5 i bl e Ct r ue} ;

Output:

444 | Chapt

*;r 27

My radio buttons

Current selection: Yes

carries! C No

TextField

A TextField represents a long rectangular box where the user can type a single line of text. We i also display a line of text in the text field- also. To create a TextField:

i wl

ox t Fie Id tf v new TextFieidQ; // a blank text field is created TextField tf = new T'extField(2!>) ; //25 characters width of text field TextField tf = new TextField {"default text",, 253 * //default text, ts displayed when // th e t ext f i e 1 d is displ ayerJ .

To retrieve the text from a TextField:

iS&tS^jSr S $;f\ de^a&tTl i

To set the text to a TextField:

To hide the text being typed into the TextField by a character char:

Now, the original characters typed in the text field are not displayed. In their place, the char displayed. This is useful to hide important text like credit card numbers, passwords, etc.

TextArea

A TextArea is similar to a text field, but it can accommodate several lines of text. For example, if 1 user wants to type his address which contains several lines, he can use a text area. To create a TextArea:

Graphics Programming using AWT j 445

area with some rows ana

Text Area ta - nev; T'earAreaCrwvs ,cols) ; //t //columns TextArea ta ^ new TextAreaC'string") //text area with predefined string

To retrieve the text from a TextArea:

To set the text to a TextArea:

To append the given text to the text area's current text:

To insert the specified text at the specified position in this text area:

Label

A Label is a constant text that is generally displayed along with a TextField or TextArea. To create a label:

Label 1 =* new Label O ; //create an empty label LabeT 1 == new Label ("text" , alignment constants Here, the alignraentconstani may De one of the foil owing: Label, right, Label. left, Label. center

When the label is displayed, there would be some rectangular area allotted for the label. In this area, the label is aligned towards right, left, or center as per the alignment constant. Program 18: Write a program to create two labels and two text fields for entering name and passwords. The password typed by the user in the text field is hidden.

//TextFields LYith a Labels i mpo rt j a va , awt , u \ import java.awt .e^ent, *; class MyText extends Frame implements //vars TextField name j pass;

MyTextQ

//set layout to flow lavcut setLayout(new F-lowLayoutQ) ; //create 2 label s Label n new Label ("Name: \ Label. LEFT); Label p = new Label [' Fas s word; " T Label. L£FT3 ; /.'create text fields for name and password name » new Text Field (20) ; pass - new Text Field (2Qj; //hidft the password bv 'n

446 | Chapter 27

pass . settdioCJiarO r 3 i //use background , foreground colors and rant for name textfielcf name . setEacfc ground C.CoTor .yel 1 aw) ; najrve , s et Fo re g ro und (col o r , red } ; Font f » new" Fan t ( % r i a I " , Fo nt . F lain .25) * name. set Font (.t) ; //adc; the labels and tax t fields to frame addO} ; add trta/iie) \ add (..pi ; , add (pass. - ) ;

//add action listener to text fields name . add Act iotiLi stener Cthi ; pais , addActtotiLi steuertthi s) ;

//close the frame addwi n do wl i s t en e r ( new wi n tfowAd a p t e r { ) public void windowclosingCwiTidowEvejit we)

5ysts.ni. exit £0} ;

i »i 1 >//encf of constructor //this method "is executed when enter Is clicked //display the t«xt entered into the text fields public void act iunPetfornied^ct^oriii vent ae'J C //create Graphics class object graphics g • this.getGraphicsO;

1

g.drawstringC'Name: H +name.getTexi:0 * 10,200); g , d r a w5 t r i ng C Pass wo rd : " +pa ss . geiTex t Q , 10 , 240) ;

public static void mainCstHng args["J) //create the frame wyrext mt - new MyTextQ: Tnt.setTitleC'My text field 11 "); nrt.setsi zeC*QD,4 00) ; ^t-setVisit-TeCtrue) ;

Output:

C:\> javac MyText.jaVa java MyText

Graphics Programming using AWT j 447

ti My text field

SEE

Name: [Nageswara Rao

.Pass wont j

NameiNafleswara f?aa Passworttnag

Choice Class Choice class is useful to display a choice menu. It is a pop-up list of items and the user can select only one item from the available items. To create a Choice menu: Choice ch = new ChoiceO; //create empty choice menu Once a choice menu is created, we should add items to it using add ( ) method, as:

cb. add ("item") ;

To know the name of the item selected from the Choice menu:

Strir = . - :edTtero0 : :

Index of items in the Choice menu starts from 0 onwards. To know the index of the currently selected item:

i nt i *h ch , get Sel e ctedl n d ex Q ; This method returns -1 if nothing is selecte-d.

To get the item string, given the item index number,

string item = ch.g^tltMCin.t Tnctex} 3

To know the number of items in the Choice menu,

To remove an item from the choice menu at a specified position,

To remove an item from the choice menu,

c h . r emo ve (s t r 1 rig 1 tejft)

To remove all items from the choice menu,

448| Chapter 27

ch.rpii r.v^A I ! Q ;

Program 19: Write a program to create a choice menu with names of some languages from w| the user has to select any one item. The selected item must also be displayed in the frame.

//choice box demo iraport .java.avct . v i i rnpo rt java , awt . event . * ; 1 a.s s Myth oice. e a t * n ds f rajae i mp> 1 e i te^i t s * l 1 ftrtl String liisg* Cooue. qftj //set f i c w layout to fran^e - setLayo.iJt £ new Fl. okiLay a ut CO [ //create an empty choice menu ch = new choiceO; //add State items to choice- menu n ^.addC'Enflliih^; ^Ji>Hdjar*M lndin ; d>.addC r $ansGrii''}; //add the choi ce menu to frame atidCch) ; //j?.dd item listener Co choice rienu ch^adiflteii'.Lis^aneKthis} ; //ciostf the Frame addwi .jrdowLi s t ene r (dgw Adapt e r g ) public void vnndowCltisingf^indowEvent We}

//tfns lifted is called toh^ft any it en

^nblifj void ItenStrrreChaiigedCftefrtEvent ie} .//call paintO method - - repaintO: } //'display selected item from, tht; choice menu public void pai nt(G"aphics g) g k drator5tririg£ i, 5e1ected language! 11 , 10,100} ; msg = r.h.-jetSfiVectedXtfimO ? g'* n r.awS^n ng (msg $ 10 . ±2 01 j

pufeli* static void mai n Cstrino arg^R} //create a frame

Graphics Programming using AWT I 449

Selected language: Telugu

List Class This class is useful to create a list box which is similar to choice menu. A list box presents the user with a scrolling list of text items. The user can select one or more items from the list box. To create a list box, we can create an object to List class:

This statement creates a list box. The user can select only one item from the available items.

This statement creates a list box which displays initially 3 rows. The rest of the rows can be seen by clicking on the scroll button.

This list box initially displays 3 items. The next parameter true represents that the user can select more than one item from the available items. If it is false, then the user can select only one item. To add items to the list box, we can use add ( ) method, as:

To get all the selected items from the list box:

er 27

To get a single selected item from the list box:

To get the selected items' position numbers:

To get a single selected item position number:

mm^ ztiffla »

To get the number of visible lines (items) in this list:

To get all the items available in the list box:

To get the item name when the position number (index) is known:

-get:

To know how many number of items are there in the list box:

To remove an item at a specified position from the list:

To remove an item whose name is given:

To remove all items from the list:

1st, remove All [> ;

Program 20: Write a program to create a list box with names of some languages from where user can select one or more items.

//List box demo import java.awt.*; i mpo rt j ava . awt . event . fr ; class Mylist extends Frame implements itemLi stener int[] msg^ List 1st;

{

//set flow layout manager

Graphics Programming using AWT | 451

s et Lay o u t (. new Fl owl ay out Q ) ;

//create an empty list box that displays 4 itetns initially ' //ancl multiple selection is also enabled 1st = new Li stC^triae) : //add iteftis to the list to* 1st. add C'tinyl ishT") ; 1st. add ("Mi nd1 ") ; Tyt.addrreluqo"); Tst^ddC'sanskrit'^^ 1st. add ("French"); //'add the list box to frame addClst^ //add i :em listener to the list bo* 1 st . addltemLi stener (thi s) ; //frame closing addwi nd owl_i s t eh e r (new wi ndowAd apte r Q public void ivindo^cla&ingCwiiid owe vent we) * System .exit CO) ; H; } _.//-ertd of constructor ptfbl 1 c vol d i teiflStateChangedCit emEvent i e.) n[ //call the paint O method : repaint (); public void paint (^Graphics g> g- drawstring ("selected languages: ",100,200); //get the selected items position numbers into ntsg[] msg * 1st .getselectedindexesO ; //know each selected i tent's name and display for(int i=0; i public vol d w i n kqv.C losing {Wi ndovt Even ivs}

System -ftiti

V

public void adjust^entvai ueCbangedC-Ad jus idientEvew: ae.) repa inr.Q ; //call patntQ pub 1 -if: -void »ai ntCsra'phfcs a} ( //display the position of scrollbar g,draw5tri ngC" scrollbar position: % 20,15.0); msg +4 sl.getyalueO 5 g . d rjiwS t ri ng (m s a Z 0 , ISO") ; } ubl.ic static void main (string arcs[]) //create the frame Myscroll tits = new Myst rail O; ms,&etri tTeC"«y scroll bar"); m5,setSizeC4CHM0O"j ;

454 | Chapter 2

Output:

C:\> javac My scroll . java C:\> java Myscroll

My scroll bar

Knowing the Keys on Keyboard

To know which key is pressed on the keyboard, we can take the help of KeyListener interface. ] interface has the following methods: public void keyPressed (KeyEvent ke) : This method is called when a key on the is pressed. public void JceyTyped (KeyEvent ke j : This method is called when a key on the ke; typed. This method is applicable to the keys, which can be displayed and generally does denote the special keys like function keys, control keys, shift keys, etc. public void keyReleased (KeyEvent ke) : This method is called when a key on the ] is released. Program 22: Write a program to trap the key code and key name typed by the user on the ] and display them in a text area.

//catching which key 3 s pressed i flipa rt q ava . av-t . - ; i snport z ^ ^ a . awt . even t , - ; class Keys extends Frame implements KeyListener { //vars String msg="" ;

//set flow layout s et Lay out C n ew F 1 owLayout'O ) \

Graphics Programming usingAWT 1 455

create a text area to display the key cade ta= new TextArea(5 ? 25) ; //set some font and foreground color' to text area. Font f = new Font ("sanserif " t Font. BOLD, 25'); ta.setFont(0 ; ta.se tFomgroun^Color . red) ; //add text area to frame add(taj ; + //add key listener to 1;e*T area ta.addKeyLisrenerCthisD ; //close the frsme addiVindowLis^ener(new wi ndowAdapterO public void winctowclos-f ng.(windoivEvent we J System. exi t(G) ; }>; void key P re ssedtKey Event ke) //get the code of the key pressed Int keycc>de= ke.getKeyciodeO ; msg += "\nKey code: "Vkeytodej //get the name of the key from the code String k ey n anie= ke , get Key Tex t £ key code ) ^ msg += "\nKey pressed: keyname; //display the key code and key name in text area ta.setTexr(fiisg) : msg='*;

pub'li c 1 1 pub I i c I

void keyT/ped (Key E vent k*0 void keyRe leased (Key Event ke) //get; the key code released int keycode^ ke.getKeyr.ode Q ! msg H, \nKey code: Vkeycode; //get the key name from the tude S£.r4ftg keyname^ ke.getKeyTexirtkeycode) ; msg += 1fc \nKey Released: + keyname; //df splay key code and key name in text -area ta r setText(msg) ; msg="" ;

public {

static void main (St ring arg*[]) //create the frame Keys ks = new KeysO; ks^et fitleC'catch the key 1 '}; k a, set Size (400,400)! ks r setvi si bl e(true) ;

456 [ chapter 27

Output:

c:\> iavac Kays, java C:\? Java Ksys

Working with Several Frames

In software development, it is necessary to create several frames to display some screens to the user and to accept user input. Similarly, there may be several other screens which display the results to the user. So, we should know how to generate one frame from the other one. Suppose, we create a frame with the name 'Frame 1*. When a button like *Next' is clicked on Frame 1 then it should display *Frame2'. There is another button *Back* in Frame2, which when clicked takes us back to the first frame. To create a new frame < Frame2\ we sliould write the following code in Frame 1 class: Fraftel f2 = new Frame**)'-; To make Frame2 terminate from memory, we can use dispose () method. To do this, write the following code in Frame 2 class:

Program 23: Write a program to create a . frame 'Frame l ' with Next and Close buttons //This Is frame! impart java.awt.*,- import i a vb, . awt , e ven I - * ; class Frame 1 extends Frame litiplemeiits Actio.nL't&L ftrtfep //vsrs Button bl r bZ: Frairrel() sett,ayoutCriLi1"0 ; //create two buttons h X- n Liu s; ton C " n ext "'} ; b2= hew Button ost5 r " 3 //net tbe "ptjf.atiun of buttons bl.se tB&u nd s O 00 , 100 ; 70 ;4QiY. b2 . setfluunste C20O . 100 , 70 , 40) ;

//acid them to -frame

Graphics Programming using AWT [ 457

//add action listener to button b.L . addActi on Li stener ( thi s.) ; b2_ add Acti anl_i stener (tH s} ;

jjtiblfc

void acti onP^r forced CAcUonFvent ae} //if N'ext button is clicked, display Framed if Oe-getsourceO == bl) //create Frame2 object and display Frame2 jP2 = new Frame2Q; f2.set£ize£4G0,4GQ); . f Z, . s e tvi sibleCtru e) :

} public

else

//if close button is clicked, close application systeni.evi t(G) ;

static void main(Strfng apgsgp //create Frauiel Frarrei fl n new Frame! O : fl.setsize(500 t 500) : fl.setTrtleC First frame' 1 ); f I , s etvi si bl e Ctr ue ). ;

DO NOT COMPILE THIS CODE TILL FRAME2JAVA IS COMPILED.

Here, in this program when the user clicks the Next button, Frame2 is displayed. When the user clicks the Close button, the application is closed. Program 24: Write a program to create Frame2 with Back button, such that when the user clicks Back button, Frame2 is closed and we see the Frame 1 only.

import ijava.awt i mpo rt } ava . awt . even t . * JS class Frame 2 extends Frame //create a button Button b;

Framed O {

//set layout to flow layout setLay o ut ( n ew Fl owLayou t Q ) ; //create the button b= new eutton-CBack' 1 ) ; //add it to frame add 00; .//add action listener to button ft . addAc t i o n Li s ten e r{ t hi s) ;

458 I Chapter 27

public void act i on Perfonnedf Act ion Event ae) I //remove this frame front memory ^ this-dlspas&Oj

Output:

C:\> j a vac Frame 2 > j a va C:\> ^ava Frarnel. java C:\> lava Framel

Is it possible to send some CheckRadioO I // create the content pane container c getcontentPanef } ; //set flow layout no content pane c . set Lay out( n ew F I owLayou t Q ) ; //create 3 te*t area mth 10 rows aM 20 chars per row ta = new J re KTArea 0.0,2011 ; //create two check boxes cbl - new JChetk&oxC'Java" . true); cb2 = new 3Clieckfeox C n 32EC ,, >;

//create two radio buttons rbl = ne 1 * ^ ^^^^ ^^o(i^]tto^( ^l Ma1e ,, , true} ; rb2 = new ; i oGutton C H Femal r "j ; //create a button group and add the radio buttons to -it sacj * nw Butionr : roupO : ba.add{rbl); bg.addtrbZ); //add the checkboxes, radio buttons, texta>-ea to the cbrrtaifier c-adtfCcbl); c.add(cfazy s c. add (rbl) ; c. add(rb2) ; c , add CtaO ; //add action listeners. We need not add listener to teXt'arfca . //since the user clicks on the checkboxes or radio buttons pnl^ cb 1 . a dd Act i on Li s ten e r ( t hi s ) ; cbZ . add Act i onci sten ^r^thi s~) ; rbl , add Act i on Li. s tene r { t hi s ) : rb 2 . addAct i on Li s ten e r ( thi s j ; //close the frame upon clicking setoefaul tcl aseoper^ti &n(.i Frame , exit_QNL_cl05E1 !

public void actionFerformedC'ActionEvertt ae}

482 1 Chapter 28

//know which components are selected by user i f ( cb I . aetModel ( > . i sse 1 ec ted Q) ms g " \ n J a va " ; if nr J rou'pO : bg.add(rU ; bo L add(rz} ; bg.add(r3); //set r.he lixacion of components in content pane b . set Bounds £ 100 3 5G a 75, 40) ; . cb.setEoujidsCICK:', jl00,.10Q ,40) ; £, . s e tsounds ("100 ii SO ,3,00*40.^ pi .seiBGUnds CSQ , 250 , 100 , 303:3 n r 2 . setBCHmdsD 50 . 250 , 100 , W) \ r3 1 setSaunds £2 SO , 2?Q , 100, 30) ; //add the components to content pane

484 | Chapter 28

c.addC'cb] ; C-add{rj ; • caddCrt) ; //add item listeners to radio buttons rl . adtfrternLi stener ( tM s) ; r2,addttern[_1 stenerCthis) ; r3 . add I ternM stesie r tthi s) j //close the frame this. setDef aultcloseOperationC^Frame .EKlT.OS.ClLOSEj- ;

public t

//know which r&ttfo button is selected ami thy look &ftd // fee".

accordingly change

-ff {rl.getModel O . isSe'lectedO) U iMan u g*r . s at look An d Fee 1 r b i a va x . stfri rig , p 1 a f a met a 1 . Metal LookAiwfFe^^'J ; i*Ftr2 « gettoodel Q . i iS^l ect.ed Q ) «j iMan age t\ 5 e la.ookAnd Feel C 71 torn , h j n . j ays . sivi riy , p 1 a f\ mot t f . t 'i f L 0 u kAn d Feel ' 1 3 1 if C^sretModel 0 -i^SelecvedOj itf-Majg agkr . settDokA^df-eef ("conhsunrjaVa, ng T pi a f , windows, ndowsLOokAndFeel "j ; //change the look and feel in the content pane Zv.i nguti 1 i ti es , updateCoFTiponen£7reo!lJT (r.) ; } catch {Exception e>{} .

public, staiic vend rnaintstring- args[]} //create the fr arise n l, odk F&e) If = new LookFeelO; 1fy; MouseEverrtsQ //create content pane c = getContentPaneO ; c.settayout(new FlowLaycwtO) ; //create a text area and set some font to it ta = new DTaxtAreaC "Click the mouse or move it" , 5,20); ta.setFontCnew Font£ M Ar1aT" , Font. bold, 30)); //add text area to content pane //add mause 11 stener r mouse motion listener to text area tJ . addMousefc. i stener £thi s} ; ta^ddMous^MoflonLi 5tener(this) ;

public vo i d mou seel i c ked CMou seE nt me)

Graphics Programming usMf Swing \Ml

//know which button of mouse is clicked irii i = me. get But ton O; if (1=1) str += 'clicks Button: Leri"- str + = "clicked Button: Middle"; str n+= "clicked fluttan: Right 11 ; thls.displayQ; public void ^oirseEnteredCHouseEvprn; mO str +m "Mouse entered"; ^ this.displayQ ; public vo-rd moi*seE* i ted (Mous^t vent me} 5tr += "Mouse Edited" : this., display Qi

public void mousepressedCMousGEvent me}

x = me^geixO i y = me.qetYQ ; str Mouse Pressed at: in is. display Q;

"+x- ,1 \t H 4y;

public void iwouseReleasedCKioiiseEvent me) y = in^.qetYC;; str += Mouse Released at: ,1 +*-f- , "Vt v +v r this.displayQ; n'n

public void iftouseuraggedfrio use Event V = me.getYO; str *» Mouse Dragged c it r n tx- ,J \t"+y; this, display Or ? . . public void mouseMoved(MouseEvflJit mO K = me.getxO j y = me .qetYQ ; str 4« rl Mouse Moved as; ,, -!-x+"\t , '+y; this.displayO;

public void di'splayO ta.-&etText(str> ; j *tr= rj "; public static void main String args[l) //create the frame wouse Events mes = nt?w Mo use Events CM mes . setSi ze (40 D, 400} ;

522 | Chapter 28

me s , s e tDe f au 1 tcl os eop e rati on O * rarree . ex rr_GN_c LOSE) ;

Output:

:\> qavac MouseE vents c:\> java mous&e vents

Conclusion Since AWT components are heavy-weight and dependent internally on native methods, swing has been invented. Swing components are light weight and take very less resources of the system. The screens designed in swing look same on all operating systems. But, if the programmer wishes to provide a different look and feel depending on the operating system, he can do so. This is the "flexibility in swing. Also, swing has more and more number of features which made it to be programmers' favorite package. This is the reason that today almost all software development companies look for swing programmers for their projects.

Graphics Programming — Layout Managers

CHAPTER

We create several components like push buttons, checkboxes, radio buttons etc., in GUI. After creating these components, they should be placed in the frame \m AWT) or container (in swing). While arranging them in the frame or container, they can be arranged in a particular manner by. using layout managers. JavaSoft people have created a LayoutManager interface in java. awt package which is implemented in various classes which provide various types of layouts ta arrange the components. n— imifc_ _j l Li- v What is a layout manager? g A layout manager /a a class that is useful to arrange components in a particular manner in a frame or container. ^ f - ^ The following classes represent the : layout managersin Java: FlowLayout BorderLayout CardLayout a GridLayout GridBagLayout BoxLayout To set a particular layout, we should first create an object to the layout class and pass the object to setLayout ( > method. For example, to set FlowLayout to the container that holds the components, we can write:

524 | Chapter 29 - - ;- " n - _ FlowLayout FlowLayout is useful to arrange the components in a line one after the other. When a line is filled with components, they are automatically placed in the next line. This is the default layout in applets and panels. To create FlowLayout, we can use the following ways: FlowLayout obj %iewr FlowLayout () ; This creates flow layout. By default, the gap between components will be 5 pixels and the components are centered in the first line. " © Q FlowLayout obj = new FlowLayofltiint alignment) ; Here, the alignment of components can be specified. To arrange the components storting from left to right, we can use FlowLayout . LEFT. To adjust the components towards right, we can use FlowLayout.. RIGHT" and for center alignment, we can use FlowLayout .CENTER: FlowLayout' obj = new FlowLayout (in t alignment, int hgap, int vgap) ; Here, the hgap and ^gap specify the space between components, hgap represents horizontal gap and vgap represents vertical gap in pixels. Program 1: Write a program to create a group of push buttons and arrange them in the container using flow layout manager. The buttons are right justified, //FlowLayout demo nimport java.awt,*; import javax. swing. *; class Fl ow Lay ou tDemo Flow L ay ou tDemo () //create content pane Container c = getcon tern: Pane O ; //create FlowLayout object with alignment: right //and 10px horizontal and vertical gap flow Layout obj = nm lOaivLayoiitC FlowLayout RIGnt ,10,10) ; //s&i the layout feTedh^epS pjjkhS csetcayout .Cobj) ; //create 4 push buttons J Button bl,^,^,^; hi - new 1 Button ("Buttonl"] ; hi = new J Bu t ton (."But ton 2 " } } b3 - new 3ButtonC n Eutton3"J ; h4 - new J Button ( 11 But ton 4" > ; //when we add the buttons to c, they are added as per flow layout c.add(bl); c.addf b2} : c-add java Border Lay outDerno

In preceding program, the components are arranged in the four borders as well as in the center of the container.

Card Layout A CardLayout object is a layout manager which treats each component as a card. Only one card is visible at a time, and the container acts as a stack of cards. The first component added to a CardLayout object is the visible component when the container is first displayed. To create CardLayout object, we can use the following ways: CardLayout obj = new CardLayout (}; Here,, the card layout object is created without any gaps between the components. CardLayout ^ob j = new CardLayout (inthgap, int vgap) ; The preceding statement creates a card layout with the specified horizontal and vertical gaps between the components. s While adding components to; the container, we can use add() method as:

To retrieve the cards one by one, the following methods can be used: • void first (container) : to retrieve the first card, • void last (container) : to retrieve the last card.: • void next (container) : to go to the next card. • void previous (container) : to go back to previous card.

528 | Chapter 29

• void showicofitaiJie^r "cardname^) : to see a particular card with the name specified. Program 3: Write a program to create ^ group of push buttons and add them to the container uj CardLayout.

//jCarjd layout demo import jjavcuawt. - ; i mpo rt j ava . awt . event . ; i mpo rt j avax , swi ng . 1 n a , class cardLayou iuemo extends J Frame implements ActionLisrener nT //vars Container c; Ca rd Layo ut r.a rd n D Button bl J b2,b3,b4; nr " -n - - Ca r d Layout Demo Q //create eontiriuftr c = yetContentPSineO : //create CardLayout object with 50 px horizontal space //and ID px vertical space card - nev. card Layout! SO, 10) //set the layout to card layout c . setLayout [card} ; . . //create 4 'push buttons hi = rrew ]8iittanC n E5Mtton3 ") ; hi = new J Button C"ButTon2 ,r ) ; b* = new J Button T true ton^'}; hA = new J Button C'Button^ 1 '"} ; //add each button to c on a separate card caddC First card".bU; c T ad dC second card'\b2); cadd ("Third card",b3); c .add ("Fourth care", b4); //add action listeners to buttons . bl. addiction Li s-zenerCthi si; h 2 . add Ac ti on'Li s t e re r ( th i s j ; h 3 . add Ac t i r> I. i s - t e r U h i s J i b4 . addAC Li on Li stene r (. th i 5 j ;

blic void action Per formed (Action Event ae)

OLID PIC

. }

pub"i i t

//when a button is clicked show the next card card. next(c) ; /* To show a particular card, e,g. Third card, we can use £s; ca rd . sh ow( c , r4i i rd ca rd 1 ' ) ;

static void main (St ring args[]) //create frame CardLayoutDercio demo = new Card Layo LitDemoD; demo . setsi ze C400 , 4GQ) ; demo n setTi tl e ( " Ca rd 1 ay o ut ,fc ) demo . setvi s i bl e {X rue) ; t^o.setOefauT telescope r at fooO Frame r EXiT_0N_a,0'5R ;

Graphics Programming - Layout Managers j 529

Output:

C:\> 3 a vac: CardLAyoutr>emt>. java c:\> java Car d*_ ay out Demo

In preceding program, the components are arranged on 4 cards whose names are First card, Second card, Third card and Fourth card. When a button on a card is clicked, the next card is displayed.

I Card layout

•S3®®

Observe the preceding output. If the Button 1 is clicked there, the next card with Button2 will be displayed as shown here.

E5 Card \x //gap between components GridLayout grid = new GridLayout (2, 3 , SO, SO) ; c . setLayuut ri d) ' T //create !> push buttons J But con bl = new .1 Button ("Buttonl") ; J Button b2 = new J Button C M Button2"j ; j Button b3 = new 3 Button v' Button?- 1 ) ; J Bu t.io n b4 = new J Bu X ton £ " 1 Button4 " ) : .] Button b5 = new .TBjJttonC'ButtortS"} ; //add buttons to c c.eiddCb2)i c. a dd£b4);

Graphics Programming - Layout Managers | 533

stafi c vol d mai n (st n ng a rgs [ ] ) //create a frame Grid Layout Demo demo = new GridLayoutDentoO ; demo , setsi zeCSOO , 400) ; demo.setTltleC'Grid- layout") ; dento , setVi si bl e(trije) ; deiRo.setDefaultCloseOperati on (D Frame . EXIT_0N_CL05EJ ;

Output:

- Grid layout

Button 1

£utton2i

B«tt 0 n4

GridBagLayout GridBagLayout class represents grid bag layout manager where the components are arranged in rows and columns. This layout is more flexible as compared to other layouts since in this layout, the components can span more than one row or column and the size of the components can be adjusted to fit the display area. The intersection of rows and columns where a component can be placed is called a 'grid' or 'display area'. When positioning the components by using grid bag layout, it is necessary to apply some constraints or conditions on the components regarding their position, size and space in or around the components etc. Such constraints are specified using GridBagConstraints class. To create grid bag layout, we can, create an object to GridBagLayout class, as:

To apply some constraints on the components, we should first create an object to GridBagConstraints class, as:

This will create constraints for the components with default values. The other way to specify the constraints is by directly passing their values while creating the GridBagConstraints object, as:

GridBagConstraiivfcs cons n = new GridBagConst£aints (int gridx, int gridy r int gridwidth, int gridheight, double weightx, double weighty, int anchor, int fill, Insets insets, int ipadx> int ipady) ; Let us now understand each of the constraints. GridBagConstraints .gridx, GridBagConstraints .gridy: They represent the row and column positions of the component at upper left corner of the component. See Figure 29.2. gridx= 0 1 5

% i

P pridBag fa)

BUtton.1 .

LJNMM&,

.. mm£-~

Suftoa?

Button 9

, grnlx=2

Figure 29.2 gridx and grid/ values GridBagConstraints .gridwidth, GridBagConstraints .gridheight: Specify the number of columns (for gridwidth) or rows (for gridheight) in the component's display area. The default value is 1. See Figure 29.3. .

f% GridBd&.tayout

gridwidth=2

Figure 29.3 gridwidth=2 for Button4 GridBagConstraints .weightx, Gr idBagConstraints. weighty : When the frame is resized, the components inside the container should also be resized or not - is determined by the weightx and weighty constraints. When these values are not set, by default, they take 0.0. This means the components size will not change when the frame is resized. The components wOl have their original size. If the weightx and weighty values are set to a value from 0.0 to 1.01 then the components size will also change along with the size of the frame, weightx is far resizing the component horizontally and weighty is for resizing the component vertically Generally, weights are specified with 0.0 and 1.0 as the extremes, the numbers in between arc used as necessary. Larger numbers indicate that the component's row or column should more space. Figure 29.4 depicts components when resized and not resized.

*H GndBag layout

± % Button jL^ %

Button* ^

Buttons

Buttons I

X! H fM GridBag layout

weights 0.7 weighty=0.7 w*ighbt~0.0 weighty- G.O Figure 29.4 components resized and not resized

Graphics Programming - Layout Managers f 535

GridBagConstraints .anchor : When the display area is larger than the component, anchor constraint will determine where to place the component in the display area. The positions of the component in the display area are shown; in the Figure 29.5 here. The default value is GridBagConstraints . CENTER.

RUST _L1N-E_ST AFT

H]7BT_IJ|ME_ENP

UNU_fiTArcr

CENTER

-©• UNE_END

LA&T i _LINI'_ j START

LAST_iJ>rE_J=N[J

Figure 29.5 The anchor values of a component

GridBagConstraints . fill : While the weightx and weighty constraints are useful to resize the component according to the frame's size, filT is useful to resize the component according to the space available in its display area. If the display area is larger than the component, then the component should stretch and occupy the display area horizontally or vertically and it is decided by the fill constraint. Possible values are as follows: GridBagConstraints. NONE (the default) GridBagConstraints . HORIZONTAL (make the component wide enough to fill its display area horizontally, but don't change its height) GridBagConstraints. VERTICAL (make the component tall enough to fill its display area vertically, but don't change its width) GridBagConstraints. BOTH (make the component fill its display area entirely). The effect of fill constraint is shown in Figures 29.6(a), (b) and (c).

.H'GndBag layout lv^fS,|[K

Figure 29.6 (a) Filling horizontally

'fi GiidBdg layoi

IP

Button 2

f rjfflOt|g-v_-,

Buttons

Button? W j

Buttons

Figure 29.6 (b) Filling vertically

536 | Chapter 29

H GridB.ip, layout

Button 1 y ; ;.V V -;-. .

^ ButtOft2

Buttons ^ •

Button 4

Buttons

Button^

s ., B«tton7 l '

.Button 8

BiitionS

Figure 29.6 (c) Riling in both directions GridBagConstraints. insets: This constraint is useful to leave some space around the component at the four edges of component. This space is left around the component and the boundary of its display area, insets is the object of Insets class, so it is created as:

insets insets = net* insetsCS ,10,15, 20) ;

Here, we are leaving 5px at top of the component, lOpx at left, 15px at bottom and 20px at the right of the component. See Figure 29.7. By default, it is given as:

insets = new lnsetsC0 ? O r 0 P O> ;

1 5

-20

I 15

display a

Insets insets - new Imetet^ia^S^O); Figure 29,7 The effect of insets constraint

GridBagConstraints .ipadx, GridBagConstraints. ipady : ipadx and ipady are useful % leave space horizontally and vertically within the component. After adding the space, Hi components size width-wise and height-wise will increase. Default value is 0. What happed when ipadx and ipady values are set to a component is shown in Figure 29.8.

ipadx -0 ipady - 0 (original size)

ipadx = 100 ipady -0 (original size + ICQ pa width-wise)

ipadx = 0 ipady = 100 (original size + ICO px height-wise) Figure 29.8 The effect of ipadx and ipady constraints

Graphics Programming - Layout Managers

Program 6: This program is designed to display 5 push buttons using grid bag layout manager at certain positions. Please observe the output of the program constraints_set to the buttons; ^ - - ~~~ r ~

//GridBag Layout demo iir-port java.awt-"; i iripo r t ] avax . swi n g . v ; lass GridBagLayoutDenvo sxtends 3 Frame //vars GridEsgLayout gbag^ G ri dBagCo ns trai n ts con s ; Gri dBag Lay ou tDemo { ) //get tli a content pane Container t = getConterctPaneO : //create Gridtiag Layout object ybag - new GridBagLayoutO ? .//set gridbag layout to content pane c. set Layout (gbag) ; //create GndfiagCo-hs tracts object cons = new GridBagConst raint&O ; //create 5 push buttons j Button bl = new J Button ("Button l n ); JR Litton bl = new if Button (" Button 2"); .7 Button b3 = new J Button ("Button 3"); J Button b4 = new J Button ( 1 1 Button V T Y; ^Button b5 b new J Button ("Button 5") i //for all buttons, use horinzontal filling cons if til = £ri d&agcons r ra.i nts , HORIZONTAL ; //display button! at x,y coordinates' 0,0 cons .gridx = 0; cons .gridy = 0 i •//resize all the. tamp orients when the frame is resized //eons, weighty = . //set the above constraints to button 1 gb ag . se t Cons t r a i rit s ( bl , cons ) ; //add button 1 to content pane c add CM 3; //'display button^ at x,y coordinates l.Q cons ..grid* - 1: cons.gridy » 0j //remaining constraints applicable as sfe* for previous button //set constraints to birt?«n2 gbag . setCon-strai nts f_h2 , cons) j ; }.

Output:

t:\> J a vac BoxDemo. Java ~:\> lava BoxDerno

iter Name: \

l •

Bite* Password: ]



Conclusion

Layout managers are useful to arrange a group of components in a partieular manner in a contain^ as wished by the programmer. FlowLayout is the simplest layout manager and GridBagLayout is tfci most flexible and complex layout manager among all other layouts. While working with a group a components, the programmer should first plan his output and accordingly decide which layooj should be used in a particular application. Then only he can start writing his program.

CHAPTER

Apple i s *

30

When a HTML (Hyper Text Markup Language) page wants to communicate with the user on Internet, it can use a special Java program, called 'applet' to communicate and respond to the user. The user can interact by typing some details or by clicking the components available in the applet program. The program then processes and displays the results. We can understand an applet as a Java byte code embedded in a HTML page, generally for the purpose of achieving communication with the user. We can think of an applet as:

Apple > - roue * hT*i page.

What is an applet? An applet represents Java byte code embedded in a web page.

Creating an Applet To create an applet, we need to write a Java program and compile it to get byte code. Then we should embed (include) it into a HTML page on a particular location wherever we want it to be displayed. This page is then stored in the web server. A client machine communicates with the web server, the server then sends the HTML page that contains the applet. The page is then transmitted to the client where the applet is executed on the client's web browser. Thus applets are executed at client side by the web browser. Thus applets travel thousands of kilometers of distance on Internet and reach the client machines before their execution on the client. To create an applet, we have Applet class of j a va. applet package and JApplet class of javax. swing package. These classes use the following methods, which are automatically run by any applet program. So, these methods should be overridden in an applet program. public void init ( ) : This method is the first method to be called by the browser and it is executed only once. So, the programmer can use this method to initialize any variables, creating components and creating threads, etc. When this method execution is completed, browser looks for the next method: startO- public void start () ; This method is called after initQ method and each time the applet is revisited by the user. For example, the user has minimized the web page that contains the applet and moved to another page then this method's execution is stopped. When the user

546 [Chapter 30

comes back to view the web page again, start() method execution will resume. Any calculatioj and processing of height-300 widths "htffllA

Save the above code with the name: MyApp.html. This HTM opened in the browser, or an applet viewer supplied by the test the applet. For this purpose, open any browser and in t name along with the directory path. The applet opens in system prompt as: app 1 et v i ewe r MyApp , h tsi

to open the applet in the applet viewer. Opening of the applet in the browser also in the applet

Applets 549

© n 0 0 .© S* * ML #p Mjbna Star led £3 Laf.nl hwrfres

Lejt us write another applet^ismg the methods: irfit0, «tart0, stopQ and destroyQ along with paintQ method ^feo track and: display the execution sequence of. these methods. Remember, none of these methods arc compulsory for creating an applet. Program 2: This Java program creates an applet with some background color and foreground color with a message. The message string is stored in msg and is displayed in paint() method.

//applet creation Import java.awt. * i i mpo rt j a va . app 1 et « * ; public class Appl extends Applet { /Avars String Stfjf^'^j //this method is executed when an applet is; loaded public void inixO .//set back round color for ap&ie.t Frame set Background (Color . yel 1 ow) 5 //set foreground for text in frame setForegroundCcolor .red) ;

//set font for text in applet Font f = new Fontf'Arial Font, setFont (f> ; //store method name in msg msgi-^" init p ;

BOLD, asai

//this method is executed after initd public void start O //add this method name to msg msg4=" start n ;

//to stop the- applet public void stopQ //add. this method name to msg s»s§+= " stop " ;

55q[ Chapter 30

//to remove applet from memory public void destroyO //add this methu name to msg msg-^= " destroy " ; ] _ ._- ., .

Output:

C:\> javac Appl k Java c:\> " Nfiiv, create a HTML pa$e to embed the Appl applet into it, as shown below: ^/appl et> pen the above &yApp,html file in the applet viewer, C:\> applet viewer MyApp,html

MLI.IIJ. IJ...IJIII—5CT1

init start paint

Applet sldrtnd

See the output of Program 2. Minimize the applet frame and you will see stopO method executed, then maximize it to see if the start() method is executed- When ever the applet frame is resized paint i) method is again executed, thus showing the updated contents of the applet frame.

An applet with Swing Components

Let us see how to use swing components in an applet. We know how to create components using javax. swing package. In Program 3, we create a text field for receiving the name of the user, a text area to receive the address and a list box: to receive the user selected items. Two push buttons OK and Cancel are created additionally at the bottom of the form. When the user enters his 5 strl= n,r 1 str2= nik ; Object x[] ; JLabel n.Qfi ^ 1 hi : zrrextField name; Treat A re* addn JList 1st; J Sutton M. T b2; Container c; public void inft^Sj //create J Frame and container 3 Frame jf = new J Frame O; c = . Jf .getContentPane-O ; //display yellow background color in container c . setEackground(Color ,-yeill ow} ; //do not. set any layout to c c.setLayoutCriLiU); //set the size and title for frame - • jf,set7ltle(-My Form"); //display the fraiftei jf.setvid li?eCtrwe)i //Display he&diny in the frame using a label Font P = ntan Fo n t ( n Di al do |P 7 Font . BOLD \2fi~) i \hl - neiw jubelC); ibl .set Font CO J I bl . s*t foreground (Color . red) \ lbl-S«tTeXtC "^-ELECTRONICS ONLINE SHOP"); t bi - setEounds (?oo , 10 , 500 , so j t c.add(lbl); //Text Field and a label for entering name n m new JLateU"Name: JLabel . left? \ name - new 3TextFleldC30} ; n r setBcmnds r 50 , 100 r 100 a 30) ; name . setBoundsC^OG t 100 a 200 , 30) ; C,add(n) ; - . _ c,sEdd(najne) ;

//Text Are a and a label fur entering address a - new JLabel ("Address; % DLabel .left;) ; addr = new JTeatArea(5,5D)r a^s.ettsoundsCSO, 150, 10D 5 30) r addr. setEounds (2QQ , ISO, 200, 100} i caddCa) * c, add (add r} ;

//List box tor multiple selection i = new JLabel ("select items: i JLabel .left) ; string {J widr.h=30G heighr= 6GG>

tag has two attributes name* and Value', "name' represents the name of the parameter and Value' indicates its value. For example, in the above code, we have two parameters: tl and t2 and their values are "Nag* and "1 50000. 50* respectively. To receive the values of the parameters, an applet uses getParameterO method. This method takes the parameter name and returns its value as a string.

where name and str and String type variables. getParameter {} method should be used inside the initQ method of the applet. tag is useful for passing information to the applets. This eliminates the need for modifying the applet even if we want to pass different , "scott" , "ti ge r" ) ; //Create a SQL stattmen- statcment stmi * con . createstatementC) ; //count the time before insertion long tl = System. currentTimeMlll isQ 7 //insert 999 rows into mytab forCint i T

What is the difference between a function and a method?

9

Which nart of »I\HMf will atlocafp the roemorv for a Java nropraTTY?

Which algorithm is used by garbage collector to remove the unused variables or objects from memory?

10

How can you call the garbage collector?

to

What is JIT compiler?

12

What is an API dooxment?

What is the difference between #include and import statement?

18

What happens if String args[] is not written in main() method?

20

What is the difference between print0 and printlnf) method?

25

What is the difference between float and double?

30

What is a Unicode system?

31

How are positive arid negative numbers :re^eseni^yiiitemally? : n

What is the difference between »and »> ?

43 n n

What are control statements?

47

Out of do:..while and while- which loop is efficient?

50

What is a collection?

[•••.OP " 4

622 I Index

Questions

Dana KJ r\ rage rao*

Why goto statements are not available in Java?

59

What ifcthe difference between return and System.exit(O) ?

64

What is the difference between System*exit{0) and System.exit(l) ?

64

What is the difference between System.out and System. err ?

66

On which memory, arrays are created in Java? *

81

Can you call the main() method of a class from another class?

93 '

Is String a class or data type?

95

Can we call a class as a data type?

95

What is object reference?

101

What is the difference between — and equalsQ while comparing strings? Which one is reliable?

101

What is a string constant pool?

102

Explain the difference between the following two statements: 1. Strings = "Hello*; 2. String s = new Strmg( Hello") ;

103

What is the difference between String and StnngBuffer classes?

107

Are there any other classes whose objects are immutable?

107

What is the difference hetweeh StringBuffer and StringBuilder classes?

113

What is object oriented approach?

116

What is the difference between a class and an object?

117

What is the difference between object oriented programming languages and object based prograinming languages?

122

What is hash code?

124

How can you find the hash code of an object?

124

Can you declare a class as 'private?

129

When is a constructor called, before or after creating the object?

3:31

What is the difference between default constructor and parameterized constructor?

134

What is the difference between a constructor and a method?

1 Q/t

What is constructor overloading?

134 ...

What are instance methods?

142"

What are static methods?

144

Questions

Page No.

What is the difference between instance variables and class variables [static variables J?

146

Why instance variables are not available to static methods?

148

Is ft possible to compile and run a Java pro grain, without writing'mainfl method?

tap

How are objects are passed to methods in Java? ,

157

What are factory methods?

In how may ways can you create an object in Java?

166

What is object graph?

I? 3

What is anonymous inner class?

180

What ia inheritance?

; 183

Why super class members are available to sub class?.

188

What Is the advantage of inheritance?

188

Why multiple inheritance is not available in Java?

196

How many types of inheritance are there?

196

What is coercion?

197

; What is co aversion?

19B

What is method signature?

199

What is method overloading?

200

| What is method overriding?

20!

What is the difference between method overloading and method overriding?

202

Can you override private methods?

204

Can wc take private methods and ikta! inethrjcte =*s same?

205

What is final?

205

What Is the difference between dynamic polymorphism tm.d static polymorphism?

205

What is the difference between primitive data types and advanced data types?

210

What is iETjplinii casting?

.; : 1

What is explicit casting?

211

What fa generalisation and specialization' 11

2 12

What is widening and narrowing?

217

Which m the super class for all the classes inciudmg ^mr classes aiao?

a i7

Which method is used in cloning?

222

624 Index I

Questions

Page No.

Can you write an interface without any methods?

; 222

What do you call the interface without any members?

222

What is abstract method?

What is abstract class?

225

How can you force ytiLir prujprarrcmes-s to implement only the features of your 1 dm$?

23 Q r

Can you declare a class as abstract and final also?

232

Wbei i£ an interfere?

234

Why the methods of interface are public andr abstract by default?

235

Cwti you implement one interface from another?

| 240

Can you write a class within an interface?

240

What 13 tht: diffcrr-nct between zurt abstract class and an tnicrface 7

A programmer is writing the following statements in a program: 1. import java.awt**; ; 2. import Java, awt . event. *;

246

Shnulo he write both the staJfrrncrifs m his program or the firs! one is enough'

246

How can you call the garbage collector?

247

What tg tfaja djffareru:* between fog Mowing two statemenTs- 1 J Tin port packrAddition; 2| import pack.*:

251

What is CLASSPATH?

252

Wtet fsf a JAR file?

: ; 253

What is the scope of default access specifier?

259

What happens if maim) method is written without String at gs| j V

26G

What are checked exceptions?

267

What is Throwable?

268

Which is the super class for all exceptions?

268

What is the difference beRve^n an exception and an error'?

IBB

What is the difference between throws and throw ?

279

Is it pos&ibte to re -throw exceptions?

281

Why do we need wrapper classes?

284

Question Index [ 625

Questions

Page No.

wnujj us idt= vvrHj/ps^j li^h^q^c uun\H3UH riijj un.e Miami uiAurr |or) Whicb of the wrapper classes dees not contain a constructor with Striizft aa

What is boxing?

289

j Whai is unbci.drtg?

IW

What happens if a string like "Heliosis passed to parselnt[j method?

290

wbSE is a isrfiliirs n,ji:i':v -m kF

299

Does a collection object store copies of other objects or their references?

299

Can you krorea primitive data type Into a tfollectTOn?

. 300

What is the difference between Iterator and Listlterator?

301

, WhRt i*i the dirTorence between Iterator and Enitmemtlbn?

What is auto boxing?

What is ihfl difTrnenc* between a SJtack and LirikedList 7'

j 3H7

What is the difference between Amaylist and Vector?

315

Can you synchronize Ihe Array Li at object?

S15

What is the load (actor for a HaahMap or Hashtable?

316

What ia the difference between HashMap and Hashtable *

Can you make HashMap synchronized ?

321

What is the difference between a Set and a Lis^?

3S1

What is the difference between System, out and System. err ?

334

What is the advantage of stream concept?

334

What ia the default. Mtlfer sizft uatsd ^ny ijitiltitd clas*?

339

What is serialization?

347

Which type of variables cannot be serialized?

:\-\ >:

What is dc-BcrialiEaudn?

348

Tl>e jjipuL fi]e neeti to he already avaiiabJe.

What is IP address?

358

Whet DNS?

3S£

The input file need to be already available.

352

V'-: Hi Hi ; toekfit?

359

What is port number?

359

626 I Index I

Questions

Page No.

Which thread always runs in a Java program by default?

376

1.3.1 In i n tnrf>Q/io orp v*oll*»/"l 1 -i ryTi i - _tt t^xi cr\~\ 'f" ^ Vk Ll'r UllCaUo cULC \srt 1 ICU ligll L WClgilL :

37S

Wh^t "i ^ rlii -- nrl i"Ffr^Tr , n , r i f* In^tTurp^n ritif^Ip f n^iWnn ^nri ititiMt t ^.^1 finer"-'*

37fl

How can you stop a thread in Java?

381

What is the difference between 'esrtends Thread' and 'LmpLecnents Ruonable*? Which one is advantageous?

3S!1

Which method is executed by the thread by default?

3S2

What Is Thread synchronization?

3S7

What is the difference between synchronized block and synchronized keyword?

388

What is Thread deadlock?

What is the difference between the sieepj) and waitft methods ?

397:

What .s the ddfanir priority 1 ore thread?

What is a daemon thread?

402:-

1 What is thread life cycle?

, 406

What is the difference between a window and a frame?

410

Wbar event delegation model?

Which model is used to provide actioos to AWT components?

414

Whai i$ an adaipter da as?

What is anonymous inner class?

! 4.1&

What is the default layout it* a framer

437

What is the default layout in an applet?

437

What ire Java Foundation classes?

+60

Discuss about the MVC architecture in JFC/ swing?

461

Wh^t are Hit; various* winduw panes ava'dgftfe In swing?

' 462

Where are the borders available in swing?

475

What is a layout manager?

523

What is an applet?

545

Whiit is applet life cycle?

546

Where are the applets executed?

546

I What is HotJiwaV

547

Which tag is used to embed an applet into a HTML page?

547

Question Index I 627

Questions

Page No.

What is ^ fgeroejfc i.ype?

564

What is erasure?

, 564

What is, atito btudng?

566

HT1 Java uses unchecked or unsafe operations.

569

What is JDBC?

573

What is a database driver?

580

How ca_n you regi&rer a driver?

580

What is DSN?

580

What is ResultSet?

581

Will the performance of a JDBC program depend on the driver?

595

What is parsing?

599

What is the difference between Statement and PreparedStaterneJit?

599

Whwt arc stored procedures?

690

What is the use of CallableStatement?

603

What is scrollable result set?

&D4

What is BLOB?

613

What is CLOB?

6J3

r Program Inde;

-J*

Programs

to display a message.

To find the sum of two numbers.

To understand tile effect of printfl and. printing methods an

codes

Let us now write a program to observe the effects of various bitv

Write a program to test if a number is positive or negative.

Write a program to display numbers from 1 to 10.

Let us rewrite the previous program (Program 2) using while

Iog

Write a program to display numbers from 1 to 10.

Write a program to display numbers from 1 to 10 usmg%ifmit<

Program to display stars in a triangular form — a single star in stars in the second line, three stars in the third line, and so on.

Program to see the use of for-each loop and retrieve the elen from an array and display it-

Write a program for using the switch statement to execute depending on color value.

— — ~ n - n 'n. ' nJ.- ' ' ' ^ TTT Write a program to come out of srwitch block, after executing a i

Write a program to use a break statement to go to end of a bloc

Write a program using for loop to displaj fee numbers in desc

Write a program for using nested loops {to display i and j value

Write ^. yogram to return a value from a metjE6&

Write a program to demonstrate that the return statement terminates the application.

To accept ^d d^jplay a character f

Programs

Psg& No.

Acwprirtg ;3 Tiarn^ (alringl irmn the keyboard.

6B

Accepting an integer from keyboard.

69

Actzeptiii^ nt Doa! number.

70

Accepting and displaying employee details.

71

Accepting and displaying employee details - version 2

75

To accept different types of input in a line at a time from the keyboard, just like I one can do using sane() crief Tind ls called.

221

634 | Index I*

Programs

Pafje No.

Write 3 program, where M}d ip available to all the objects and hence every object csjlqulatei the aquEire Value-

Let us make a program where the abstract class Myclass has one abstract method which has got various impleonpntarians in sub classes.

225

WHtfi u iimgram in which abstract class Car contains an instance variable; one 1 concrete method and *wu abstract to retrod**. CompiJ^ ttjis c&dv in gEt-Car.daa^. Wl dijj noi ;iin j! LKfcauJvc tt i l s Fi~i f hi i -~ L " i t k ~ fji i h nfiik'^i i/. . . nn • . --- — i — f -—i 4* Ii 't i n p> t cihi i n nn tT-L - - J~ ULMdlSI JlT f.-'r! 1UI LLJ lulitl ^ LL L U |Jr [ - LJ'-J 1 l-z 1 • n c-L Ta » d i^h 1 1 H Dl Igr r


-ir |-

Write a prci-r-raTn ^has shows the use of LiriktrdLisi class.

309

* t,Un^P "n 7~;7i"i u i Mu i iii i£*Hf-cli iin AttPvLi^I iA.nl 1. uinn1i.s >inn ri^rfrTFrn 'JSnnif m i -i TTUIC * 1 J*"*LiKU AUJ. i i J 1 tl 1111 J 1 1 r VJ i i. yv i i (, 1 p r i i n i \ft ri i 1 1 i J.pl-.i n u |jj ffl f luM IT 1 o p era d^tiiL? on ii .

n

Write a program dial shows the use of Vector Class.

314

Lte i Dra^ram that shows the use of HsshMap class-.

317

; Write a program that shows the uef of f ErifthT&blc class.

\V2(\

' Wine a program thai shows Ihe use oi' Arrays.

322

Write a program that shows sorling vising comparator..

324

WHte apj'Lij^ram thai shows the use-oi'SLringToiceiiizer object.

$26

, Write a program thai shows the use of Calendar class.

32S

1 * r i" 1 1 c -2 pi cj |3 rai] l trial shfiwia llie use 01 Dat^-izlasii.

329

An Array List handling a group of Employee class objects .

330

Wrlir T3 r.n^rinri tfhieh shnm b i.rrair i,^rnnJO>CiT r«a-5c- wri^Jtr.^ riiir^f r.s are tc: i>c ^Lcir^u mm h

-.- -r

Write a program to show serialization of objects.

349

Write u ^Lr r grarrj ahuwiri^, dt-iJtTJiil^ulj.vn ^.biecta.

Write a program which accepts a filename ^from command line arguxnerit and

351

I

Program Index 637

Programs

Page No.

displays the number of characters, words, and Lines in the iile H

\X/tt"I"p t nmimTTT In TfTrJ 1 H r r- Hi n t p n t ^ r\F tY\(^ mntH filr* T-rn r4 mrrrlp# TrnrTn ttiSm tti VI n LT- 3 ^.1 i 'J til c\l: 1 I'l ! '^'-MLI 1 lit- V-JlUI ICll UL h 1 1 C- LllJJ I 1 ' J 1 X . JJJU k.1 " ' 1 M> I U' 'H U M r ' - U.< nuipm file,

write a. program tnat accepts a rue or uirectory name uom commano. line arguments.

^4 oot

Write & program to accept a directory name and diapkay iis contents into an airay,

*

Write a program to accept a website name and return its IPAddress, after checking it on Internet.

360

WnLe a program to retrieve fEfierent paii^ of a URL supplied to URL class object-.

Write a program to display the details and the index.htmL page contents of www.yahoo . com .

Write a program to create a -servei for the purpose oi sending some smiigs 1o the client - ,

965

Write a program to create client side program, which accepts all the strings sent by the server.

367

Writr ^fjfWgrarrJ t£i wr^te &dfetfir HusSi *h&\ the Server rtioeftfl^ data from ihe dllcni using BuHeTfirfRaMter gtad ^ntls t*n|y Ed !faf9 cfifltil UiUHg

368

Write a program to create a client which first connects to a server, then starts the - communication by sending a Ktnn g t n the server. The server sends response totke client. When 'exit' is typed at client side, the program terminates.

369

Write a program that accept tog Filename and rhedte for Its nxterence. When the rite exists yi -i«.:rvrr side, it fcends 1-s wntonfs |o file client.

Write a client program to accept a me name from the keyboard and send that name to the server. The client receives the fiie-coritents- from the server.

372

Write d program to find the thread nsed or JVM ts& execute the statement.

375

Write a program to create MyThread class with runQ rpethod end Then attach a thread to this MyThread class object.

| 379

Re write Program 2 showing now lo terminals Ihc "hn^d hy pressing the ft Titer LuitlDiL

Write a program showing execution of multiple tasks with a single thread

382

• Wrhv h program Rowing two ffigtearife wmfeng aimnlt^ffequsljr' upon LWo objecte.

Write a program g hawing two threads a tzting upon a single object,

385

Write a program to syncrironise the threads acdng an the s^rrm object. The 3ynchrorjjzeG -"lock in the program can be executed Hy irmiv ©rtfc intra r| at a time,

Write a program depicting a situation in which a deadlock can occur.

391

638 Index W

Programs

Page No.

Wcrir a progmta where Die QtWBmuxrtr thread tlit?eks iviifi.bei Hit data

Write a program such that the Consumer £bread i» informed immediately when title data production is over. i

397

Write _l program to understand the thread prion ffefe, I&e Inroad With faightsr priority iiumber'will complete its Eatecutiorj first-

Write a program to demonstrate the creation of thread groups and some methods which act on thread groups.

* 401

Write program t*> Cre#c a zztyct wHh 2 cteate Framed -with Back button, such tha clic ks Back buttdnyFrjaffl£i^ we see the Frame 1 onl Write a program to create a frame by creating an object to JFram

Rewrite Program 1 to show how to terminate to Application bj close button of the frame. ^ - i

Write a program to create the frame and display green color in jit!

Write a program to display text in the : frame by oforriding^ method of JPanel class, ^ .... 3§|j

Write a program to display some text in the frame with the help <

Write a program to create some push buttons using JButton diffif&nt borders ai^und 1^e biittons:

Write a program in which we create a push button with a label and then set different features for the- button.

Write a program -to-.- Create a push button as;^we did in Progra button is clicked an image is displayed: in the frame. ^ :

Write a program that helps in creating some check boxes anc When the user clicks on a check box or radio button, the sele will be displayed in a text area. __ n n " n * J ' ' ' Write ;a program that changes the look and feel of the component

Write a program that creates a table with some rows and column

Programs

Page- No.

Write- a prv&Ltm m i »nr l, JJ u-JU illc UtLLdU-Ll-^tV CcLlL Li.Js=iLc LLjc UII Ic LdU/JcIl I Li rc LI leve L.4 1 1 rlc v: 1 J i'.jTlV- M*. ImI myrao.

In this pro grant, we use Statement ofajtjet to insert rows Isir.n mytab.

Let us now re-write tin: previous program, using l^-eparedSiELLemenl and utserr i '"lOQ T*rltVtrft intA TTHTPi i.lT-1"

sag

In this program, we create CftlJabTeSlatement to call the stored procedure and retrieve the resull from orsclft sttrv'cr,

taOI

Thifz- program user- CaUabdeStaternenL to coil s runctton and £eis the returned vaJUL" iroiiL Lbt? ftiriclian.

60S

This program uses scrollable result set to retrieve the data from the database and also perform operations like mserting new row, deletion and updation of rows.

605

in tins program, we store an image i-gif into the £rat coimmi tiT\hn hlgl&to i.aferifl. In this, program, use PrEparedStatemrni-,

BOB

This progiam retrieves the image from 1st column of bigtab and stores it in the current directory with the name x 1 , gif ,

609

In Lfote program, we store myfiSe.tai file into my dob latije Set: that l.bc FUf! j myfSlfi.tKt already exists in the presenE directory.

1 In this program, we read the contents of myfSle.txt file from myclob table and store the same into newfile.txt

612

Let u* find qui the information *if The coiununt of iht table: enrprgb "This infortrtflHrin \s availabie in ResirtSet object wliich can he again retrieved liltn ! saltSetMetiiData.

u$

In this program, let us connect to oracle database with thin driver and let us know which features are offered by the database and driver vendors.

! 615

Mr. R, Magsswara fiao has be-on associated with teaching Computer Science sfrfea 1 993. He has worked st vanous colleges aa HOD iDep'.. ol Computers) and as a freelance developer for some time for a couple of organizations. He has been teaching Java since 2000 , and is currently associated with INet Solv Solutions, Hyderabad, a prestigious training division, fmparting. specialized training in Java. Mr, Rao is teaching and interacting wish more than 100Q;new student ever^i month, Including software developets and foreign students. Since 1398. Mr. Rao ss associated with 'Computer Vignanann", a widely E;ircutated- monthly rnatja^ine. published in Telugu. He has been on the editorial board of this magazine lor the iftlrt six yearn. He published several articles, including articles oh Virtual Reality, Mobile communications, Blue tooth technology, and Global positioning sysTcms. He also published hundreds of articles on C/C-s- -r and Java,

Published by: dr^mfech 19 -A, Ansiw Hoad. Daryagwij. New Dalhi=iiQM2 til; 51-1 t*23SH212, 23243075 BDC SI -23243078 Entail: 6asdteiX^dF&amlKhpfESE.ccrTn

Core Java - an Integrated Approach covers all core concepts in a methodical way. It helps you learn the concepts —from OOPS to Abstract classes and interfaces; from software packaging to providing API documents; from error handling to converting fundamental data into objecfform; from Collection Framework to Streams and Creating Client and Server Program to threads; from Creating GUI applications lo Generics and Communication with Database . This book also covers the interview questions along with the subject matter will help students do well in interviews. The questions presented in this bookhaye been collected from various interviews.

»

This book will help you to:^ • Understand the concepts of Java Language • Understand Data Types and Literals • Work with Conditional Statements • Apply OOPS in the Java • Work with Abstract Classes and Interfaces • Perform Type Casting' • Work with Built-in and User Defined Packages •^Handle errors and exceptions • Use Wrapper Classes • Use array for storing the group of objects • Create a file using Streams • "Zip and UnZip files in Java • Create Single and Multithread Applications • Create GUI Applications with AWT and Swing • Create an Applet • Work with Generic and Java Database Connectivity

I . CATEGORY: I Programming/Ja va

i

ISBN 10: fll-7722-aaL-L ISBN 13: 17fl-'Al-77ES-fl3L-L

Begmntr to Advanced ?!CE: Rs. 379/-

Smile Life

When life gives you a hundred reasons to cry, show life that you have a thousand reasons to smile

Get in touch

© Copyright 2015 - 2024 PDFFOX.COM - All rights reserved.