Table of Contents
Advanced JAVA Laboratory Manual Unit 1 Introduction Practical 1: Write an applet that draws a circle. The dimension of the applet should be 500 x 300 pixels. The circle should be centered in the applet and have a radius of 100 pixels. Display your name centered in a circle. (USING DRAWOVAL () method) Practical 2: Draw ten red circles in a vertical column in the center of the applet. Practical 3: Built an applet that displays a horizontal rectangle in its center. Let the rectangle fill with color from left to right. Practical 4: Write an applet that displays the position of the mouse at the upper left corner of the applet when it is dragged or moved. Draw a 10x10 pixel rectangle filed with black at the current mouse position. Practical 5: Write an applet that contains one button. Initialize the label on the button to “start”, when the user presses the button change the label between these two values each time the button is pressed. Practical 6: Write an applet that uses the mouse listener, which overrides only two methods which are mouse Pressed and mouseReleased. Exercise: Unit 2 Introduction Practical 7: Write a program that has only one button in the frame, clicking on the button cycles through the colors: red->green->blue->and so on. One color change per click. (use getBackGround() method to get the current color) Practical 8: Write an applet that contains three check boxes and 30 x 30 pixel canvas. The three checkboxes should be labeled “Red”,”Green”,”Blue”. The selection of the check boxes determines the color of the canvas. For example, if the user selects both “Red” and “Blue”, the canvas should be purple. Practical 9: Create an application that displays a frame with a menubar. When a user selects any menu or menu item, display that selection on a text area in the center of the frame Practical 10: Write an applet that draws two sets of ever-decreasing rectangles one in outline form and one filled alternately in black and white. Exercise: Unit 3 Introduction Practical 11: Write a database application that uses any JDBC driver. Practical 12: Develop a UI that performs the following SQL operations:1) Insert 2)Delete 3)Update. Practical 13: Write a program to present a set of choice for user to select a product & display the price of product.Exercise: Unit 4 Introduction Practical 14: Write a simple servlet program which maintains a counter for the number of times it has been accessed since IT’S loading; initialize the counter using deployment descriptor. Practical 15: Create a form processing servlet which demonstrates use of cookies. Practical 16: Create a form processing servlet which demonstrates use of sessions. Unit 5 Introduction Practical 17: WRITE a simple JSP program for user Registration & then control will be transfer it into second page. Practical 18 :Write a simple JSP program for user login form with static & dynamic database. Practical 19 :Write a JSP program to display the grade of a student by accepting the marks of five subjects.
A
DVANCED
JAVA L
ABORATORY
M
ANUAL
Advanced JAVA Laboratory Manual Copyright © Reserved by the Author
Advanced JAVA Laboratory Manual Unit 1 Introduction Practical 1: Write an applet that draws a circle. The dimension of the applet should be 500 x 300 pixels. The circle should be centered in the applet and have a radius of 100 pixels. Display your name centered in a circle. (USING DRAWOVAL () method) Practical 2: Draw ten red circles in a vertical column in the center of the applet. Practical 3: Built an applet that displays a horizontal rectangle in its center. Let the rectangle fill with color from left to right. Practical 4: Write an applet that displays the position of the mouse at the upper left corner of the applet when it is dragged or moved. Draw a 10x10 pixel rectangle filed with black at the current mouse position. Practical 5: Write an applet that contains one button. Initialize the label on the button to “start”, when the user presses the button change the label between these two values each time the button is pressed. Practical 6: Write an applet that uses the mouse listener, which overrides only two methods which are mouse Pressed and mouseReleased. Exercise: Unit 2 Introduction Practical 7: Write a program that has only one button in the frame, clicking on the button cycles through the colors: red->green->blue->and so on. One color change per click. (use getBackGround() method to get the current color) Practical 8: Write an applet that contains three check boxes and 30 x 30 pixel canvas. The three checkboxes should be labeled “Red”,”Green”,”Blue”. The selection of the check boxes determines the color of the canvas. For example, if the user selects both “Red” and “Blue”, the canvas should be purple. Practical 9: Create an application that displays a frame with a menubar. When a user selects any menu or menu item, display that selection on a text area in the center of the frame Practical 10: Write an applet that draws two sets of ever-decreasing rectangles one in outline form and one filled alternately in black and white. Exercise: Unit 3
Introduction Practical 11: Write a database application that uses any JDBC driver. Practical 12: Develop a UI that performs the following SQL operations:1) Insert 2)Delete 3)Update. Practical 13: Write a program to present a set of choice for user to select a product & display the price of product. Exercise: Unit 4 Introduction Practical 14: Write a simple servlet program which maintains a counter for the number of times it has been accessed since IT’S loading; initialize the counter using deployment descriptor. Practical 15: Create a form processing servlet which demonstrates use of cookies. Practical 16: Create a form processing servlet which demonstrates use of sessions. Unit 5 Introduction Practical 17: WRITE a simple JSP program for user Registration & then control will be transfer it into second page. Practical 18 :Write a simple JSP program for user login form with static & dynamic database. Practical 19 :Write a JSP program to display the grade of a student by accepting the marks of five subjects.
UNIT 1
GENERAL OBJECTIVES After performing this practical student will be able to: Learn about Applet. Develop an Applet Program in JAVA Execute an Applet Program in JAVA using AppletViewer Execute an Applet in Web Browser Learn How to use Graphics Class to draw Shapes. LEARNING OUTCOMES Explain & Practice Graphic Drawing Applications using Applets. ASSUMPTIONS Oracle JDK installed Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, Path, Classpath are configured.I
NTRODUCTIONWhat is an Applet?
According to Sun “An applet is a small program that is intended not to be run on its own, but rather to be embedded inside another application….The Applet class provides a standard interface between applets and their environment.”Four definitions of applet:
A small application A secure program that runs inside a web browser A subclass of java.applet.Applet An instance of a subclass of java.applet.AppletThe APPLET HTML Tag
Applets are embedded in web pages using the <APPLET> and </APPLET> tags. The <APPLET> tag is similar to the <IMG> tag. The CODE attribute of <APPLET> tag tells the browser where to look for the compiled .class file. It is relative to the location of the source document. The CODEBASE attribute is a URL that points at the directory where the .classfile is. The CODE attribute is the name of the .class file itself. For instance if on the HTML page of the previous section you had written
The HEIGHT and WIDTH attributes specify how big a rectangle the browser should set aside for the applet. These numbers are specified in pixels and are required. <APPLET CODE=“TestApplet.class” CODEBASE=“classes” WIDTH=200 HEIGHT=200> </APPLET> then the browser would have tried to find TestApplet.class in the classes directory in the same directory as the HTML page that included the applet. On the other hand if you had written <APPLET CODE=” TestApplet.class” CODEBASE=“http://www.foo.bar.com/classes” WIDTH=200 HEIGHT=200> </APPLET> then the browser would try to retrieve the applet from http://www.foo.bar.com/classes/ TestApplet.class regardless of where the HTML page was.
In short the applet viewer will try to retrieve the applet from the URL given by the formula (CODEBASE + “/” + code). Once this URL is formed all the usual rules about relative and absolute URLs apply.
You can leave off the .class extension and just use the class name in the CODE attribute. For example, <APPLET CODE=“TestApplet” CODEBASE=“http://www.foo.bar.com/classes” WIDTH=200 HEIGHT=200> </APPLET>
Executing Applet using Web Browser
TestApplet.javaimport java.applet.*; import java.awt.*; public class TestApplet extends Applet { public void paint(Graphics g) { g.drawString(“Welcome to the applet world”,20,40); } } TestApplet.html <HTML> <HEAD> <TITLE>Applet HTML Page</TITLE> </HEAD> <BODY> <APPLET code=“TestApplet.class” width=350 height=200></APPLET> </BODY> </HTML>
The import statements direct the Java compiler to include the java.applet.Applet and java.awt.Graphics classes in the compilation. The import statement allows these classes to be referenced in the source code using the simple class name (i.e. Applet) instead of the fully qualified class name (i.e. java.applet.Applet).
The Applet class provides the framework for the host application to display and control the lifecycle of the applet. The Applet class is an Abstract Windowing Toolkit (AWT) Component, which provides the applet with the capability to display a graphical user interface (GUI) and respond to user events.
Executing Applet directly using Appletviewer
TestApplet.java import java.applet.*; import java.awt.*; /* <APPLET code=“TestApplet.class” width=350 height=200></APPLET> */ public class TestApplet extends Applet{ public void paint (Graphics g) { g.drawString(“Welcome to Applet world”,20,40); } }
The Basic Applet Life Cycle
1. The browser reads the HTML page and finds any <APPLET> tags.2. The browser parses the <APPLET> tag to find the CODE and possibly CODEBASE attribute.
3. The browser downloads the .class file for the applet from the URL found in the last step.
4. The browser converts the raw bytes downloaded into a Java class, that is a java.lang.Class object.
5. The browser instantiates the applet class to form an applet object. This requires the applet to have a noargs constructor.
6. The browser calls the applet’s init() method. 7. The browser calls the applet’s start() method.
8. While the applet is running, the browser passes any events intended for the applet, e.g. mouse clicks, key presses, etc., to the applet’s handleEvent() method. Update events are used to tell the applet that it needs to repaint itself. 9. The browser calls the applet’s stop() method. 10. The browser calls the applet’s destroy() method. All applets have the following four methods: public void init(); public void start(); public void stop(); public void destroy();
Simple Methods to Design Applet
Method Description void setBackground (Color colorname )To set the background of an applet window.
void setForeground (Color colorname )
To set the foreground color of an applet window.
Color getBackground ( ) To obtain the current settings for the background color Color getForeground ( ) To obtain the current settings for the foreground color Applet getApplet ( String name ) To obtain the applet specified by given name from the current applet context.
Void showStatus( String status )
To display the status message in the status bar of applet window
URL
getDocumentBase ( )
To obtain the directory of the current browser page.
URL getCodeBase( ) To obtain the directory from which the applet’s class file was loaded Example: import java.applet.*; import java.awt.*; import java.net.*; /* <applet code=AppletMethods height=300 width=400> <param name=first value=“KDP” > </applet> */ public class AppletMethods extends Applet { String arg; public void start( ) { arg=getParameter(“first”); } public void paint(Graphics g)
{ setBackground(Color.black); setForeground(Color.white); URL codename=getCodeBase( ); URL docname=getDocumentBase( ); g.drawString(“String = Welcome to KDP”,30,40); g.drawString(“Parameter Value = “+arg,30,70); g.drawString(“Class name= “+codename.toString( ),30,100); g.drawString(“DocumentBase = “+docname.toString(),30,130); } } Output:
Passing Parameters to Applets
Parameters are passed to applets in NAME=VALUE pairs in <PARAM> tags between the opening and closing APPLET tags. Inside the applet, you read the values passed through the PARAM tags with the getParameter() method of the java.applet.Applet class.<param name = parameter_name value = parameter_value>
Complete syntax for the APPLET tag including Param Tag <APPLET CODEBASE = codebaseURL CODE = appletFile ALT = alternateTextNAME = appletInstanceName WIDTH = pixels HEIGHT = pixels ALIGN = alignment > <PARAM NAME = appletAttribute1 VALUE = value> <PARAM NAME = appletAttribute2 VALUE = value> … alternateHTML </APPLET> Example Applet with parameters /* * AppletWithPara.java * */ import java.applet.*; import java.awt.*; /* <applet code=AppletWithPara width=200 height =150> <param name=author value=“J.B.Patel”> <param name=age value=“27”> <param name=designation value=“Lecturer”> <param name=institute value=“SSPC Visnagar”> </applet> */ public class AppletWithPara extends java.applet.Applet { public void paint (Graphics gp) { String au=getParameter(“author”); String ag=getParameter(“age”);
String desg=getParameter(“designation”); String inst=getParameter(“institute”); gp.drawString(“Author:”+au,20,40); gp.drawString(“Age:”+ag,20,70); gp.drawString(“Designation:”+desg,20,100); gp.drawString(“Institute:”+inst,20,130); showStatus(“Parameter methods”); } } Output:
The Coordinate System
Java uses the standard, two-dimensional, computer graphics coordinate system. The first visible pixel in the upper left-hand corner of the applet canvas is (0, 0). Coordinates increase to the right and down.
Graphics Objects
In Java all drawing takes place via a Graphics object. This is an instance of the class java.awt.Graphics. Initially the Graphics object you use will be the one passed as an argument to an applet’s paint() method.
Each Graphics object has its own coordinate system, and all the methods of Graphics including those for drawing Strings, lines, rectangles, circles, polygons and more. Drawing in Java starts with particular Graphics object. You get access to the Graphics object through the paint(Graphics g) method of your applet. Each draw method call will look like g.drawString(“Hello World”, 0, 50) where g is the particular Graphics object with which you’re drawing.
Commonly used methods of Graphics class are as follows:
drawString ( String s, int x, int y ) To output a string to an applet at a specified position. It is called from within update( ) or paint( ).
drawChars ( char c[ ], int start_index, int num_of_char, int x, int y )
To output characters of array to an applet at specified location.
drawChars ( byte c[ ], int start_index, int num_of_char, int x, int y )
To output characters of byte’s array to an applet at specified location.
drawLine (int x1, int y1, int x2, int y2); To draw a line at specific location.
height) location x,y having specific height and width setColor ( Color c ) To set the color of the object fillOval ( int x, int y, int width, int height ) To fill color in Oval
drawRect ( int x, int y, int width, int height )
To draw a rectangle at specific location
fillRect ( int x, int y, int width, int height )
To fill color in rectangle
drawArc (int x, int y, int width, int height, int arcwidth, int archeight ) To draw an Arc fillArc (int x, int y, int width, int height, int arcwidth, int archeight ) To fill color in Arc. setFont ( Font f) To set the font f
Drawing Lines
Drawing straight lines with Java is easy. Just call g.drawLine(x1, y1, x2, y2) where (x1, y1) and (x2, y2) are the endpoints of your lines and g is the Graphics object you’re drawing with. This program draws a line diagonally across the applet. import java.applet.*; import java.awt.*; public class SimpleLine extends Applet { public void paint(Graphics g) { g.drawLine(0, 0, this.getSize().width, this.getSize().height);} } Output
Drawing Rectangles
Drawing rectangles is simple. Start with a Graphics object g and call its drawRect() method:
public void drawRect(int x, int y, int width, int height)
As the variable names suggest, the first int is the left hand side of the rectangle, the second is the top of the rectangle, the third is the width and the fourth is the height. This is in contrast to some APIs where the four sides of the rectangle are given.
import java.applet.*; import java.awt.*; public class RectangleApplet extends Applet { public void paint(Graphics g) { g.drawRect(0, 0, this.getSize().width - 1, this.getSize().height - 1); } } Output
Remember that getSize().width is the width of the applet and getSize().height is its height.
Why was the rectangle drawn only to getSize().height-1 and getSize().width-1?
Remember that the upper left hand corner of the applet starts at (0, 0), not at (1, 1). This means that a 100 by 200 pixel applet includes the points with x coordinates between 0 and 99, not between 0 and 100. Similarly the y coordinates are between 0 and 199 inclusive, not 0 and 200.
Filling Rectangles
The drawRect() method draws an open rectangle, a box if you prefer. If you want to draw a filled rectangle, use the fillRect() method. Otherwise the syntax is identical.
This program draws a filled square in the center of the applet. This requires you to separate the applet width and height from the rectangle width and height. Here’s the code:
import java.applet.*; import java.awt.*;
public class FillAndCenter extends Applet { public void paint(Graphics g) { int appletHeight = this.getSize().height; int appletWidth = this.getSize().width; int rectHeight = appletHeight/3; int rectWidth = appletWidth/3; int rectTop = (appletHeight - rectHeight)/2; int rectLeft = (appletWidth - rectWidth)/2; g.fillRect(rectLeft, rectTop, rectWidth-1, rectHeight-1); } } Output
Ovals and Circles
Java has methods to draw outlined and filled ovals. As you’d probably guess these methods are called drawOval() and fillOval() respectively. As you might not guess they take identical arguments to drawRect() and fillRect(), i.e.
public void drawOval(int left, int top, int width, int height) public void fillOval(int left, int top, int width, int height)
Instead of the dimensions of the oval itself, the dimensions of the smallest rectangle which can enclose the oval are specified. The oval is drawn as large as it can be to touch the rectangle’s edges at their centers. This picture may help: The arguments to drawOval() are the same as the arguments to drawRect(). The first int is the left hand side of the enclosing rectangle, the second is the top of the enclosing rectangle, the third is the width and the fourth is the height. Example: import java.applet.*; import java.awt.*; public class Bullseye extends Applet { public void paint(Graphics g) { int appletHeight = this.getSize().height; int appletWidth = this.getSize().width; for (int i=8; i >= 0; i—) { if ((i % 2) == 0) g.setColor(Color.red); else g.setColor(Color.white);
// Center the rectangle int rectHeight = appletHeight*i/8; int rectWidth = appletWidth*i/8; int rectLeft = appletWidth/2 - i*appletWidth/16; int rectTop = appletHeight/2 - i*appletHeight/16; g.fillOval(rectLeft, rectTop, rectWidth, rectHeight); } } } Output
Using Colors with Applets
The syntax of the constructor to create custom colors: Color ( int red, int green, int blue); Example: new Color (255, 100, 100); // light red Calling a constructor to set the color Color c=new Color (255, 175, 175) g.setColor (c) Color Obtained Red Value Green Value Blue Value White 255 255 255 Black 0 0 0 Light Gray 192 192 192 Dark Gray 128 128 128 Red 255 0 0 Green 0 255 0 Blue 0 0 255 Yellow 255 255 0 Purple 255 0 255 Table of RGB values of common colorsYou create new colors using the same RGB triples that you use to set background colors on web pages. However you use decimal numbers instead of the hex values used by the bgcolor tag. For example medium gray is Color(127, 127, 127). Pure white is Color(255, 255, 255). Pure red is (255, 0, 0) and so on. As with any variable you should give your colors descriptive names. For instance
Color cream = new Color(255, 231, 187); Color lightGreen = new Color(0, 55, 0);
A few of the most common colors are available by name. These are
Color.black Color.gray Color.orange Color.yellow
Color.blue Color.green Color.pink
Color.cyan Color.lightGray Color.red
Color.darkGray Color.magenta Color.white
To change colors you change the color of your Graphics object. Then everything you draw from that point forward will be in the new color until you change it again.
When an applet starts running the color is set to black by default. You can change this to red by calling g.setColor(Color.red). You can change it back to black by calling g.setColor(Color.black). The following code fragment shows how you’d draw a pink String followed by a green one: g.setColor(Color.pink); g.drawString(“This String is pink!”, 50, 25); g.setColor(Color.green); g.drawString(“This String is green!”, 50, 50); Example: AppletColor.java import java.applet.*; import java.awt.*; /* <applet code=AppletColor height=300 width=400> </applet> */ public class AppletColor extends Applet { public void paint(Graphics g) { Color c1=new Color(255,0,255);
Color c2=new Color(128,128,128); g.setColor(c1); int r=c1.getRed( ); int gr=c1.getGreen( ); int b=c1.getBlue( ); g.drawString(“RED = “+r+” GREEN = “+gr+” BLUE = “+b,10,20); c1=c1.darker( ); g.setColor(c1); g.drawString(“RED = “+r+” GREEN = “+gr+” BLUE = “+b,10,40); g.setColor(c2); g.drawString(“RED = “+r+” GREEN = “+gr+” BLUE = “+b,10,60); c2=c2.brighter( ); g.setColor(c2); g.drawString(“RED = “+r+” GREEN = “+gr+” BLUE = “+b,10,80); } } Output:
Fonts
You’ve already seen one example of drawing text in the HelloWorldApplet program ofthe last chapter. You call the drawString() method of the Graphics object. This method is passed the String you want to draw as well as an x and y coordinate. If g is a Graphics object, then the syntax is
g.drawString(String s, int x, int y)
The String is simply the text you want to draw. The two integers are the x and y coordinates of the lower left-hand corner of the String. The String will be drawn above and to the right of this point. However letters with descenders like y and p may have their descenders drawn below the line.
Until now all the applets have used the default font, probably some variation of Helvetica though this is platform dependent. However unlike HTML Java does allow you to choose your fonts. Java implementations are guaranteed to have a serif font like Times that can be accessed with the name “Serif”, a monospaced font like courier that can be accessed with the name “Mono”, and a sans serif font like Helvetica that can be accessed with the name “SansSerif”.
The following applet lists the fonts available on the system it’s running on. It does this by using the getFontList() method from java.awt.Toolkit. This method returns an array of strings containing the names of the available fonts. These may or may not be the same as the fonts installed on your system. It’s implementation dependent whether or not all the fonts a system has are available to the applet. import java.awt.*; import java.applet.*; public class FontList extends Applet { private String[] availableFonts; public void init () { Toolkit t = Toolkit.getDefaultToolkit(); availableFonts = t.getFontList(); } public void paint(Graphics g) { for (int i = 0; i < availableFonts.length; i++) {
g.drawString(availableFonts[i], 5, 15*(i+1)); } } } Output
Drawing Graphics
Example: GraphicsDemo.java import java.awt.*; import java.applet.*; /*<applet code=“GraphicsDemo” width=400 height=400> </applet>*/ public class GraphicsDemo extends Applet { public void paint(Graphics g) { setBackground(Color.pink); setForeground(Color.blue); Font f=new Font(“Arial”,Font.ITALIC,10);g.setFont(f); g.drawLine(20,20,50,50); g.drawString(“Line”,20,70); g.drawRect(100,20,50,50); g.drawString(“Rectangle”,100,100); g.fillRoundRect(200,20,80,50,10,10); g.drawString(“Filled Round Rect”,200,100); g.drawOval(20,100,50,80); g.drawString(“Oval”,25,200); g.fillOval(100,130,50,50); g.drawString(“Circle”,110,200); g.drawString(“WELCOME TO GRAPHICS”,130,350); } } Output:
PRACTICAL 1: WRITE AN APPLET THAT DRAWS A CIRCLE. THE
DIMENSION
OF
THE
APPLET
SHOULD
BE
500
X300
PIXELS. T
HECIRCLE
SHOULD
BE
CENTERED
IN
THE
APPLET
AND
HAVE
A
RADIUS OF 100 PIXELS. DISPLAY YOUR NAME CENTERED IN A
CIRCLE
. (USING DRAWOVAL ()
METHOD)
After performing this practical student will be able to: Learn about Applet. Develop an Applet Program in JAVA Execute an Applet Program in JAVA using AppletViewer Execute an Applet in Web Browser Learn How to use Graphics Class to draw Circle. LEARNING OUTCOMES Explain & Practice Graphic Drawing method drawOval() to draw circle. ASSUMPTIONS Oracle JDK installed Editor Like notepad, Jcreator available for program development
ENVIRONMENT VARIABLES LIKE JAVA_HOME, PATH, CLASSPATH ARE CONFIGURED.CODE
import java.awt.*; import java.applet.*; /* <applet code=CenterCircle height=500 width=300> </applet> */ public class CenterCircle extends Applet { int w,h; public void init() { w=getWidth(); h=getHeight(); } public void paint(Graphics g) { g.setColor (Color.blue); g.drawOval ((w/2)-50,(h/2)-50,100,100); g.drawString(“J.B.Patel”, w/2,h/2);
g.setColor (Color.green);
showStatus (“This applet draws circle in the center of the applet”); }
} OUTPUT
P
RACTICAL2: D
RAWTEN
RED
CIRCLES
IN
A
VERTICAL
COLUMN
IN THE CENTER OF THE APPLET. SPECIFIC OBJECTIVES After performing this practical student will be able to: Develop an Applet Program in JAVA Execute an Applet Program in JAVA using Appletviewer or web browser Learn How to use Graphics Class to draw Circle. LEARNING OUTCOMES Explain & Practice Graphic Drawing method drawOval () to draw circles pattern and setColor() to fill Circle. ASSUMPTIONS Oracle JDK installed Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, Path, Classpath are configured. CODE import java.awt.*; import java.applet.*; /* <applet code=TenRed height=500 width=300> </applet> */ public class TenRed extends Applet { int w,h; public void init()
{ w=getWidth(); h=getHeight(); } public void paint(Graphics g) { int count=0; g.setColor (Color.red); for(int i=h;i>0;i=i-50) { g.fillOval(w/2-25,h-i,50,50); count++; if (count==10) break; } } } OUTPUT
P
RACTICAL3: B
UILTAN
APPLET
THAT
DISPLAYS
A
HORIZONTAL
RECTANGLE
IN
ITS
CENTER
. L
ETTHE
RECTANGLE
FILL
WITH
COLOR
FROM
LEFT
TO
RIGHT
.
SPECIFIC OBJECTIVES After performing this practical student will be able to: Develop an Applet Program in JAVA Execute an Applet Program in JAVA using Appletviewer or web browser Learn How to use Graphics Class to draw and fill Rectangles. LEARNING OUTCOMES Explain & Practice Graphic Drawing method drawRect() and fillRect() to create Progress bar. ASSUMPTIONS Oracle JDK installed Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, Path, Classpath are configured. CODE import java.awt.*; import java.applet.*; /* <applet code=FillRectGrad height=500 width=300> </applet> */ public class FillRectGrad extends Applet { int w,h, x1=100,x2,y1=50,y2=150, flag=0; Thread t; Graphics g1; public void init() { w=getWidth(); h=getHeight(); } public void paint(Graphics g) { g.setColor(java.awt.Color.red); g.drawRect(100,50,300,150); for(x2=100;x2<=300;x2=x2+2) { try{ Thread.sleep(1000); g.fillRect(x1,y1,x2,y2); } catch(Exception e) {} } }
} OUTPUT
P
RACTICAL4: W
RITEAN
APPLET
THAT
DISPLAYS
THE
POSITION
OF THE
MOUSE
AT
THE
UPPER
LEFT
CORNER
OF
THE
APPLET
WHEN
IT
IS DRAGGED OR MOVED. DRAW A 10X10 PIXEL RECTANGLE FILED WITH BLACK
AT
THE
CURRENT
MOUSE
POSITION
.
SPECIFIC OBJECTIVES After performing this practical student will be able to: Develop an Applet Program in JAVA Execute an Applet Program in JAVA using Appletviewer or web browser Learn How to handle Mouse Events using MouseListener and MouseMotionListeners interfaces. LEARNING OUTCOMES Explain & Practice Mouse Events like Move, Drag and Current Position using init(), repaint() methods. ASSUMPTIONS Oracle JDK installed Editor Like notepad, Jcreator available for program development
Environment variables like JAVA_Home, Path, Classpath are configured. CODE import java.awt.event.*; import java.applet.*; import java.awt.*; /* <applet code=MousePosition height=300 width=400> </applet> */
public class MousePosition extends Applet implements MouseListener, MouseMotionListener { String s=””; int mx=0, my=0; public void init( ) { addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent m) { } public void mouseEntered(MouseEvent m) { } public void mouseExited(MouseEvent m) { } public void mousePressed(MouseEvent m) { }
public void mouseReleased(MouseEvent m) { } public void mouseDragged(MouseEvent m) { mx=m.getX( ); my=m.getY( ); s=“Dragging:”; repaint( ); } public void mouseMoved(MouseEvent m) { mx=m.getX( ); my=m.getY( ); s=“Moving:”; repaint( ); } public void paint(Graphics g) { g.drawString(“Mouse”+s+mx+”,”+my, 10, 10); g.setColor (Color.red); g.drawRect ( mx,my, 10, 10); } } OUTPUT: When Moving When Dragging
P
RACTICAL5: W
RITEAN
APPLET
THAT
CONTAINS
ONE
BUTTON
.
I
NITIALIZETHE
LABEL
ON
THE
BUTTON
TO
“
START”,
WHENTHE
USER PRESSES THE BUTTON CHANGE THE LABEL BETWEEN THESE TWO VALUES
EACH
TIME
THE
BUTTON
IS
PRESSED
.
After performing this practical student will be able to: Develop a GUI Applet Program in JAVA using AWT Button Control Execute an Applet Program in JAVA using Appletviewer or web browser Learn How to handle AWT Button Events using ActionListener interfaces. LEARNING OUTCOMES Explain & Practice AWT Button Events like using actionPerformed() methods. ASSUMPTIONS Oracle JDK installed Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, Path, Classpath are configured. CODE import java.awt.*; import java.applet.*; import java.awt.event.*; import java.lang.String; /*<applet code=ButtonsDemo.class width=300 height=300></applet>*/ public class ButtonsDemo extends java.applet.Applet implements ActionListener{ Button b1; public void init() { b1=new Button(“Start”); add(b1); b1.addActionListener(this); } public void actionPerformed(ActionEvent e) { if(e.getSource()==b1) { String s; s=b1.getLabel(); if(s==“Start”)
b1.setLabel(“Stop”); else b1.setLabel(“Start”); } } } OUTPUT:
When You Press Stop Button
When You Press Start Button
P
RACTICAL6: W
RITEAN
APPLET
THAT
USES
THE
MOUSE
LISTENER
,
WHICHOVERRIDES
ONLY
TWO
METHODS
WHICH
ARE
MOUSE
P
RESSED ANDMOUSE
R
ELEASED.
SPECIFIC OBJECTIVES After performing this practical student will be able to: Develop an Applet Program in JAVA Execute an Applet Program in JAVA using Appletviewer or web browser Learn How to handle Mouse Events using MouseListener and MouseMotionListeners interfaces. LEARNING OUTCOMES Explain & Practice Mouse Events like Press and Released using mousePressed(), mousePressed() methods. ASSUMPTIONS Oracle JDK installed Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, Path, Classpath are configured. CODE import java.awt.event.*; import java.applet.*; import java.awt.*; /* <applet code=MouseState height=300 width=400>
</applet> */
public class MouseState extends Applet implements MouseListener, MouseMotionListener { String s=””; int mx=0, my=0; public void init( ) { addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent m) { } public void mouseEntered(MouseEvent m){ } public void mouseExited(MouseEvent m) { } public void mousePressed(MouseEvent m) { mx=m.getX( ); my=m.getY( ); s=” Pressed:”; repaint( ); } public void mouseReleased(MouseEvent m) { mx=m.getX( ); my=m.getY( ); s=” Released:”; repaint( ); } public void mouseDragged(MouseEvent m) { } public void mouseMoved(MouseEvent m) { } public void paint(Graphics g)
{ g.drawString(“Mouse”+s+mx+”,”+my, 10, 10); g.setColor (Color.red); g.drawRect ( mx,my, 10, 10); //g.drawString(“Mouse moving at: “+mx+”,”+my,20,40); } } OUTPUT: When You Press Mouse When You Release Mouse
E
XERCISE:
WRITE AN APPLET THAT DISPLAYS A SIMPLE MESSAGE: “HELLO APPLET”.
Code:
Output:
WRITE A JAVA PROGRAM TO DRAW LINES, RECTANGLES AND OVALS.
Code:
Output:
WRITE AN APPLET THAT DRAWS A HUMAN FACE WITH ARC AND OVAL.
Code:
Output:
TO DEVELOP A PROGRAM TO SET THE GIVEN STRING IN A DESIRED FONT AND COLOR.(FONT:
ARIEL, BOLD AND
POINT SIZE 20,COLOR:PINK)
Code:
Output:
UNIT 2
GENERAL OBJECTIVES After performing this practical student will be able to: Learn about Windows AWT Controls. Develop an AWT Program in JAVA Execute an AWT Program in JAVA Learn How to use Graphics Class to draw Shapes. LEARNING OUTCOMES Explain & Practice AWT Controls using Applets and Frames. ASSUMPTIONS Oracle JDK installed Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, Path, Classpath are configured.I
NTRODUCTIONAbstract Window Toolkit
The AWT contains numerous classes and methods that allow us to create and manage windows. Although the main purpose of the AWT is to support applet windows, it can also be used to create stand-alone windows that run in a GUI environment, such as Windows.AWT Classes
The AWT classes are contained in the java.awt package. It is one of Java’s largest packages. Fortunately, because it is logically organized in a top- down, hierarchical fashion, it is easier to understand and use than you might at first believe.
AWTEvent Encapsulates
AWT
events.
AWTEventMulticaster Dispatches events to
multiple listeners.
BorderLayout The border layout
manager.
Border
layouts
use
five
components: North, South, East, West, and
Center.
Button Creates a push button control.
Canvas A
blank,
semantics-free
window.
CardLayout The card layout manager.
Card layouts emulate index cards. Only the
one on top is showing.
Checkbox Creates a check box control.
CheckboxGroup Creates a group of check box
controls. CheckboxMenuItem Creates an on/off
menu item.
Choice Creates a pop-up list.
Color Manages colors in a portable,
independent fashion.
Component An abstract super-class for various AWT
components.
Container A subclass of Component that can
components.
Cursor Encapsulates
a
bitmapped
cursor. Dialog Creates a dialog window.
Dimension Specifies the dimensions of
an object. The width is stored in width, and
the height is stored in height.
Event Encapsulates
events.
EventQueue Queues events.
FileDialog Creates a window from which a file can
be
selected.
FlowLayout
components left to right, top to bottom.
Font Encapsulates a type font.
FontMetrics Encapsulates
various
information
related
to
a
font.
This
information helps you display text in a
window.
Frame Creates a standard window that
has a title bar, resize corners, and a menu bar.
Graphics Encapsulates the graphics
context. This context is used by the various
output methods to display output in a window.
GraphicsDevice Describes
a
graphics device such as a screen or printer.
GraphicsEnvironment Describes the
collection of available Font and
GraphicsDevice objects.
GridBagConstraints Defines various constraints
GridBagLayout class.
GridBagLayout The grid bag layout
manager.
Grid
bag
layout
displays
components subject to the
constraints specified by
GridBagConstraints.
GridLayout The grid layout manager.
components in a two-dimensional grid.
Image Encapsulates graphical images.
container. Label Creates a label that displays a
string.
List Creates a list from which the user
can choose. Similar to the standard Windows
list box.
MediaTracker Manages
media
objects. Menu Creates a pull-down
menu. MenuBar Creates a menu bar.
MenuComponent An abstract class implemented by
various menu classes. MenuItem Creates a menu item.
MenuShortcut Encapsulates a keyboard shortcut
for a menu item. Panel The simplest concrete subclass
of Container.
Point Encapsulates a Cartesian coordinate pair, stored
in x
and y.
Polygon Encapsulates a polygon.
PopupMenu Encapsulates
a
pop-up
menu.
PrintJob An abstract class that represents a
print job. Rectangle Encapsulates a rectangle.
Robot Supports automated testing of AWT- based
applications. Scrollbar Creates a scroll bar control.
ScrollPane A container that provides
horizontal and/or vertical scroll bars for
another component.
GUI widgets such as windows, scroll bars,
text, and others.
TextArea Creates
a
multiline
edit
control. TextComponent A superclass for
TextArea and TextField. TextField Creates a
single-line edit control.
Toolkit Abstract class implemented by
the AWT. Window Creates a window with
no frame, no menu bar,
Window Fundamentals
The AWT defines windows according to a class hierarchy that adds functionality and specificity with each level. The two most common windows are those derived from Panel, which is used by applets, and those derived from Frame, which creates a standard window. Much of the functionality of these windows is derived from their parent classes. Thus, a description of the class hierarchies relating to these two classes is fundamental to their understanding. Figure below shows the class hierarchy for Panel and Frame.Working with Frame Windows
After the applet, the type of window we will most often create is derived from Frame. We will use it to create child windows within applets, and top-level or child windows for applications. It creates a standard-style window. Following are two of Frame’s constructors:
Frame( );
Frame(String title);
The first form creates a standard window that does not contain a title. The second form creates a window with the title specified by title. Note that we cannot specify the dimensions of the window. Instead, we must set the size of the window after it has been created.
Creating a Frame Window in an Applet
This example overrides the applet window’s start( ) and stop( ) method s so that they show and hide the child window, respectively. It also causes the child window to be shown when the browser returns to the applet. SampleFrame.java /*<applet code=“AppletFrame” width=300 height=50> </applet> */ class SampleFrame extends Frame { SampleFrame(String title) { super(title); } public void paint(Graphics g) { g.drawString(“This is in frame window”, 10, 40); } } public class AppletFrame extends Applet { Frame f; public void init() { f = new SampleFrame(“A Frame Window”); f.setSize(250, 250); f.setVisible(true); } public void start() { f.setVisible(true); } public void stop() { f.setVisible(false); }
public void paint(Graphics g) { g.drawString(“This is in applet window”, 10, 20); } } Output:
Using AWT Controls, Layout Managers and Menus
Controls are components that allow a user to interact with his application in various ways—for example; a commonly used control is the push button. Control Fundamentals The AWT supports the following types of controls: Labels Push buttons Check boxes Choice lists Lists Scroll bars Text Area Text Field These controls are subclasses of Component. Adding and Removing Controls In order to include a control in a window, we must add it to the window. So, we must first create an instance of the desired control and then add it to a window by calling add( ), which is defined by Container. The add( ) method has several forms. The following form is the one that is used for the first part of this chapter: Component add(Component compObj) Here, compObj is an instance of the control that we want to add. A reference to
compObj is returned. Once a control has been added, it will automatically be visible whenever its parent window is displayed. Sometimes we will want to remove a control from a window when the control is no longer needed. For doing this, call remove( ). This method is also defined by Container. It has this general form:
void remove(Component obj)
Here, obj is a reference to the control that we want to remove. We can remove all controls by calling removeAll( ).
Responding to Controls
Except for labels, which are passive controls, all controls generate events when they are accessed by the user. For example, when the user clicks on a push button, an event is sent that identifies the push button. In general, our program simply implements the appropriate interface and then registers an event listener for each control that we need to monitor.
Labels
Label defines the following constructors: Label( ) ; Label(String str) ; Label(String str, int how); We can set or change the text in a label by using the setText( ) method. We can obtain the current label by calling getText( ). These methods are shown here: void setText(String str) ; String getText( ); To obtain the current alignment, call getAlignment( ). The methods are as follows: void setAlignment(int how); int getAlignment( ); Example: The following example creates three labels and adds them to an applet. // Demonstrate Labels. LabelDemo.java import java.awt.*; import java.applet.*; /* <applet code=“LabelDemo” width=300 height=200> </applet> */public class LabelDemo extends Applet { public void init() { Label one = new Label(“One”); Label two = new Label(“Two”); Label three = new Label(“Three”); // add labels to applet window add(one); add(two); add(three); } } Output:
Buttons
The most widely used control is the push button. A push button is a component that contains a label and that generates an event when it is pressed. Push buttons are objects of type Button. Button defines these two constructors: Button( ); Button(String str); Example: Using button control //ButtonDemo.java import java.awt.*; import java.applet.*; /* <applet code=“ButtonDemo” width=250 height=150></applet> */ public class ButtonDemo extends Applet { String msg = ””; Button yes, no, maybe; public void init() { yes = new Button(“Yes”); no = new Button(“No”); maybe = new Button(“Undecided”); add(yes); add(no); add(maybe); } public void paint(Graphics g) { g.drawString(msg, 6, 100); } } Output:
Check Boxes
A check box is a control that is used to turn an option on or off. Check boxes can beused individually or as part of a group. Check boxes are objects of the Checkbox class. Checkbox supports these constructors: Checkbox( ); Checkbox(String str); Checkbox(String str, boolean on) Checkbox(String str, boolean on, CheckboxGroup cbGroup); Checkbox(String str, CheckboxGroup cbGroup, boolean on) The first form creates a check box whose label is initially blank. The state of the check box is unchecked. The second form creates a check box whose label is specified by str. The state of the check box is unchecked. The third form allows us to set the initial state of the check box. If on is true, the check box is initially checked; otherwise, it is cleared.
The fourth and fifth forms create a check box whose label is specified by str and whose group is specified by cbGroup. If this check box is not part of a group, then cbGroup must be null. The value of on determines the initial state of the check box.
In order to retrieve the current state of a check box, call getState( ). For setting its state, call setState( ). We can obtain the current label associated with a check box by calling getLabel( ). For setting the label, setLabel( ) is used. These methods are as follows: boolean getState( ); void setState(boolean on); String getLabel( ); void setLabel(String str); Example: Demonstrate check boxes. //CheckboxDemo.java import java.awt.*; import java.applet.*; /* <applet code=“CheckboxDemo” width=250 height=200> </applet> */ public class CheckboxDemo extends Applet { String msg = ””;
Checkbox Win98, winNT, solaris, mac; public void init() { Win98 = new Checkbox(“Windows 98/XP”, null, true); winNT = new Checkbox(“Windows NT/2000”); solaris = new Checkbox(“Solaris”); mac = new Checkbox(“MacOS”); add(Win98); add(winNT); add(solaris); add(mac); } public void paint(Graphics g) { } } Output:
Checkbox Group/Option Button
Only one check box in the group can be checked at any one time. These check boxes are often called radio buttons. For creating a set of mutually exclusive check boxes, we must first define the group to which they will belong and then specify that group when we construct the check boxes. Check box groups are objects of type CheckboxGroup. Only the default constructor is defined, which creates an empty group.We can determine which check box in a group is currently selected by calling getSelectedCheckbox( ). We can set a check box by calling setSelectedCheckbox( ). These methods are as follows: Checkbox getSelectedCheckbox( ) void setSelectedCheckbox(Checkbox wh) Example: Here is a program that uses check boxes that are part of a group. //CBGroup.java import java.awt.*;import java.applet.*; /* <applet code=“CBGroup” width=250 height=200> </applet> */ public class CBGroup extends Applet { String msg = ””; Checkbox Win98, winNT, solaris, mac; CheckboxGroup cbg; public void init() { cbg = new CheckboxGroup(); Win98 = new Checkbox(“Windows 98/XP”, cbg, true); winNT = new Checkbox(“Windows NT/2000”, cbg, false); solaris = new Checkbox(“Solaris”, cbg, false); mac = new Checkbox(“MacOS”, cbg, false); add(Win98); add(winNT); add(solaris); add(mac); } public void paint(Graphics g) { msg = “Current selection: “; msg += cbg.getSelectedCheckbox().getLabel(); g.drawString(msg, 6, 100);
} } Output:
Choice Controls
The Choice class is used to create a pop-up list of items from which the user may choose. Choice only defines the default constructor, which creates an empty list. In order to add a selection to the list, add( ) is used. It has this general form: void add(String name) Here, name is the name of the item being added. In order to determine which item is currently selected, we may call either any of the following methods: String getSelectedItem( ); int getSelectedIndex( );
The getSelectedItem( ) method returns a string containing the name of the item. getSelectedIndex( ) returns the index of the item. The first item is at index 0. By default, the first item added to the list is selected. For obtaining the number of items in the list, call getItemCount( ). We can set the currently selected item using the select( ) method with either a zero-based integer index or a string that will match a name in the list. These methods are shown here:
int getItemCount( ); void select(int index); void select(String name);
Given an index, we can obtain the name associated with the item at that index by calling getItem( ), which has this general form:
String getItem(int index); Example: Demonstrate Choice lists. //ChoiceDemo.java import java.awt.*; import java.applet.*; /* <applet code=“ChoiceDemo” width=300 height=180> </applet> */ public class ChoiceDemo extends Applet { Choice os, browser; String msg = ””; public void init() { os = new Choice(); browser = new Choice();
os.add(“Windows 98/XP”); os.add(“Windows NT/2000”); os.add(“Solaris”); os.add(“MacOS”); browser.add(“Netscape 3.x”); browser.add(“Netscape 4.x”); browser.add(“Netscape 5.x”); browser.add(“Netscape 6.x”);
browser.add(“Internet Explorer 4.0”); browser.add(“Internet Explorer 5.0”); browser.add(“Internet Explorer 6.0”); browser.add(“Lynx 2.4”); browser.select(“Netscape 4.x”); add(os); add(browser); } public void paint(Graphics g) { } } Output:
Lists
The List class provides a compact, multiple-choice, scrolling selection list. The List object can be constructed to show any number of choices in the visible Window. It can also be created to allow multiple selections. List provides these constructors: List( ); List(int numRows); List(int numRows, boolean multipleSelect); The first version creates a List control that allows only one item to be selected at any one time. In the second form, the value of numRows specifies the number of entries in the list that will always be visible (others can be scrolled into view as needed). In the third form, if multipleSelect is true, then the user may select two or more items at a time. If it is false, then only one item may be selected. For adding a selection to the list, we can call add( ). It has the following two forms: void add(String name); void add(String name, int index); Here, name is the name of the item added to the list. The first form adds items to the end of the list. The second form adds the item at the index specified by index.
For lists that allow multiple selection, we must use either getSelectedItems( ) or getSelectedIndexes( ), shown here, to determine the current selections:
String[ ] getSelectedItems( ); int[ ] getSelectedIndexes( );
The getSelectedItems( ) returns an array containing the names of the currently selected items. getSelectedIndexes( ) returns an array containing the indexes of the currently selected items. In order to obtain the number of items in the list, call getItemCount( ). We can set the currently selected item by using the select( ) method with a zero-based integer index. These methods are shown here:
int getItemCount( ); void select(int index);
Given an index, we can obtain the name associated with the item at that index by calling getItem( ), which has this general form: String getItem(int index) Here, index specifies the index of the desired item. Example: List Demonstration //ListDemo.java import java.awt.*; import java.applet.*; /* <applet code=“ListDemo” width=300 height=180> </applet> */ public class ListDemo extends Applet { List os, browser; String msg = ””; public void init() {
os = new List(4, true); browser = new List(4, false); os.add(“Windows 98/XP”); os.add(“Windows NT/2000”); os.add(“Solaris”); os.add(“MacOS”); browser.add(“Netscape 3.x”); browser.add(“Netscape 4.x”); browser.add(“Netscape 5.x”); browser.add(“Netscape 6.x”);
browser.add(“Internet Explorer 4.0”);
browser.add(“Internet Explorer 5.0”); browser.add(“Internet Explorer 6.0”); browser.add(“Lynx 2.4”); browser.select(1); add(os); add(browser); } public void paint(Graphics g) { int idx[]; msg = “Current OS: “; idx = os.getSelectedIndexes(); for(int i=0; i<idx.length; i++) msg += os.getItem(idx[i]) + ” “;
g.drawString(msg, 6, 120); msg = “Current Browser: “; msg += browser.getSelectedItem(); g.drawString(msg, 6, 140); } } Output:
TextField
TextComponentTextArea
TextField
Fig. Text components hierarchy
The TextField class implements a single-line text-entry area, usually called an edit control. Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and paste keys, and mouse selections. TextField is a subclass of TextComponent. TextField defines the following constructors: TextField( ); TextField(int numChars); TextField(String str); TextField(String str, int numChars); The first version creates a default text field. The second form creates a text field that is numChars characters wide. The third form initializes the text field with the string contained in str. The fourth form initializes a text field and sets its width. TextField (and its superclass TextComponent) provides several methods that allow us to utilize a text field. In order to obtain the string currently contained in the text field, we can use getText( ). For setting the text, we call setText( ). These methods are as follows: String getText( ); void setText(String str); Here, str is the new string. The user can select a portion of the text in a text field. Also, we can select a portion of text under program control by using select( ). Our program can obtain the currently selected text by calling the getSelectedText( ). These methods are shown here:
String getSelectedText( );
void select(int startIndex, int endIndex);
The getSelectedText( ) returns the selected text. The select( ) method selects the characters beginning at startIndex and ending at endIndex–1. We can control whether the contents of a text field may be modified by the user by calling setEditable( ). We can determine editability by calling isEditable( ). These methods are shown here:
boolean isEditable( )
void setEditable(boolean canEdit)
The isEditable( ) returns true if the text may be changed and false if not. In setEditable( ), if canEdit is true, the text may be changed. If it is false, the text cannot be altered. There may be times when we will want the user to enter text that is not displayed, such as a password. You can disable the echoing of the characters as they are typed by calling setEchoChar( ). This method specifies a single character that the TextField will display when characters are entered (thus, the actual characters typed will not be shown). We can check a text field to see if it is in this mode with the echoCharIsSet( ) method. We
can retrieve the echo character by calling the getEchoChar( ) method. These methods are as follows: void setEchoChar(char ch); boolean echoCharIsSet( ); char getEchoChar( ); Here, ch specifies the character to be echoed. Example: Using TextField //TextFieldDemo.java import java.awt.*; import java.applet.*; /* <applet code=“TextFieldDemo” width=380 height=150> </applet> */ public class TextFieldDemo extends Applet { TextField name, pass; public void init() {
Label namep = new Label(“Name: “, Label.RIGHT); Label passp = new Label(“Password: “, Label.RIGHT); name = new TextField(12); pass = new TextField(8); pass.setEchoChar(‘?’); add(namep); add(name); add(passp); add(pass); } public void paint(Graphics g) { } } Output:
TextArea
Sometimes a single line of text input is not enough for a given task. To handle these situations, the AWT includes a simple multiline editor called TextArea. Following are the constructors for TextArea: TextArea( ); TextArea(int numLines, int numChars); TextArea(String str); TextArea(String str, int numLines, int numChars); TextArea(String str, int numLines, int numChars, int sBars); Here, numLines specifies the height, in lines, of the text area, and numChars specifies its width, in characters. Initial text can be specified by str. In the fifth form we can specify the scroll bars that we want the control to have. sBars must be one of these values: SCROLLBARS_BOTH SCROLLBARS_NONE SCROLLBARS_HORIZONTAL_ONLY SCROLLBARS_VERTICAL_ONLYTextArea is a subclass of TextComponent. Therefore, it supports the getText( ), setText(), getSelectedText(), select( ), isEditable( ), and setEditable( ) methods described in the preceding section. TextArea adds the following methods: void append(String str); void insert(String str, int index); void replaceRange(String str, int startIndex, int endIndex); The append( ) method appends the string specified by str to the end of the current text. The insert( ) inserts the string passed in str at the specified index. In order to replace text, we call replaceRange( ). It replaces the characters from startIndex to endIndex–1, with the replacement text passed in str. Text areas are almost self-contained controls.
Example: Using TextArea Control //TextAreaDemo.java import java.awt.*; import java.applet.*; /* <applet code=“TextAreaDemo” width=300 height=250> </applet> */ public class TextAreaDemo extends Applet { public void init() { String val = “There are two ways of constructing ” + “a software design.\n” + “One way is to make it so simple\n” + “that there are obviously no deficiencies.\n” +
“And the other way is to make it so complicated\n” + “that there are no obvious deficiencies.\n\n” +
” -C.A.R. Hoare\n\n” +
“There’s an old story about the person who wished\n” +
“his computer were as easy to use as his telephone.\n” + “That wish has come true,\n” +
“since I no longer know how to use my telephone.\n\n” + ” -Bjarne Stroustrup, AT&T, (inventor of C++)”; TextArea text = new TextArea(val, 10, 30); add(text); } } Output:
Layout Managers
All of the components that we have shown so far have been positioned by the default layout manager. A layout manager automatically arranges our controls within a window by using some type of algorithm. Each Container object has a layout manager associated with it. A layout manager is an instance of any class that implements the LayoutManager interface. The layout manager is set by the setLayout( ) method. If no call to setLayout( ) is made, then the default layout manager is used. Whenever a container is resized (or sized for the first time), the layout manager is used to position each of the components within it. Fig. Layout Managers at work The setLayout( ) method has the following general form: void setLayout(LayoutManager layoutObj); Here, layoutObj is a reference to the desired layout manager. If we wish to disable the layout manager and position components manually, pass null for layoutObj. If we do this, we will need to determine the shape and position of each component manually, using the setBounds( ) method defined by Component.Each layout manager keeps track of a list of components that are stored by their names. The layout manager is notified each time we add a component to a container.
Whenever the container needs to be resized, the layout manager is consulted via its minimumLayoutSize( ) and preferredLayoutSize( ) methods. Each component that is being managed by a layout manager contains the getPreferredSize( ) and
getMinimumSize( ) methods. These return the preferred and minimum size required to display each component. Java has several predefined LayoutManager classes, several of which are described next. We can use the layout manager that best fits our application.
FlowLayout
FlowLayout is the default layout manager. Components are laid out from the upper-left corner, left to right and top to bottom. When no more components fit on a line, the next one appears on the next line. A small space is left between each component, above and below, as well as left and right. Here are the constructors for FlowLayout:
FlowLayout( );
FlowLayout(int how);
FlowLayout(int how, int horz, int vert);
The first form creates the default layout, which centers components and leaves five pixels of space between each component. The second form lets us specify how each line is aligned. Valid values for how are as follows: FlowLayout.LEFT FlowLayout.CENTER FlowLayout.RIGHT These values specify left, center, and right alignment, respectively. The third form allows us to specify the horizontal and vertical space left between components in horz and vert, respectively. Here is a version of the CheckboxDemo applet shown earlier, modified so that it uses left-aligned flow layout. // FlowLayoutDemo.java import java.awt.*; import java.applet.*; /* <applet code=“FlowLayoutDemo” width=400 height=200> </applet> */ public class FlowLayoutDemo extends Applet { String msg = ””; Checkbox Win98, winNT, solaris, mac;
public void init() { Win98 = new Checkbox(“Windows 98/XP”, null, true); winNT = new Checkbox(“Windows NT/2000”); solaris = new Checkbox(“Solaris”); mac = new Checkbox(“MacOS”); setLayout(new FlowLayout(FlowLayout.CENTER)); add(Win98); add(winNT); add(solaris); add(mac); } public void paint(Graphics g) { } } Output:
BorderLayout
The BorderLayout class implements a common layout style for top-level windows. It has four narrow, fixed-width components at the edges and one large area in the center. The four sides are referred to as north, south, east, and west. The middle area is called the center. Here are the constructors defined by BorderLayout: BorderLayout( ); BorderLayout(int horz, int vert); The first form creates a default border layout. The second allows us to specify the horizontal and vertical space left between components in horz and vert, respectively. BorderLayout defines the following constants that specify the regions: BorderLayout.CENTERBorderLayout.SOUTH BorderLayout.EAST BorderLayout.WEST BorderLayout.NORTH When adding components, we will use these constants with the following form of add( ), which is defined by Container: void add(Component compObj, Object region); Here, compObj is the component to be added, and region specifies where the component will be added. Here is an example of a BorderLayout with a component in each layout area: // BorderLayoutDemo.java import java.awt.*; import java.applet.*; /* <applet code=“BorderLayoutDemo” width=400 height=200> </applet> */ public class BorderLayoutDemo extends Applet { public void init() { setLayout(new BorderLayout()); add(new Button(“This is across the top.”), BorderLayout.NORTH); add(new Label(“The footer message might go here.”), BorderLayout.SOUTH); add(new Button(“Right”), BorderLayout.EAST); add(new Button(“Left”), BorderLayout.WEST); String msg = “The reasonable man adapts ” + “himself to the world;\n” +
“the unreasonable one persists in ” + “trying to adapt the world to himself.\n” + “Therefore all progress depends ” +
“on the unreasonable man.\n\n” + ” - George Bernard Shaw\n\n”; add(new TextArea(msg),
BorderLayout.CENTER); } } Output:
P
RACTICAL7: W
RITEA
PROGRAM
THAT
HAS
ONLY
ONE
BUTTON
IN
THE
FRAME
,
CLICKINGON
THE
BUTTON
CYCLES
THROUGH
THE
COLORS: RED->GREEN->BLUE->AND SO ON. ONE COLOR CHANGE PER
CLICK
. (
USEGET
B
ACKG
ROUND()
METHODTO
GET
THE
CURRENT COLOR
)
SPECIFIC OBJECTIVES After performing this practical student will be able to: Develop an AWT Program in JAVA using Button Control Learn How to handle Button Events using ActionListener interfaces. LEARNING OUTCOMES Explain & Practice Button Events. ASSUMPTIONS Oracle JDK installed Editor Like notepad, Jcreator available for program development Environment variables like JAVA_Home, Path, Classpath are configured. CODE import java.awt.*;import java.applet.*; import java.awt.event.*; import java.lang.String; class ChangeColor extends Applet implements ActionListener { Button b1; public void init() { b1=new Button(“Change Color”); add(b1); b1.addActionListener(this); } public void actionPerformed(ActionEvent e) { if(e.getSource()==b1) { String s; s=b1.getBackground(); if(s==“Change Color”) { this.setBackground(Color.RED); b1.setLabel(“Green”); } if(s==“Green”) { this.setBackground(Color.GREEN); b1.setLabel(“Blue”); } if(s==“Blue”) { this.setBackground(Color.BLUE); b1.setLabel(“Change Color”);