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

Chapter 01: Introduction to Abstract Window Toolkit

1.1 Working with Windows and AWT AWT classes Windows Fundamentals Working with frame windows Creating a frame window in applet Creating windowed program Display information within a window

1.2

Working with Graphics


Working with color Setting the paint mode Working with Fonts Managing text output using Font Metrics Exploring text and graphics

1.3 Using

AWT Controls, Fundamentals

Layout

Managers

and

Menus

Control

Labels Using Buttons Applying CheckBoxes CheckBox Group Choice Controls Using Lists Managing Scroll Bars Using Text Field Using Text Area Understanding Layout Managers Menu Bars and Menu Dialog Boxes File Dialog Handling events by extending AWT components Exploring the Controls, Menus, and Layout Managers

Introduction AWT contains numerous classes and methods that allow you to create and manage windows. 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.

Working with Windows and AWT AWT Classes The AWT classes are contained in the java.awt package. It is one of the Javas largest packages. Class Applet Button Canvas Description Creates an applet This class used to create a label button It represents the blank rectangular area on screen. It can draw or trap input events from the user. It is a graphical component. It has two states. True state that means "on" or false sate that means "off". This class represents pop-up menu to user's choice. It is a component which contains the text in container. It has pull-down menu components that displayed as like menu bar. Creates a combobox This component uses by the uses and it choose the list of item. This class defines top-level window and it designs the any area of border This is a top label window. It has title and border. It can be used for taking some input of users. This is a simplest container class. It includes components and other panels. It extends Container and implements to Accessible. It extends the Menu and specifies the positions of components. Creates a radiobutton This class provides the user interface components and also include the scroll bar which implements the Adjustable interface.

Checkbox

Choice Label Menu ComboBo x List Frame Dialog

Panel

PopupMe nu RadioButt on Scrollbar

ScrollPan e

It includes the horizontal and vertical scrolling for a single child components. The horizontal and vertical state represented by the ScrollPaneAdjustable objects. It displays multi line text. It has text component and It allows to editing a single line of text. Creates a text surface It is a top-level window. It has not borders and menubar. It capable for generating the window events like: WindowOpend, WindowClosed.

TextArea TextField TextPane Window

Windows Fundamentals
Q. Give meaning of following terms in windows components. [W-09, W-10] 1. Frame 2. Panel. Q. Give the meanings of following terms. [S-11] 1. Component 2. Panel. The AWT defines windows according to the class hierarchy that adds functionality and specificity with each level. The 2 most common windows are those derived from Panel, which is used by applets, and those derived from Frame which creates a standard window. Most of the functionality of these windows is taken from their parent classes. The class hierarchy for Panel and Frame

Component : At the top of the AWT hierarchy is the component class. Component is an abstract class that contains all of the attributes required for a visual component. All visual components that are displayed on the screen and that interact with the user are subclasses of component. It defines number of methods that are responsible for positioning and sizing the window, managing events such as mouse and keyboard input and repainting. A component object is responsible to remember the current foreground and background colors and the currently selected text fonts. Container: The container class is a subclass of Component. It has extra methods that allow other component objects to be used within it. A container is responsible for positioning any components that it contains. It does this through the use of various layout managers. Panel: The Panel class is a subclass of container. A Panel may be thought of as component. Panel is the super class for Applet. When the screen output is directed to an applet it is drawn on the surface of an Panel object. A Panel is a window that does not contain a title bar, menu bar or border. So, we are not able to see these items when an applet is run inside a browser. Other components can be added to a Panel object by its add() method(method of container). Once these components have been added we can position and resize

them manually using the setLocation(), setSize() or setBounds() methods defined by the Component class. Window: The window class creates a top-level window. A top-level window is not contained within any other object. Mostly, a subclass of window called Frame is used. Frame: Frame is commonly nothing but window. It is a subclass of window and has a title bar, menu bar, borders and resizing corners. When a Frame window is created by a program rather than a applet, a normal window is created. Canvas: There is other type of window called canvas which is a blank window on which one can draw.

Working with Frame Windows


Q. What is Frame? 10, W-10] [S-09, S-

The type of window one can create for standalone applications is subclass of frame. Two of the Frames constructors are: 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. We cannot specify the dimensions of the Frame rather we can set the size of the frame after it has been created. There are several methods of Frame in Java library: 1. Setting the Windows Dimensions: The setSize() method is used to set the size of the Frame. Its general syntax is: void setSize(int newwidth, int newheight)

void setSize(Dimension newSize) The dimensions are specified in terms of pixels. The getSize() method is used to obtain the current size of the window. Its general syntax is: Dimension getSize() This method returns the current size of the window contained within the width and height fields of a Dimension object. 2. Showing and Hiding a Window: After a frame has been created, it will not be visible until we call the setVisible() method. Its general syntax is: void setVisible(Boolean visibleFlag) The component is visible if the argument to this method is true, otherwise it is hidden. 3. Setting a Windows Title: We can change the title of a frame window using setTtitle(), which has the general form as: void setTitle(String newTitle) Here, newTitle is the title for the window. Example 1: import java.awt.*; class myframe extends Frame { myframe() { } public static void main(String args[ ]) { myframe f=new myframe();

//create frame

f.setVisible(true); // Make frame visible f.setSize(100,100); f.setTitle(hello new to frame); } } Example 2: import java.awt.*; class myframe extends Frame { myframe(String title) { setVisible(true); setSize(100,100); setTitle(title); } public static void main(String args[ ]) { myframe f=new myframe(hello new to frame); } } C:\Program Files\Java\jdk1.6.0\bin>javac myframe.java C:\Program Files\Java\jdk1.6.0\bin>java myframe

4. Closing a Frame Window Q. Write procedure to close frame with the help of example. [S-09] When frame is used, it is obvious that we need to close it wherever it is not required. The method used to remove that window from the screen is: setVisible(false). To catch a window-close event, we must implement the windowClosing() method of the WindowListener interface. Inside windowClosing() method we will have to remove the window from the screen. Creating a Frame Window in an Applet Q. Explain the use of frame in AWT with example. [S-10] Q. How do you create a frame? Show with an example. [W-10] It is possible to simply create a new frame window from within an applet. First create a subclass of Frame. Next, override any of the standard applet methods, such as init(), start(), and stop(), to show or hide the frame as needed. Finally

implement the windowClosing() method of the WindowListener interface calling setVisible(false) when the window is closed. Once a Frame subclass has been defined, you can create an object of that class. This causes a frame window to come into existence, but it will not be initially visible. Make it visible by calling setVisible(). When created, the window is given a default height and width. You can set the size of the window explicitly by calling the setSize() method. Example 3: Frame in Applet import java.awt.*; import java.applet.*; /* <applet code=myapplet width=200 height=100> </applet> */ class myframe extends Frame yyframe(String title) { super(title); } public void paint(Graphics g) { g.drawString(This is a frame in Applet,100,40); } } public class myapplet extends Applet { Frame f; public void init() { f=new myframe(A frame is created ); 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,50,50); } }

C:\Program Files\Java\jdk1.6.0\bin>javac frapp.java C:\Program Files\Java\jdk1.6.0\bin>appletviewer frapp.html

Creating windowed Program


Although creating applets is a common use for Javas AWT, it is also possible to create stand-alone AWT-based applications. Simply, create an instance of the window or windows you need inside main().

Working with Graphics

The AWT supports a number of graphics methods. All graphics are drawn relative to a window. This can be the main window of an applet, a child window of an applet, or a stand-alone application window. The origin of each window is at the top-left corner and is 0, 0. Co0rdinates are specified in pixels. All output to a window takes place through a graphics context. A graphics context is encapsulated by the Graphics class and is obtained in 2 ways: 1. It is passed to an applet when one of its various methods such as paint() or update(), is called. 2. It is returned by the getGraphics() method of component. In the below examples we will be demonstrating graphics in the main applet window. However, the same techniques will apply to any other window. The Graphics class defines a number of drawing functions. Each shape can be drawn edge-only or filled. Objects are drawn and filled in the currently selected graphics color, which is black by default. When a graphics object is drawn that exceeds the dimensions of the window, output is automatically clipped. Several drawing methods are:

Drawing Lines
Lines are drawn by the means of the drawLine() method as shown below: void drawLine(int startX, int startY, int endY, int endY) drawLine() displays a line in the current drawing color that begins at startX, startY and ends at endX, endY. Eg: //Draw Lines import java.awt.*; import java.applet.*; /* <applet code=Lines.class width=300 height=200> </applet> */ public class Lines extends Applet{ public void paint(Graphics g) {

g.drawLine(0,0,100,100); g.drawLine(0,100,100,0); g.drawLine(40,25,250,180); g.drawLine(75,90,400,400); } } C:\Program Files\Java\jdk1.5.0\bin>javac Lines.java C:\Program Files\Java\jdk1.5.0\bin>appletviewer Lines.java

Drawing rectangles
The drawRect() and fillRect() methods display an outlined and filled rectangles They are shown as below: void drawRect(int top, int left, int width, int height) void fillRect(int top, int left, int width, int height) The upper-left corner of the rectangles is at top.left. The dimensions of the rectangle are specified by the width and height. To draw rounded rectangle, use drawRoundRect() or fillRoundRect() as shown below:

void drawRoundRect(int top, int left, int width, int height, int xDiam, int yDiam) void fillRoundRect(int top, int left, int width, int height, int xDiam, int yDiam) A rounded rectangle has rounded corners. The upper-left corner of the rectangle is at top, left The dimensions of the rectangle are specified in width and height. The diameter of the rounding arc along the X axis is specified by xDiam. The diameter of the rounding arc along the Y axis is specified by yDiam. Eg: //Draw rectangles import java.awt.*; import java.applet.*; /* <applet code=Rectangles.class width=300 height=200> </applet> */ public class Rectangles extends Applet{ public void paint(Graphics g) { g.drawRect(10,10,60,50); g.fillRect(100,10,60,50); g.drawRoundRect(190,10,60,50,15,15); g.fillRoundRect(70,90,140,100,30,40); } } C:\Program Files\Java\jdk1.5.0\bin>javac Rectangles.java C:\Program Files\Java\jdk1.5.0\bin>appletviewer Rectangles.java

Drawing Ellipses and Circles


To draw an ellipse, use drawOval(). To fill an ellipse, use fillOval(). These methods are shown below: void drawOval(int top, int left, int width,int height) void fillOval(int top, int left, int width,int height) To draw a circle, specify a square as the bounding rectangle: Eg: //Draw Ellipses import java.awt.*; import java.applet.*; /* <applet code=Ellipses.class width=300 height=200> </applet> */ public class Ellipses extends Applet{ public void paint(Graphics g) { g.drawOval(10,10,50,50); g.fillOval(100,10,75,50); g.drawOval(190,10,90,30); g.fillOval(70,90,140,100);

} } C:\Program Files\Java\jdk1.5.0\bin>javac Ellipses.java C:\Program Files\Java\jdk1.5.0\bin>appletviewer Ellipses.java

Drawing Arcs Arcs are drawn with drawArc() and fillArc() is shown below: void drawArc(int top, int left, int width, int height, int startAngle, int sweepAngle) void fillArc(int top, int left, int width, int height, int startAngle, int sweepAngle) The arc is bounded by the rectangle whose upper-left corner is specified by top, left and whose width and height are specified by width and height. The arc is drawn from startAngle through the angular distance specified by the sweepAngle. Angles are specified in degrees. Zero degrees is on the horizontal at the 3o clock position. The arc is drawn counterclockwise if sweepAngle is positive, and clockwise if the sweepAngle is negative. Therefore, to draw an arc from 12o clock to 6o clock the start angle would be 90 and the sweep angle is 180. Eg: //Draw Arcs import java.awt.*; import java.applet.*; /* <applet code=Arcs.class width=300 height=200>

</applet> */ public class Arcs extends Applet{ public void paint(Graphics g) { g.drawArc(10,40,70,70,0,75); g.fillArc(100,40,70,70,0,75); } } C:\Program Files\Java\jdk1.5.0\bin>javac Arcs.java C:\Program Files\Java\jdk1.5.0\bin>appletviewer Arcs.java

Drawing Polygons
Q. Write methods for drawing polygon W-10 It is possible to draw arbitrarily shaped figures using drawPolygon() and fillPolygon() as shown below: void drawPolygon(int x[ ], int y[ ], int numPoints) void fillPolygon(int x[ ], int y[ ], int numPoints)

The polygons endpoints are specified by the coordinate pairs contained within the x and y arrays. The number of points defined by x and y is specified by numPoints. There are alternative forms of these methods in which the polygon is specified by a Polygon object. Eg: // Draw Polygon import java.awt.*; import java.applet.*; /* <applet code=HourGlass.class width=230 height=210> </applet> */ public class HourGlass extends Applet{ public void paint(Graphics g) { int xpoints[ ]={30,200,30,200,30}; int ypoints[ ]={30,30,200,200,30}; int num=5; g.drawPolygon(xpoints, ypoints,num); } } C:\Program Files\Java\jdk1.5.0\bin>javac HourGlass.java C:\Program Files\Java\jdk1.5.0\bin>appletviewer HourGlass.java

Working with Color


Q. Write constructors for color class. W-10 Java supports color in a portable, device-independent fashion. The AWT color system allows you to specify any color you want. It then finds the best match for that color, given the limits of the display hardware currently executing your program or applet. Color is encapsulated by the color class. Color defines several constants(eg: Color.black) to specify a number of common colors. You can create your own colors, using one of the color constructors. The most commonly used forms are shown below: Color(int red, int green, int blue) Color(int rgbValue) Color(float red, float green, float blue) The first constructor takes 3 integers that specify the color as a mix of red, green, and blue. These values must be between 0 and 255. Eg: new Color(255,100,100); //light red

The second color constructor takes a single integer that contains the mix of red, green and blue packed into an integer. The integer is organized with red in bits 16 to 23, green in bits 8 to 15, and blue in bits 0 to 7.

The final constructor takes, Color(float,float,float) takes 3 float values(between 0.0 and 1.0) that specify the relative mix of red, green and blue. Once you have created a color, you can use it to set the forground and/or background color by using the setForeground() and setBackground() methods. You can also set it as the current drawing color.

Color Methods
The Color class defines several methods that help manipulate colors. Using Hue, Saturation, and Brightness The hue-saturation-brightness(HSB) color model is an alternative to red-green blue (RGB) for specifying particular colors. The hue is specified with a number between 0.0 and 1.0 ( the colors are approximately red, orange, yellow, green, blue, indigo, and violet). Saturation is another scale ranging from 0.0 to 1.0, representing light pastels to intense hues. Brightness values also range from 0.0 to 1.0 where 1 is bright white and 0 is black. Color supplies 2 methods that let you convert between RGB and HSB. They are shown below: Static int HSB to RGB(float hue, float saturation, float brightness) Static float[ ] RGBto HSB(int red, int green, float values[ ]) HSBto RGB() returns a packed RGB values compatible with the Color(int) constructor. RGBtoHSB() returns a float array of HSB values corresponding to RGB integers. If values is not null, then this array is given the HSB values and returned. Otherwise, a new array is created and the HSB values are returned in it. In either case the array contains the hue at index 0, saturation at index 1, and brightness at index 2. getRed(), getGreen(), getBlue() You can obtain the red, green and blue components of a color independently using getRed(), getGreen(), and getBlue() shown below: Int getRed() Int getGreen()

Int getBlue() Each of these methods returns the RGB color component found in the invoking Color object in the lower 8 bits of an integer. getRGB() To obtain a packed, RGB representation of a color, use getRGB() shown below: Int get RGB() The return value is organized as described earlier.

Setting the current Graphics Color


By default, graphics objects are drawn in the current foreground color. You can change this color by calling the Graphics method setColor(): void setColor(Color newColor) Here, newColor specifies the new drawing color. You can obtain the current color by calling getColor() as shown below: Color getColor() Eg: //Demonstrate Color Import java.awt.*; Import java.applet.*; /* <applet code=ColorDemo width=300 height=200> </applet> */ Public class ColorDemo extends Applet { //draw lines public void paint(Graphics g) Color c1=new Color(255, 100,100); Color c2=new Color(100,255, 100); Color c3=new Color(100,100,255);

g.setColor(c1); g.drawLine(0,0,100,100); g.drawLine(0,100,100,0); g.setColor(c2); g.drawLine(40,25,250,180); g.drawLine(75,90,400,400); g.setColor(c3); g.drawLine(20,150,400,40); g.drawLine(5,290,80,19); g.setColor(Color.red); g.drawOval(10,10,50,50); g.fillOval(70,90,140,100); g.setColor(Color.blue); g.drawOval(190,10,90,30); g.drawRect(10,10,60,50); g.setColor(Color.cyan); g.fillRect(100,10,60,50); g.drawRoundRect(190,10,60,50,15,15); } }

Painting Mode There are two painting or drawing modes for the Graphics class:- paint mode which is the default mode and XOR mode. In paint mode, anything we draw replaces whatever is already on the screen i.e. it overwrites any preexisting contents. If you draw a green circle, you get a green circle, no matter what was underneath. Setting the Paint Mode The paint mode determines how objects are drawn in a window. By default, new output to a window overwrites any preexisting contents. However, it is possible to have new objects XORed onto the window by using setXORedMode() as follows: void setXORMode(Color xorColor)

Here, xorColor specifies the color that will be XORed to the window when an object is drawn. The advantage of XOR mode is that the new object is always guaranteed to be visible no matter what color the object is drawn over. To return to overwrite mode, call setPaintMode() as shown below: void setPaintMode() In general, you will want to use overwrite mode for normal output and XOR mode for special purposes. Here is an example to show how paint mode works:import java.awt.*; import java applet.*; /* <applet code="xor" width="200" height="200"> </applet> */ public class xor extends Applet { public void paint (Graphics g) { g.drawLine(0, 0, 100, 100); g.drawLine(0, 100, 100, 0); g.setColor(Color.blue); g.drawLine(40, 25, 250, 180); g.drawLine(75, 90, 400, 400); g.setColor(Color.green); g.drawRect(10, 10, 60, 50); g.fillRect(100, 10, 60, 50); g.setColor(Color.red); g.drawRoundRect(190, 10, 60, 50, 15, 15); g.fillRoundRect(70, 90, 140, 100, 30, 40); g.setColor(Color.cyan); g.drawLine(20, 150, 400, 40); g.drawLine(5, 290, 80, 19); }

} Output:

The behavior of XOR mode is different. XOR stands for eXclusive-OR. The concept behind XOR mode is that drawing the same object twice returns the screen to its original state. This technique was commonly used for simple animations prior to the development of more sophisticated methods and cheaper hardware. The advantage of XOR mode is that the new object is always guaranteed to be visible no matter what color the object is drawn over. It is possible to have new objects XORed onto the window by using setXORMode( ), as follows: void setXORMode(Color xorColor):- The setXORMode() method changes the drawing mode to XOR mode. Here, xorColor specifies the color that will be XORed to the window when an object is drawn. For each pixel, the new color is determined by an exclusive-or of the old pixel color, the painting color, and the xorColor. For example, if the old pixel is red, the XOR color is blue, and the drawing color is green, the end result would be white. To see why, it is necessary to look at the RGB values of the three colors. Red is (255, 0,0). Blue is (0, 0, 255). Green is (0, 255, 0). The exclusive or of these three values is (255, 255, 255), which is white. Drawing another green pixel with a blue XOR color yields red, the pixel's original color, since (255, 255, 255) ^ (0, 0, 255) ^ (0, 255, 0) yields (255, 0, 0). Here is an example to demonstrate the above concept:-

public abstract void setPaintMode ():- The setPaintMode() method puts the system into paint mode. When in paint mode, any drawing operation replaces whatever is underneath it. setPaintMode() is called to return to normal painting when finished with XOR mode Another Example: The cross hairs are XORed onto the window and are always visible, no matter what the underlying color is. Code: import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="XOR1" width=400 height=200> </applet> */ public class XOR1 extends Applet { public void paint(Graphics g) { g.setColor(Color.red);

g.fillRoundRect(70, 90, 140, 100, 30, 40); g.setColor(Color.cyan); g.drawLine(20, 150, 400, 40); g.setXORMode(Color.black); g.drawLine(90, 100, 110, 100); g.drawLine(100, 90, 100, 110); g.setPaintMode(); } }

Fonts
The AWT supports various type of fonts. The AWT allow for dynamic selection of fonts. Fonts are represented by the Font class. Fonts have a family name, a logical font name, and a face name. The family name is the general name of the font such as courier. The logical name specifies a category of the font such as Monospaced. The face name specifies a specific font such as Courier Italic. Various methods defined by the Font class are as shown below: Method String getFamily() String getFontName() String getName() Description Returns the name of the font family to which the invoking font belongs. Returns the face name of the invoking font. Returns the logical name of the invoking

int getSize() int getStyle() String toString() boolean isBold()

boolean isItalic()

font. Returns the size, in points of the invoking font. Returns the style values of the invoking font. Returns the string equivalent of the invoking font. Returns true, if the font includes the BOLD style value. Otherwise, false is returned. Returns true if the font includes the ITALIC style value. Otherwise false is returned.

Font class defines following Variables: Variable String name float pointSize int size int style Meaning Name of the font Size of the font in points Size of the font in points Font stryle

Determining the available fonts:


When working with fonts, often you need to know which fonts are available on your machine. To obtain this information, you can use the getAvailableFontFamilyNames() method defined by the GraphicsEnvironment class. It is shown below: String [ ] getAvilableFontFamilyNames( ) This method returns an array of strings that contains the name of the available font families. Since, this methods is members of GraphicsEnvironment, you need a GraphicsEnvironment reference to call it. You can obtain this reference by using the getLocalGraphicsEnvironment() static method, which is defined by GraphicsEnvironment as shown below: Static GraphicsEnvironment getLocalGraphicsEnvironment()

Here, is an applet that shows how to obtain the names of the available font families. Example: Available font in System /* <applet code="allfonts" width=500 height=100> </applet> */ import java.applet.*; import java.awt.*; public class allfonts extends Applet { public void paint(Graphics g) { String fonts=" "; String allfontlist[ ]; GraphicsEnvironment t=GraphicsEnvironment.getLocalGraphicsEnvironment(); allfontlist=t.getAvailableFontFamilyNames(); for(int i=0;i<allfontlist.length;i++) fonts= fonts + allfontlist[i] + " "; g.drawString(fonts, 4, 16); } } Creating and Selecting Font To apply a new font to program, you must first create a Font object that describes that font. One Font constructor has the general form as: Font(String fontName, int fontStyle, int pointSize) Here, fontName specifies the name of the desired font. Java will support the following fonts: Dialog, DialogInput, Sans, Serif, Monospaced, and Symbol. Dialog is the font used by your systems dialog boxes. Dialog is also the default if you do not explicitly set a font. You can also use any other fonts supported by your particular system.

The style of the font is specified by fontStyle. It may consist of one or more of these three constants: Font.PLAIN Font.BOLD Font.ITALIC To combine the styles, OR them together. For example: Font.BOLD | Font.ITALIC //specifies a bold, and italic style.

The size in points of the font is specified by pointSize. To use a font that you have created, you must apply it using setFont(). The general form will be: void setFont(Font fontObj) Here, fontObj is the object that contains the desired font. Example: import java.applet.*; import java.awt.*; public class samplefonts extends Frame { Font f; String msg; public void init() { f=new Font(Dialog,Font.PLAIN,12); msg= Welcome; setFont(f); } public void paint(Graphics g) { g.drawString(msg,4,20); } public static void main(String args[ ]) { samplefonts f=new samplefonts(); f.setVisible(true); f.setSize(200,200); } }

Managing Text Output Using FontMetrics Q. What is font and font metrics classes? Explain with the help of example how to set font to a text. [S-09] Java supports large number of fonts. For most fonts, characters are not all the same dimension. Also, the height of each character, the length of descenders, (the hanging parts of letters, such as y) and the amount of space between horizontal lines vary from one font to other font. Also, the point size of a font can be changed. The size of each font may differ and that fonts might be changed while your program is running, there must be some way to determine the dimensions and various other attributes of the currently selected font. For Example: to write one line of text after another indicates that you have some way of knowing how tall the font is and how many pixels are needed between lines. To satisfy this requirement the AWT includes the FontMetrics class, which encapsulates various information about a font. Common terminology used when describing fonts are: Height Baseline The top-to-bottom size of the tallest character in the font. The line that the bottom of characters are aligned to, (not counting descent) The distance from the baseline to the top of a character. The distance from the baseline to the bottom of a character. The distance between the bottom of one line of text and the top of the next.

Ascent Descent Leading

FontMetrics supports several methods that help us to manage text output. These methods help to properly display text in a window. Method Int bytesWidth(byte b[ ], int start, int Description This method

returns

the

width

of

numBytes)

numBytes characters held in array b, beginning at start. Int charWidth(char c[ ], int start, int charWidth() method returns the width of numChars) numChars characters held in array c, beginning at start. Int charWidth(char c) This method returns the width of c Int charWidth(int c) charWidth() method returns the width of c. Int getAscent() This method returns the ascent of the font. Int getDescent() It returns the descent of the font Font getFont() getFont() returns the font Int getHeight() This method returns the height of a line of text. This value can be used to output multiple linesof text in a window Int getLeading() It returns the space between lines of text Int getMaxAdvance() This method returns the width of the widest character -1 is returned if this value is not available Int getMaxAscent() Method used to return the maximum ascent Int getMaxDescent() It returns the maximum descent Int [ ] getWidths() The method returns the widths of the first 256 characters. Int stringWidth(String str) This method will returns the width of the string specified by str. String toString() It returns the string equivalent of the invoking object Exploring Text and Graphics When displaying text or graphics it works with the surface of Javas capabilities. This is an area in which further enhancements are expected as Java and the computing environment continue to evolve. For example: Java 2 added a subsystem to the AWT called Java 2D. Java 2D supports enhanced control over graphics, including things such as coordinate translations, rotation and scaling. It also provides advanced imaging features. The Java 2D Application Programming Interface(the 2D API) is a set of classes that can be used to create a high quality graphics. It includes features like

geometric transformation, antialiasing, alpha compositing, image processing and bidirectional text layout. The 2D API introduces new classes in the following packages: java.awt java.awt.image Also 2D API includes 6 packages: java.awt.color java.awt.font java.awt.geom java.awt.print java.awt.image.renderable com.sun.image.codec.jpeg

Using AWT Controls, Layout Managers and Menus Q. What are different AWT controls? Explain any one in details. [S-09] Controls are components that allow a user to interact with your application in various ways. A commonly used control is the push button, choice control or list. A layout manager automatically positions components within a container (Frame or Panel). Thus, the appearance of any window is determined by a collection of various controls that it contains and the different layout manager used to position them. Control Fundamentals The AWT package defines following types of controls: Labels Buttons Checkboxes Choice Lists Lists Scroll bars Text editing

Adding and Removing Controls

To put a control in a window, we must add it to the window. To do this, we must first create an object of the desired control and then by using add() method of container add it to a window. The general syntax of add() method is: Component add(Component Obj) Here, Obj is an object of the control that we want to add. Once, a control has been added, it will automatically be visible. Sometimes, we may want to remove a control from a window when the control is not needed, for this one has to use remove() . This method is also defined by Container. The general form is: void remove(Component obj) Here, obj is a reference to the control you want to remove. You can remove all controls by calling removeAll().

Responding to Controls
Except for labels which are passive, all controls generate events when they are accessed by the user. For e.g. When the user clicks on a push button an event is generated that identifies the push button. In general, your program implements the appropriate interface and then registers an event listener for each control that you need to monitor.

Labels
A label is an object of type Label, and it contains a string which it displays. Labels are passive controls that do not support any interaction with the user. Label defines the following constructors: Common Constructors: Label () Creates a blank Label instance. Label (String Text) Creates a Label instance with the specified text.

Label (String Text, int Alignment) Creates a Label instance with the specified text and horizontal alignment. The value of these 3 constants can be Label.LEFT, Label.RIGHT, and Label.CENTER.

Common Methods: void setAlignment (int Alignment) Sets the alignment of the label's contents along the X axis. Also current alignment can be obtained using getAlignment(). Its general form is: int getAlignment() void setText (String Text) Sets the text for the label. The getText() is used to get the text of label. The general form is: String getText() Like the Button component, a Label is restricted to a single line of text.

import java.awt.*; import java.applet.*; /* <applet code=Labels width=300 height=200> </applet> */ public class Labels extends Applet { public void init() { Label l1=new Label(FYCO); Label l1=new Label(SYCO); Label l1=new Label(TYCO); Add(l1); Add(l2); Add(l3); }

Buttons Q. Explain the use of button control in AWT with examples. [S-10]
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) The first form creates an empty button. The second form creates a button that contains str as a label. Methods: 1. void setLabel(String str): To set a label on the push button. 2. String getLabel(): It returns the label of the push button as string. Handling Buttons: 1. ActionEventClass: An ActionEvent is generated when a button is pressed, a list item is double-clicked, or menu item is selected.

Hierarchy: Java.lang.Object Java.util.EventObject Java.awt.AWTEvent Java.awt.event.ActionEvent Methods: 1. Object getSource(): It returns the object on which event initially occurred. 2. String getActionCommand(): It returns the command string associated with this action. ActionListener Interface: Each time a button is pressed, an action event is generated. This is sent to any listeners. Each listener implements the ActionListener interface. That interface defines the actionPerformed() method, which called when an event occurs. An ActionEvent object is supplied as the argument to this method. Method: void actionPerformed(ActionEvent obj)

import java.awt.*; import java.applet.*; import java.awt.event.*; /*<applet code="bdemo" width=400 height=350> </applet>*/ public class bdemo extends Applet implements ActionListener { TextField t1,t2,t3; Button b1,b2,b3,b4; Label l1,l2,l3; String msg= " "; public void init() { l1=new Label("Enter the first number"); add(l1); t1=new TextField(15); add(t1); l2=new Label("Enter the second number"); add(l2); t2=new TextField(15); add(t2); l3=new Label(":result of two numbers"); add(l3); t3=new TextField(15); add(t3); b1=new Button("add"); add(b1); b1.addActionListener(this); b2=new Button("sub"); add(b2); b2.addActionListener(this); b3=new Button("mul"); add(b3); b3.addActionListener(this); b4=new Button("div"); add(b4); b4.addActionListener(this); } public void actionPerformed(ActionEvent e) { if(e.getSource()==b1) { int x=Integer.parseInt(t1.getText()); int y=Integer.parseInt(t2.getText()); int sum=x+y; t3.setText(" "+sum); } if(e.getSource()==b2)

Checkboxes
A checkbox is a control that is used to turn an option on or off. It consists of a small box that can either contain mark or not. There is a label associated with each check box that describes the option that box represents. We can change the state of the check box by clicking it. Check boxes can be used individually or as a part of a group. Checkboxes are objects of the Checkbox class. Checkbox supports these constructors: 1. CheckBox () 2. CheckBox (String Text) 3. CheckBox (String Text, boolean Selected) 4. CheckBox (String Text, CheckboxGroup Group, boolean Selected) The first form creates a check box with empty label and the state is unchecked. The second form creates a checkbox with the label str and the state is unchecked. The third form creates a checkbox with the label str and the state is checked when the Boolean argument on it is true. The fourth form creates a checkbox with the label str and the state is checked when the Boolean argument on is true whose group is specified by cb.

Common Methods: Q. Explain any 4 methods of checkbox class with syntax. W-09 1. Boolean getState(): Determines whether this check box is in the on or off state. 2. Void setState(Boolean on): Sets the state of this checb box to the specified state. 3. String getLabel(): Gets the label of this check box. 4. Void setLabel(): Sets this check boxs label to be the string argument. Handling Checkboxes: ItemEvent Class: An Itemevent is generated when a checkbox or a list item is clicked or when a checkable menu item is selected or deselected. Hierarchy: Java.lang.Object Java.util.EventObject Java.awt.AWTEvent Java.awt.event.ItemEvent Methods: 1. Object getItem(): returns the item effected by the event. 2. Int getStateChange() : returns the type of state change. ItemListener Interface: Each time a checkbox is selected or deselected, an item event is generated. This is sent to any listeners. Each listener implements the ItemListener interface. That interface defines the itemStateChanged() method. An ItemEvent object is supplied as the argument to this method. Method: void itemStateChanged(ActionEvent obj) E.g. import java.awt.*; import java.applet.*; import java.awt.event.*;

class chkbox extends Frame implements ItemListener { String msg= " "; Checkbox c1, c2,c3; chkbox() { setSize(400,350); setVisible(true); setLayout(new FlowLayout()); c1=new Checkbox("Dos"); c2=new Checkbox("Windows"); c3=new Checkbox("Unix"); add(c1); add(c2); add(c3); c1.addItemListener(this); c2.addItemListener(this); c3.addItemListener(this); } public void itemStateChanged(ItemEvent e) { repaint(); } public void paint(Graphics g) { msg="State"; g.drawString(msg,50,150); msg="DOS:"+c1.getState(); g.drawString(msg,50,170); msg="Windows:"+c2.getState(); g.drawString(msg,50,190); msg="UNIX:"+c3.getState(); g.drawString(msg,50,210); } } class checkdemo { public static void main(String args[ ]) {

chkbox ch1 =new chkbox(); } }

CheckboxGroup A CheckboxGroup is used to control the behavior of a group of Checkbox objects (each of which has a true or false state). Exactly one of the Checkbox objects is allowed to be true at one time. Checkbox objects controlled with a CheckboxGroup are usually referred to as "radio buttons". The following example illustrates the basic idea behind radio buttons.

import java.awt.*; import java.applet.Applet; public class CheckboxGroupTest extends Applet { public void init() { // create button controller CheckboxGroup cbg = new CheckboxGroup(); Checkbox cb1 = new Checkbox("Show lowercase only", cbg, true); Checkbox cb2 = new Checkbox("Show uppercase only", cbg, false); add(cb1); add(cb2); } }

Choice Choice objects are drop-down lists. The visible label of the Choice object is the currently selected entry of the Choice.

import java.awt.*; import java.applet.Applet; public class ChoiceSimpleTest extends Applet { public void init() { Choice rgb = new Choice(); rgb.add("Red"); rgb.add("Green"); rgb.add("Blue"); add(rgb); } }

Lists A List is a scrolling list box that allows you to select one or more items. Multiple selections may be used by passing true as the second argument to the constructor. Parent Classes java.awt.List

java.awt.Component java.lang.Object Common Public Constructors List () Creates an empty List instance with the default 4 rows visible. List (int Rows) Creates an empty List instance with the specified number of visible rows. List (int Rows, boolean MultiSelect) Creates an empty List instance with the specified number of visible rows and the specified MultiSelect switch.

Common Public Methods void addItemListener (ItemListener Handler) Specifies an event handler for the list. void add (String Item) Inserts the item into this choice at the next position. void add (String Item, int Index) Inserts the item into this choice at the specified position. int getSelectedIndex () Returns the index of the selected item. void setBackground (Color BackgroundColor) Sets the background color of the list. void setFont (Font TextFont) Sets the font for this component. void setForeground (Color TextColor) Sets the color of the text for the list. void Select (int Selection) Sets the index of the selected item.

import java.awt.*; import java.applet.Applet; public class ListSimpleTest extends Applet { public void init() { List list = new List(5, false); list.add("Seattle"); list.add("Washington"); list.add("New York"); list.add("Chicago"); list.add("Miami"); list.add("San Jose"); list.add("Denver"); add(list); } }

The constructor may contain a preferred number of lines to display. The current LayoutManager may choose to respect or ignore this request.

Scrollbar A Scrollbar is a "slider" widget with characteristics specified by integer values that are set during Scrollbar construction. Both horizontal and vertical sliders are available.

import java.awt.*; import java.applet.Applet; // A simple example that makes a Scrollbar appear public class ScrollbarSimpleTest extends Applet { public void init() { Scrollbar sb = new Scrollbar(Scrollbar.HORIZONTAL, 0, // initial value is 0 5, // width of slider -100, 105); // range -100 to 100 add(sb); } }

The maximum value of the Scrollbar is determined by subtracting the Scrollbar width from the maximum setting (last parameter). Common Constructors: Scrollbar () Creates a Scrollbar instance with a range of 0-100, an initial value of 0, and vertical orientation. Scrollbar (int Orientation) Creates a Scrollbar instance with a range of 0100, an initial value of 0, and the specified orientation.

Common Methods: addAdjustmentListener (AdjustmentListener Handler) Configures an event handler for the scrollbar. getValue () Returns the value of the scrollbar setting. setBackground (Color BackgroundColor) Sets the background color of the scrollbar.

setMaximum (int Max) Sets the maximum value of the scrollbar. setMinimum (int Min) Sets the minimum value of the scrollbar. setValue (int Value) Sets the current value of the scrollbar.

TextField Parent Classes java.awt.TextComponent implements Accessible java.awt.Component implements ImageObserver, Serializable java.lang.Object Common Public Constructors TextField () Creates a blank TextField instance. TextField (String Text) Creates a TextField instance with the specified text. MenuContainer,

TextField (int Columns) Creates a blank TextField instance with the specified number of columns. TextField (String Text, int Columns) Creates a TextField instance with the specified text and the specified number of columns.

Common Public Methods void addActionListener (ActionListener Handler) Configures an event handler for the TextField. String getText () Returns the text in the field. void setBackground (Color BackgroundColor) Sets the background color of the TextField.

void setEditable (boolean Editable) Sets the field as being editable or fixed. void setFont (Font TextFont) Sets the font for this component. void setText (String Text) Sets the text for the field.

A TextField is a scrollable text display object with one row of characters. The preferred width of the field may be specified during construction and an initial string may be specified.

import java.awt.*; import java.applet.Applet; public class TextFieldSimpleTest extends Applet { public void init() { TextField f1 = new TextField("type something"); add(f1); } }

TextArea

Parent Classes java.awt.TextArea java.awt.TextComponent

java.awt.Component Serializable java.lang.Object

implements

ImageObserver,

MenuContainer,

Common Public Constructors TextArea () Creates a blank TextArea instance. TextArea (String Text) Creates a TextArea instance with the specified text. TextArea (int Rows, int Columns) Creates a blank TextArea instance with the specified number of rows and columns. TextArea (String Text, int Rows, int Columns) Creates a TextArea instance with the specified text and the specified number of rows and columns.

Common Public Methods void addTextListener (TextListener Handler) Configures an event handler for the TextField. String getText () Returns the text in the field. void setBackground (Color BackgroundColor) Sets the background color of the TextArea. void setEditable (boolean Editable) Sets the field as being editable or fixed. void setFont (Font TextFont) Sets the font for this component.

void setText (String Text) Sets the text for the field. A TextArea is a multi-row text field that displays a single string of characters, where newline ('\n' or '\n\r' or '\r', depending on platform) ends each row. The width and height of the field is set at construction, but the text can be scrolled up/down and left/right.

import java.awt.*; import java.applet.Applet; public class TextAreaSimpleTest extends Applet { TextArea disp; public void init() { disp = new TextArea("Code goes here", 10, 30); add(disp); } } There is no way, for example, to put the cursor at beginning of row five, only to put the cursor at single dimension position 50. There is a four-argument constructor that accepts a fourth parameter of a scrollbar policy. The different settings are the class constants: SCROLLBARS_BOTH, SCROLLBARS_HORIZONTAL_ONLY, SCROLLBARS_NONE, and SCROLLBARS_VERTICAL_ONLY. When the horizontal (bottom) scrollbar is not present, the text will wrap.

import java.awt.*; import java.applet.Applet; public class TextAreaScroll extends Applet { String s = "This is a very long message " + "It should wrap when there is " + "no horizontal scrollbar."; public void init() { add(new TextArea (s, 4, 15, TextArea.SCROLLBARS_NONE)); add(new TextArea (s, 4, 15, TextArea.SCROLLBARS_BOTH)); add(new TextArea (s, 4, 15, TextArea.SCROLLBARS_HORIZONTAL_ONLY)); add(new TextArea (s, 4, 15, TextArea.SCROLLBARS_VERTICAL_ONLY)); } }

Layout Managers A layout manager automatically arranges your controls within a window.

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, (Panel Applet have FlowLayout and Frame have Border Layout manager). The setLayout() method has the following general form:

void setLayout(LayoutManager layObj) This method is used to set the Layout manager as per users choice referenced by layObj. Each layout manager keeps track of a list of components that are stored by their names. Java has several predefined LayoutManager classes, which are described below. You can use the layout manager that best fits your application. Several AWT and Swing classes provide layout managers for general use: BorderLayout BoxLayout CardLayout FlowLayout GridBagLayout GridLayout GroupLayout SpringLayout

How to Use FlowLayout

The FlowLayout class provides a very simple layout manager that is used, by default, by the JPanel objects. The following figure represents a snapshot of an application that uses the flow layout:

The FlowLayout class puts components in a row, sized at their preferred size. If the horizontal space in the container is too small to put all the components in one row, the FlowLayout class uses multiple rows. If the container is wider than necessary for a row of components, the row is, by default, centered horizontally within the container. To specify that the row is to aligned either to the left or right, use a FlowLayout constructor that takes an alignment argument. Another constructor of the FlowLayout class specifies how much vertical or horizontal padding is put around the components. Select either the Left to Right or Right to Left option and click the Apply orientation button to set up the component's orientation. The FlowLayout API The following table lists constructors of the FlowLayout class. Constructor FlowLayout() Purpose Constructs a new FlowLayout object with a centered alignment and horizontal and vertical gaps with the default size of 5 pixels. Creates a new flow layout manager with the indicated alignment and horizontal and vertical gaps with the default size of 5 pixels. The alignment argument can be FlowLayout.LEADING, FlowLayout.CENTER, or FlowLayout.TRAILING. When the FlowLayout object controls a container with a left-to right component orientation (the default), the LEADING value specifies the components to be left-aligned and the TRAILING value specifies the components to be right-aligned.

FlowLayout(int align)

Creates a new flow layout manager with the indicated alignment FlowLayout (int and the indicated horizontal and vertical gaps. The hgap and vgap align, int hgap, int arguments specify the number of pixels to put between vgap) components.

How to Use BorderLayout

The following figure represents a snapshot of an application that uses the BorderLayout class.

As the preceding picture shows, a BorderLayout object has five areas. These areas are specified by the BorderLayout constants:

PAGE_START PAGE_END LINE_START LINE_END CENTER

If the window is enlarged, the center area gets as much of the available space as possible. The other areas expand only as much as necessary to fill all available space two of the areas of the BorderLayout object just the center, or the center and the bottom. Specify the component's location (for example, BorderLayout.LINE_END) as one of the arguments to the add method. If this component is missing from a container controlled by a BorderLayout object, make sure that the component's location was specified and no another component was placed in the same location. Tthe BorderLayout class specify the component as the first argument to the add method. For example: add(component, BorderLayout.CENTER) //preferred For example, here are alternate ways of writing the preceding code: add(BorderLayout.CENTER, component) //valid but old fashioned or add("Center", component) //valid but error prone

The BorderLayout API The following table lists constructors and methods to specify gaps (in pixels). Specifying gaps Constructor or Method Purpose BorderLayout(int horizontalGap, int Defines a border layout with specified gaps verticalGap) between components. setHgap(int) setVgap(int) Sets the horizontal gap between components. Sets the vertical gap between components

How to Use GridLayout The following figure represents a snapshot of an application that uses the GridLayout class.

A GridLayout object places components in a grid of cells. Each component takes all the available space within its cell, and each cell is exactly the same size. If the GridLayoutDemo window is resized, the GridLayout object changes the cell size so that the cells are as large as possible, given the space available to the container. The constructor of the GridLayout class creates an instance that has two columns and as many rows as necessary. Use combo boxes to set up how much vertical or horizontal padding is put around the components. Then click the Apply gaps button.

The GridLayout API The following table lists constructors of the GridLayout class that specify the number of rows and columns. The GridLayout class constructors Constructor Purpose Creates a grid layout with the specified number of rows and columns. All components in the layout are given equal size. GridLayout(int rows, int One, but not both, of rows and cols can be zero, which cols) means that any number of objects can be placed in a row or in a column. Creates a grid layout with the specified number of rows and columns. In addition, the horizontal and vertical gaps are GridLayout(int rows, int set to the specified values. Horizontal gaps are places cols, int hgap, int vgap) between each of columns. Vertical gaps are placed between each of the rows. How to Use CardLayout The following figure represents a snapshot of an application that uses the CardLayout class to switch between two panels.

The CardLayout class manages two or more components that share the same display space. When using the CardLayout class, let the user choose between the components by using a combo box. Another way to accomplish the same task is to use a tabbed pane. The following picture shows a tabbed pane version of the preceding example:

Because a tabbed pane provides its own GUI, using a tabbed pane is simpler than using the CardLayout class. For example, implementing the preceding example using a tabbed pane results in a program with fewer lines of code. Conceptually, each component that a CardLayout manages is like a playing card or trading card in a stack, where only the top card is visible at any time. You can choose the card that is showing in any of the following ways:

By asking for either the first or last card, in the order it was added to the container By flipping through the deck backwards or forwards By specifying a card with a specific name

The CardLayout API The following table lists the CardLayout class methods that are used to choose a component. For each method, the first argument is the container for which the CardLayout is the layout manager (the container of the cards the CardLayout controls). Method first parent) next parent) (Container Purpose Flips to the first card of the container. Flips to the next card of the container. If the currently visible card is the last one, this method flips to the first card in the layout.

(Container

Flips to the previous card of the container. If the currently visible previous (Container card is the first one, this method flips to the last card in the parent) layout. last parent) (Container Flips to the last card of the container.

show (Container Flips to the component that was added to this layout with the parent, String name) specified name, using the addLayoutComponent method.

How to Use GridBagLayout Here is a picture of an example that uses GridBagLayout.

GridBagLayout is one of the most flexible and complex layout managers the Java platform provides. A GridBagLayout places components in a grid of rows and columns, allowing specified components to span multiple rows or columns. Not all rows necessarily have the same height. Similarly, not all columns necessarily have the same width. Essentially, GridBagLayout places components in rectangles (cells) in a grid, and then uses the components' preferred sizes to determine how big the cells should be. The following figure shows the grid for the preceding applet. As you can see, the grid has three rows and three columns. The button in the second row spans all the columns; the button in the third row spans the two right columns.

If you enlarge the window as shown in the following figure, you will notice that the bottom row, which contains Button 5, gets all the new vertical space. The new horizontal space is split evenly among all the columns. This resizing behavior is based on weights the program assigns to individual components in the GridBagLayout. You will also notice that each component takes up all the available horizontal space but not (as you can see with button 5) all the available vertical space.

The way the program specifies the size and position characteristics of its components is by specifying constraints for each component. The preferred approach to set constraints on a component is to use the Container.add variant, passing it a GridBagConstraints object, as demonstrated in the next sections. The GridBagLayout API The GridBagLayout and GridBagConstraints classes each have only one constructor, with no arguments. Instead of invoking methods on a GridBagConstraints object, you manipulate its instance variables. The only method you invoke on a GridBagLayout object is setConstraints.

Menu Bars and Menus A top-level window can have a menu bar associated with it. A menu bar displays a list of menu choices. Each choice is associated with a drop-down menu.This concept is implemented in Java by the following classes: Menubar, Menu, MenuItem. We can develop an application with a Menu. As a name indicates a Menu consists of Menu objects. These Menu objects comprise of MenuItem objects which can be selected by the user with a click of a mouse. A MenuItem may be a String, checkbox, separator, menu etc. Following are the steps to to add menus to any Frame: 1. You need to create a MenuBar first with the help of the following method. MenuBar mb = new MenuBar(); 2. Then you need to create a Menu using Menu m = new Menu("File");.

3. Now the MenuItem options can be added to the Menu from top to bottom, using the following methods.

mi.add(new MenuItem("Open")); mi.add(new CheckboxMenuItem("Type here")); 4. Now you can add the Menu to the MenuBar from left to right using mi.add(m);. 5. Finally, you need to add the MenuBar to the Frame by calling the setMenuBar() method. The program code given below, creates an application window with a menu bar.

import java.awt.*; import java.awt.event.*; public class MainWindow extends Frame { public MainWindow() { super("Menu Window"); setSize(400, 400); FileMenu fileMenu = new FileMenu(this); HelpMenu helpMenu = new HelpMenu(this); MenuBar mb = new MenuBar(); mb.add(fileMenu); mb.add(helpMenu); setMenuBar(mb); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { exit(); } }); } public void exit() { setVisible(false); dispose(); System.exit(0); } public static void main(String args[]) { MainWindow w = new MainWindow(); w.setVisible(true);

} } class FileMenu extends Menu implements Action Listener { MainWindow mw; public FileMenu(MainWindow m) { super("File"); mw = m; MenuItem mi; add(mi = new MenuItem("Open")); mi.addActionListener(this); add(mi = new MenuItem("Close")); mi.addActionListener(this); add(mi = new MenuItem("Exit")); mi.addActionListener(this); } public void actionPerformed(ActionEvent e) { String item = e.getActionCommand(); if (item.equals("Exit")) mw.exit(); else System.out.println("Selected FileMenu " + item) ; } } class HelpMenu extends Menu implements Actio nListener { MainWindow mw; public HelpMenu(MainWindow m) { super("Help"); mw = m; MenuItem mi; add(mi = new MenuItem("Basics")); mi.addActionListener(this); add(mi = new MenuItem("Advanced")); mi.addActionListener(this);

addSeparator(); add(mi = new CheckboxMenuItem("Manual")); mi.addActionListener(this); Menu subMenu = new Menu("Miscellaneous"); subMenu.add(mi = new MenuItem("Help")); mi.addActionListener(this); subMenu.add(mi = new MenuItem("Other Option ")); mi.addActionListener(this); add(subMenu); } public void actionPerformed(ActionEvent e) { String item = e.getActionCommand(); if (item.equals("Basics")) System.out.println("Basics"); else if (item.equals("Help")) System.out.println("Help"); } } Output of the program: C:\newprgrm>javac MainWindow.java C:\newprgrm>java MainWindow

Dialog Boxes A Dialog is a window that requires input from the user. Components may be added to the Dialog like any other container. Like a Frame, a Dialog is initially invisible. You must call the method setVisible() to activate the dialog box.

You can create a simple modal dialog box, and then it will remain visible and will maintain focus until it is hidden (usually when the user clicks on a button). Here's a simple example. import java.awt.*; import java.awt.event.*; public class DialogExample { private static Dialog d; public static void main(String args[]) { Frame window = new Frame(); // Create a modal dialog d = new Dialog(window, "Alert", true); // Use a flow layout d.setLayout( new FlowLayout() ); // Create an OK button Button ok = new Button ("OK"); ok.addActionListener ( new ActionListener() { public void actionPerformed( ActionEvent e ) {

// Hide dialog DialogExample.d.setVisible(false); } }); d.add( new Label ("Click OK to continue")); d.add( ok ); // Show dialog d.pack(); d.setVisible(true); System.exit(0); } } The most important part of the program is the line that initializes the dialog. Notice the parameters we pass to it. The first parameter is a parameter for a window, and the second the title for the dialog. The final parameter controls whether the dialog is modal or not (true modal, false non-modal). d = new Dialog(window, "Alert", true); Using dialogs is easy, and can communicate information to users effectively. File Dialog The FileDialog class displays a dialog window from which the user can select a file. Since it is a modal dialog, when the application calls its show method to display the dialog, it blocks the rest of the application until the user has chosen a file. Field Index Fiel d LOA D SAV E

Description This constant value indicates that the purpose of the file dialog window is to locate a file from which to read. This constant value indicates that the purpose of the file dialog window is to locate a file to which to write.

Constructor Index Constructor FileDialog(Frame) FileDialog(Frame, String) FileDialog(Frame, String, int) Description Creates a file dialog for loading a file. Creates a file dialog window with the specified title for loading a file. Creates a file dialog window with the specified title for loading or saving a file.

The following application exercises the two forms of file dialogs, one for opening and one for saving. import java.awt.*; public class FileDialogTest extends Frame { TextField filename = new TextField(); TextField directory = new TextField(); Button open = new Button("Open"); Button save = new Button("Save"); public FileDialogTest() { setTitle("File Dialog Test"); Panel p = new Panel(); p.setLayout(new FlowLayout()); p.add(open); p.add(save); add("South", p); directory.setEditable(false); filename.setEditable(false); p = new Panel(); p.setLayout(new GridLayout(2,1)); p.add(filename); p.add(directory); add("North", p); } public boolean handleEvent(Event evt) { if(evt.id == Event.WINDOW_DESTROY) System.exit(0); else

return super.handleEvent(evt); return true; } public boolean action(Event evt, Object arg) { if(evt.target.equals(open)) { // Two arguments, defaults to open file: FileDialog d = new FileDialog(this, "What file do you want to open?"); d.setFile("*.java"); // Filename filter d.setDirectory("."); // Current directory d.show(); String openFile; if((openFile = d.getFile()) != null) { filename.setText(openFile); directory.setText(d.getDirectory()); } else { filename.setText("You pressed cancel"); directory.setText(""); } } else if(evt.target.equals(save)) { FileDialog d = new FileDialog(this, "What file do you want to save?", FileDialog.SAVE); d.setFile("*.java"); d.setDirectory("."); d.show(); String saveFile; if((saveFile = d.getFile()) != null) { filename.setText(saveFile); directory.setText(d.getDirectory()); } else { filename.setText("You pressed cancel"); directory.setText(""); } } else return super.action(evt, arg); return true; }

public static void main(String[] args) { Frame f = new FileDialogTest(); f.resize(250,110); f.show(); } } For an open file dialog, you use the constructor that takes two arguments; the first is the parent window handle and the second is the title for the title bar of the FileDialog. The method setFile( ) provides an initial file name, so in this example all the .java files will initially be displayed. The setDirectory( ) method chooses the directory where the file selection will begin. (In general, the OS allows the user to change directories.) The show( ) command doesnt return until the dialog is closed. The FileDialog object still exists, so you can read data from it. If you call getFile( ) and it returns null it means the user canceled out of the dialog. Both the file name and the results of getDirectory( ) are displayed in the TextFields. The button for saving works the same way, except that it uses a different constructor for the FileDialog. This constructor takes three arguments and the third argument must be either FileDialog.SAVE or FileDialog.OPEN.

Event Handling Events If there are no listeners when an event happens, nothing happens. If there are twenty listeners registered, each is given an opportunity to process the event, in an undefined order. With a Button, for example, activating the button notifies any registered ActionListener objects. Consider SimpleButtonEvent applet which creates a Button instance and registers itself as the listener for the button's action events:

import java.awt.*; import java.awt.event.*; import java.applet.Applet;

public class SimpleButtonEvent extends Applet implements ActionListener { private Button b; public void init() { b = new Button("Press me"); b.addActionListener(this); add(b); } public void actionPerformed(ActionEvent e) { // If the target of the event was our Button // In this example, the check is not // truly necessary as we only listen to // a single button if ( e.getSource() == b ) { getGraphics().drawString("OUCH",20,20); } } } Notice that any class can implement ActionListener, including, in this case, the applet itself. All listeners are always notified. If you don't want an event to be processed further, you can call the AWTEvent.consume() method. However each listener would then need to check for consumption using the isConsumed() method. Consuming events primarily stops events from being processed by the system, after every listener is notified. So, if you want to reject keyboard input from the user, you can consume() the KeyEvent. All the KeyListener implementers will still be notified, but the character will not be displayed. (Consumption only works for InputEvent and its subclasses.) So, here is how everything works: Components generate subclasses of AWTEvent when something interesting happens. Event sources permit any class to be a listener using the addXXXListener() method, where XXX is the event type you can listen for, for example addActionListener(). You can also remove listeners using the removeXXXListener() methods. If there is

an add/removeXXXListener() pair, then the component is a source for the event when the appropriate action happens. In order to be an event handler you have to implement the listener type, otherwise, you cannot be added, ActionListener being one such type. Some listener types are special and require you to implement multiple methods. For instance, if you are interested in key events, and register a KeyListener, you have to implement three methods, one for key press, one for key release, and one for both, key typed. If you only care about key typed events, it doesn't make sense to have to stub out the other two methods. There are special classes out there called adapters that implement the listener interfaces and stub out all the methods. Then, you only need to subclass the adapter and override the necessary method(s).

AWTEvent Events subclass the AWTEvent class. And nearly every event-type has an associated Listener interface, PaintEvent and InputEvent do not. (With PaintEvent, you just override paint() and update(), for InputEvent, you listen for subclass events, since it is abstract. Low-level Events Low-level events represent a low-level input or window operation, like a key press, mouse movement, or window opening. The following table displays the different low-level events, and the operations that generate each event (each operation corresponds to a method of the listener interface): ComponentEv Hiding, moving, resizing, showing ent ContainerEven Adding/removing component t FocusEvent KeyEvent MouseEvent WindowEvent Getting/losing focus Pressing, releasing, or typing (both) a key Clicking, dragging, entering, exiting, moving, pressing, or releasing Iconifying, deiconifying, opening, closing, really closed, activating, deactivating

For instance, typing the letter 'A' on the keyboard generates three events, one for pressing, one for releasing, and one for typing. Depending upon your interests, you can do something for any of the three events. Semantic Events Semantic events represent interaction with a GUI component; for instance selecting a button, or changing the text of a text field. Which components generate which events is shown in the next section. Do command the

ActionEvent

AdjustmentEv Value adjusted ent ItemEvent TextEvent State changed Text changed

Event Sources The following table represents the different event sources. Keep in mind the object hierarchy. For instance, when Component is an event source for something, so are all its subclasses: Low-Level Events ComponentListener FocusListener Compone KeyListener nt MouseListener MouseMotionListen er Container ContainerListener Window WindowListener

Semantic Events Button ActionListener

List MenuItem TextField Choice Checkbox Checkbox ItemListener CheckboxMenuIt em List Scrollbar TextArea TextField AdjustmentListen er TextListener

Notice that although there is only one MouseEvent class, the listeners are spread across two interfaces. This is for performance issues. Since motion mouse events are generated more frequently, if you have no interest in them, you can ignore them more easily, without the performance hit. Event Listeners Each listener interface is paired with one event type and contains a method for each type of event the event class embodies. For instance, the KeyListener contains three methods, one for each type of event that the KeyEvent has: keyPressed(), keyReleased(), and keyTyped(). Summary of Listener interfaces and their methods Interface ActionListener Method(s) actionPerformed(ActionEvent e)

AdjustmentListene adjustmentValueChanged(AdjustmentEv r ent e) componentHidden(ComponentEvent e) ComponentListene componentMoved(ComponentEvent e) r componentResized(ComponentEvent e) componentShown(ComponentEvent e) ContainerListen er componentAdded(ContainerEvent e)

componentRemoved(ContainerEvent e) FocusListener ItemListener KeyListener focusGained(FocusEvent e) focusLost(FocusEvent e) itemStateChanged(ItemEvent e) keyPressed(KeyEvent e) keyReleased(KeyEvent e) keyTyped(KeyEvent e) mouseClicked(MouseEvent e) mouseEntered(MouseEvent e) MouseListener mouseExited(MouseEvent e) mousePressed(MouseEvent e) mouseReleased(MouseEvent e) MouseMotionLi stener TextListener mouseDragged(MouseEvent e) mouseMoved(MouseEvent e) textValueChanged(TextEvent e) windowActivated(WindowEvent e) windowClosed(WindowEvent e) windowClosing(WindowEvent e) WindowListener windowDeactivated(WindowEvent e) windowDeiconified(WindowEvent e) windowIconified(WindowEvent e) windowOpened(WindowEvent e)

Exploring the Controls, Menus and Layout Managers We have discussed about the classes that comprise the AWT controls, menus and layout managers. However, the AWT provides a rich programming environment so try the following topics: 1. Try nesting a canvas inside an applet panel.

2. 3. 4. 5.

Explore the FileDialog component. Experiment with manual positioning of components by using setBounds(). Try nesting controls within panels to gain more control over layouts. Create our own layout manager by implementing the LayoutManager interface. 6. Explore PopupMenu. The more you know about the AWT Components, the more control we will have over the look, feel and performance of our applets and applications.

Assignment Questions: 1. Explain concept of windows and AWT 2. What are AWT classes? 3. What is frame? Write procedure to close frame with the help of example 4 Marks 4. Explain frame window in applet. 5. How to create windowed program? 6. Explain steps to display information within a window. 7. Explain how to work with color and paint mode with example. 8. What are font and Font Metrics classes? Explain with the help of example. 4 Marks 9. Explain following tools with example: 4 Marks Each a. Menus b. Labels c. Buttons ( check box/ check boxes group/ choice control d. Lists e. Scroll Bars f. Text Field g. Text Area h. Layout Managers i. Menu Bars and Menu j. Dialog Boxes k. File Dialog

10.Explain handling events by extending AWT components 11.What do you mean by layout manager? List out different layout managers. Programs:

4 marks

1. Write a program to create independent window with window title as Welcome to Java. 2. Develop a window based application using applet and write a program to perform following task: a. Create a textField for receiving input. b. Create OK button. When mouse is clicked on OK button it should display the contents of textfield in status window. 3. Write a program to create an applet with button RED. When clicked the background should be changed to red color. 4. Describe applet by creating a blank applet. 5. Write a program using choice list one for student name and other for student class. When a students name and his class is selected a message will appear on screen describing the selection. Eg: XYZ is a student of class ABC. 6. Write a program to create an applet with checkboxes Breakfast, Lunch and Dinner. Any one or all checkboxes can be selected Display the total bill when button named Calculate is clicked. The rate for breakfast, lunch, and dinner are Rs. 50, 100 and 150 respectively. 7. Write a program using applet to create two TextField for entering Roll_no and name of student. When OK button is pressed it should validate the Roll_no field i.e; it contains one digit else print message to correct the Roll_no. 8. Explain with suitable example to handle ActionEvent to accept the string in the textfield and display it in applet window. 9. Write a program to draw circle, rectangle, line along with the labels by using applet. 10.Write a program to demonstrate the use of Border Layout which shows 4 buttons and 4 sides of an applet with caption as east, west north and south. 8 Marks.

Вам также может понравиться