Presentation is loading. Please wait.

Presentation is loading. Please wait.

8.0 AWT Components : Overview

Similar presentations


Presentation on theme: "8.0 AWT Components : Overview"— Presentation transcript:

1 8.0 AWT Components : Overview
Introduction: The AWT i.e. Abstract Windowing Toolkit Provides a collection of classes for developing GUI Used to create windows, draw and work with images, and components like buttons,etc. The java.awt package contains the AWT GUI classes. Objective: After completing this Topic, you will be familiar with AWT Package and able to create GUI using AWT Components 1 . Introduction to AWT and AWT Components 2 . Visual Components 3 . The Container Components 4 . The Menu 5 . Utility classes Slide Instructor’s Notes: The AWT (Abstract Windowing Toolkit) package in the JDK is a library of Java classes which are used to create graphical user interfaces (GUIs). These interfaces allow users to interact with the Java application in the same way they are habitual to interact with other application programs on their native platforms (e.g. Windows , Unix ,etc... ). As Java is a multiplatform language, the AWT is not designed to implement all the features of any specific operating system which provides GUI (Graphical User Interface). Only the features which are common to all operating systems are offered by AWT classes. Programming with the AWT is therefore a highly portable solution for designing user interface. After completing this Topic, you will be familiar with AWT Package and able to create GUI using AWT Components

2 AWT and AWT Components Java components are implemented by help of supperclasses the java.awt.Component and java.awt.MenuComponents. AWT component categories : 1] Visual components 2] Container components 3] Menu components Component Slide Instructor’s Notes: Components are also known as user interface controls. Components means wide variety of interface elements that can be displayed to the user and used to design user interface. Components can also be programmed to respond to user interaction by the mouse or keyboard. This Event Handling is an important part of GUI programming.This event handling we will discuss later in the "Events" section. The Component class is an abstract class which defines elements common to all components like font, color, painting, reshaping, and event handling etc. NOTE: Abstract classes are classes that declare one or more abstract methods. Abstract methods must be overridden by a child class i.e. subclass; abstract classes cannot be instantiated. We can make three categories of components as : Visual Components : These are the components which user can see and interact. For example Button, TextArea, List, Choice, Label,Checkbox etc. Container Components : Container components can hold other components within their boundaries . For example Frame,Dialog, Panel, Applet. Menu Components : Menu components all derive from the abstract MenuComponent class. Java provides two types of menus : pull-down and pop-up menus Menu Component Visual Component Container Component

3 AWT and AWT Components Visual components and Container components are inherited from java.awt.Component and implements several methods listed below. getSize() setSize() setBackground() setForeground() setFont() setEnabled setBounds() setVisible() Note : Menu components extends java.awt.MenuComponent therefore they do not inherit the same functionality as Visual and Container components Slide Instructor’s Notes: java.awt.Component is the superclass for all Visual components and Container components. There fore all Visual and Container components have implemented methods declared in superclass java.awt.Component. These methods are related to Size, Background, Foreground, Font of the component and also about appearance of the component e.g. Enabling the component and Visibility of the component Let us discuss these methods one by one 1] getSize() : This method returns the size of the component. The return type is Dimension. Dimension has height and width as public data members 2] setSize() : This method sets the size of the component. This method is overloaded, one form takes input parameter type as Dimension, and other form takes input as two int values for width and height 3] setBackground() and setForeground() : These methods setBackground() and setForeground() sets the background and foreground colors respectively for a specified component. Each method takes parameter as one argument which is instance of java.awt.Color class. Color class have some predefined colors, which are static final variables of Color class e.g. Color.black, Color.blue etc. or we can specify color our own by using Color constructor as Color(int redValue, int greenValue, int blueValue) there are some overloaded constructor in Color class If we want to specify black color then use new Color(0,0,0) If we want to specify white color then use new Color(255,255,255) 4] setFont() : Using setFont() method we can specify font associated with component, this is used by component to render any text. This method takes instance of java.awt.Font as a argument. If font is not specified then by default, component uses font of its container. Font constructor is as Font(String fontName, int fontStyle, int fontSize) 5] setEnabled() : This method is used to define accessibility of the component, method takes parameter of type boolean . If the argument is true then the component has its normal appearance and if the argument is false then component does not respond to user input i.e. component is grayed out. 6] setBounds : setBounds() method set the position and size of the component. Position specified is relative to its container or if this component is top level window then position is relative to screen. There are two forms of setBounds() method, one form takes int arguments as xPosition, yPositiion, width, and height and other overloaded form takes parameter as Rectangle object 7] setVisible : Using this method we can specify whether component is to be seen on the screen or not. This method takes boolean argument.

4 AWT and AWT Components Screen snapshots for setEnabled method Button
button.setEnabled(true); figure 1 button.setEnabled(false); figure 2 Slide Instructor’s Notes: This slide shows screen snapshots how setEnabled method is used with the components. Here we have taken example of button figure 1 shows the button appearance when setEnabled(true) figure 2 shows the button appearance when setEnabled(false) User can not user Disabled components. Other method’s use can not be shown as snapshot, that needs to be done in Practical session

5 Visual Components AWT Visual Components Button Label Checkbox
TextField TextArea Choice List FileDialog Canvas ScrollPane Scrollbar Slide Instructor’s Notes: The visual components are components which user can actually see and interact with them. Button, Label, Checkbox, TextArea, TextField, Choice, List, FileDialog, Canvas, ScrollPane, Scrollbar are come under category visual components. To use these components while designing User Interface, we have to create an instance by calling appropriate constructor.Then we need to add these components to container.Otherwise component only gets created but does not get displayed on screen. Component size can be specified by using setBounds() method. Note : We will discuss about adding components to container in Container Component section

6 Visual Components This is the sample program to create components. 1 2
import java.awt.Button; import java.awt.Frame; class Sample extends Frame { public static void main(String args[]) //Create an instance. Frame mainFrame =new Sample(); } Sample() { //Set the title of window setTitle("CTS: Visual component Demo"); setSize(300,140); //Set the size of the frame. setVisible(true); //Make window visible. /* Change only following lines */ Button button = new Button("Click me!"); button.setBounds(80,60,140,40); add(button); } }//End of Class Slide Instructor’s Notes: This is a sample program for creating component program imports two classes Button and Frame. Class Sample extends Frame there fore it gets all features of frame. In main method we create instance of Sample class. In constructor we set Title, Size, Visibility for the frame i.e. window. Then we have written code for creating Button.And by using setBounds() method we set the appropriate bounds for the button and using add() we associate button with frame. Now next time when we want to create any other component we just replace the code which is with yellow background and also we need to change import statement import java.awt.Button to import statement for required component. e.g. import java.awt.Label , import java.awt.TextArea etc. Continue

7 Visual Components Button The button class implements push button
Button button = new Button("Click me!"); Constructor : public Button() public Button(String label) Slide Instructor’s Notes: This figure shows how the button looks like which is created by using program. Button class provides two constructor, one which do not take any argument using which we can create button with no text on it. After creation of button we can add caption to button using method setLabel(). In case of parameterized constructor, button gets created with specified string as caption on it. Handling of event on button can be done using Listeners which we will discuss in Events section

8 Visual Components Label
The label is only used to display any text, and not for user interaction Label label = new Label(“ This is Label "); Constructor : public Label() public Label(String label) public Label(String label, int alignment) Slide Instructor’s Notes: This figure shows how the label looks like which is created by using program and just changing import statement and button code to label code. Label class provides three constructor, one which do not take any argument using which we can create label with no text on it. After creation of label we can add caption to it using method setText(). In case of one parameter constructor, label gets created with specified string as caption on it and in case of two parameter constructor second parameter specifies alignment value can be one of Label.LEFT, Label.RIGHT, or Label.CENTER. Labels are not used for user interaction.labels are just to display text on screen.

9 Visual Components Checkbox
The Checkbox is a kind of button with two states. Two states are true (Checked) and false (Unchecked). Label label = new Label(“ This is Label "); Constructor : public Checkbox() public Checkbox(String label) public Checkbox(String label, CheckboxGroup group, boolean state) Slide Instructor’s Notes: This figure shows how the Checkbox looks like which is created by using program and just changing import statement and button code to Checkbox code. Checkbox class provides three constructor. First constructor Creates a check box without label. The check box is set to "off" and is not part of any check box group. Second constructor Creates a check box with the given string. The check box is set to "off" and is not part of any check box group. The CheckboxGroup class is used to group together a set of Checkbox buttons. Only one check box button in a CheckboxGroup is "on" state at any given time. Pushing any button sets its state to "on" and forces any other button that is in the "on" state into the "off" state. ( This can also be knows as Radio button) Third constructor Creates a check box with the given string, in the specified check box group, and set to the specified state

10 Visual Components TextField
The TextField is used to accept text from user TextField textfield = new TextField (“ Input here"); Constructor : public TextField() public TextField(int cols) public TextField(String text) public TextField(String text, int cols) Slide Instructor’s Notes: This figure shows how the TextField looks like which is created by using program.To create TextField we have to import java.awt.TextField and changing button code to TextField code. TextField class provides four constructor. First constructor Creates a TextField Second constructor TextField(int cols) Constructs a text field the specified number of characters wide. Third constructor TextField(String text) Constructs a text field initialized with the specified text. Fourth constructor TextField(String text, int cols) Constructs a text field initialized with the specified text and can hold the specified number of characters. TextField can not take multiline input from user for that we use TextArea()

11 Visual Components TextArea
The TextArea is used to accept text from user TextArea textarea = new TextArea (“ Input here"); Constructor : public TextArea() public TextArea(int rows, int cols) public TextArea(String text) public TextArea(String text, int rows, int cols) Slide Instructor’s Notes: This figure shows how the TextArea looks like which is created by using program.To create TextArea we have to import java.awt.TextArea and changing button code to TextArea code. TextField can not take multiline input from user for that we use TextArea() TextArea class provides four constructor. First constructor Constructs a new text area Second constructor TextArea(int rows, int cols) Constructs a new text area with the specified number of rows and columns. Third constructor TextArea(String text) Constructs a new text area with the specified text displayed. Fourth constructor TextArea(String text, int rows, int cols) Constructs a new TextArea with the specified text, and the specified number of rows and columns

12 Visual Components Choice The Choice is also called as pull-down list.
Choice choice = new Choice (); choice.addItem(“Item 1”); //To add Items to Choice choice.addItem(“Item 2”); Constructor : public Choice() Slide Instructor’s Notes: In this figure we can see how Choice box looks like. Choice is also called as pull-down list. After creating Choice we can add Items to it by using addItem() method which take string as a parameter.

13 Visual Components List
The List is a collection of text items. List can be used for single selection or multi selection List list = new List(); list.add(“List Item 1”); list.add(“List Item 2”); Constructor : public List() public List(int rows) public List(int rows, boolean isMultipleSelections) Slide Instructor’s Notes: In this figure we can see how List box looks like. List can be single selection or multi selection. After creating List we can add Items to it by using add() method which take string as a parameter. There are 3 constructors for creating List List() : Creates a new scrolling list. List(int rows) : Creates a new scrolling list initialized with the specified number of visible lines. List(int rows, boolean multipleMode) : Creates a new scrolling list initialized to display the specified number of rows.

14 Visual Components FileDialog File open or file save dialog.
Appearance of this dialog box is platform dependent FileDialog filedialog = new FileDialog (this,” Select File to Load”, FileDialog.LOAD); Constructor : public FileDialog(Frame parentWindow, String dlgTitle) public FileDialog(Frame parentWindow, String dlgTitle, int dlgMode) Slide Instructor’s Notes: The FileDialog is used to display a file open or file save dialog.Appearance of this dialog box is platform dependent We can create FileDialog box using statement:FileDialog filedialog = new FileDialog(this,"Select File to Load",FileDialog.LOAD); filedialog.setVisible(true); System.out.print(filedialog .getFile()); This getFile() method returns selected file for loading The value LOAD indicates that the file dialog is finding a file to read. The value SAVE indicates that the file dialog is finding a place to write a file. There are two constructors for FileDialog class, one constructor creates a file dialog window with the specified title for loading a file. The files shown are those in the current directory. Other constructor Creates a file dialog window with the specified title for loading/saving a file. The mode argument must have the value LOAD or to SAVE.

15 Visual Components Canvas Without any default appearance or behavior
We can use Canvas to create custom drawing Canvas canvas = new Canvas (); canvas.setBackground(Color. BLUE); canvas.setSize(200,200); Constructor : public Canvas () Slide Instructor’s Notes: The Canvas is a component without any default appearance or behavior. We can use Canvas to create custom drawing regions,components, etc . To create Canvas we can use constructor Canvas() and then we can set position, dimensions and color for canvas.

16 Visual Components ScrollPane Form of panel
Can contain child component having dimensions greater than the ScrollPane Scroll pane provides horizontal or/and vertical scrollbars //Code snippet ScrollPane scrollpane = new ScrollPane (): TextArea bigText = new TextArea(" This is very very Long Text .. !!!"); bigText.setVisible(true); scrollpane.add(bigText); add(scrollpane); Constructor : ScrollPane() ScrollPane(int scrollBarPolicy) Slide Instructor’s Notes: Scrollpanes are a form of panel.We can add a child component to the ScrollPane container that may have dimensions greater than the ScrollPane container. In this case, the scroll pane provides horizontal or/and vertical scrollbars that allow the user to display different areas of the child component. ScrollPane is a container class which implements automatic horizontal and/or vertical scrolling for a single child component. The display policy for the scrollbars can be set ScrollPane() Create a scrollpane container with default scrollbar policy. ScrollPane(int scrollBarPolicy) Create a scrollpane with the specified scrollbar behaviour. In second form of the constructor scrollBarPolicy can be one of following : ScrollPane.SCROLLBARS_ALWAYS, ScrollPane.SCROLLBARS_AS_NEEDED, ScrollPane.SCROLLBARS_NEVER

17 Visual Components Scrollbar
The Scrollbar component that adjusts scroll panes and lists which is available as a component in Scrollbar's own right. setLayout(null); Scrollbar sb = new Scrollbar(Scrollbar.HORIZONTAL, 10, 10, 0, 300); sb.setBounds(3,26,300,20); add(sb); Constructor : public Scrollbar() public Scrollbar(int orientation) Range of scrollbar Slide Instructor’s Notes: public Scrollbar() Constructs a vertical scroll bar. public Scrollbar(int orientation) Constructs a scroll bar with the specified orientation. The orientation argument must be one of the two values Scrollbar.HORIZONTAL , Scrollbar.VERTICAL indicating a horizontal or vertical scroll bar, respectively Parameters of second constructor specifies : orientation - orientation of the scroll bar (Scrollbar.HORIZONTAL , Scrollbar.VERTICAL ) value - the initial value of the scroll bar visible - the size of the scroll bar's thumb, representing the visible portion. minimum - the minimum value of the scroll bar maximum - the maximum value of the scroll bar We will discuss how to handle scroll bar Adjustment events in Events section initial value of the scroll bar scroll bar thumb

18 Container Components AWT Container Components Applet Frame Panel
Dialog Slide Instructor’s Notes: Container components are components which are capable of holding other components with in them. Applet, Frame, Panel, Dialog are comes under category of container components. We can add components to container using add() method. In add() method we pass component object.

19 Container Components Hierarchy for Container components Container
Dialog Window Panel Frame Applet Slide Instructor’s Notes: The above figure shows Hierarchy for Container components. Base class for all containers is Component.

20 Container Components Applet
Applets are Java programs that are integrated in Web pages. Every applet is implemented by creating a subclass of the Applet class. Import java.applet.*; Java.applet package contains - 1 class : Applet - 3 interfaces : AppletContext, AppletStub, and AudioClip Slide Instructor’s Notes: Applets are Java programs that are integrated in Web pages. When a Web page containing an applet is displayed by a Web browser, the applet is loaded and executed. The applet's output is displayed within a subset of the browser's display area. Applets are client side code which get be executed in be browser. Browser should have JVM (Java Virtual Machine ), to give facility of having HTML page with some java coding ( I.e. Applet code) from server. Server sends .class (Applet class file) along with the HTML page The Applet class is a subclass of the Panel class, and applets are implemented as a panel within a Web document.Every applet is implemented by creating a subclass of the Applet class. The java.applet package is the smallest package in the Java API. It consists of a single class-the Applet class-and three interfaces: AppletContext, AppletStub, and AudioClip. The Applet class contains a single default parameter less constructor. Applets are constructed by the runtime environment when they are loaded and do not have to be explicitly constructed. AppletContext : This interface represents an applet's environment. If the document containing many applets. The methods in this interface can be used by an applet to obtain information about its environment (I.e. Other applets etc.). e.g. GetApplet (String Appletname ) : Searches and returns the applet in the document represented by this applet context with the given name. AppletStub : When an applet is first created, an applet stub is attached to it using the applet's setStub() method. This stub is as a interface between the applet and the browser environment or applet viewer environment in which the application is running. e.g. public void appletResize(int appletWidth, int appletHeight) Called when the applet wants to be resized. AudioClip : The AudioClip interface is used for playing a sound clip. Multiple AudioClip items can be playing at the same time, and the resulting sound is mixed together to produce a composite sound. e.g. play : public void play() Starts playing the audio clip. Each time this method is called, the clip is restarted. loop : public void loop() Starts playing the audio clip in a loop. stop : public void stop() Stops playing the audio clip.

21 Container Components Rules for Applet / Restriction on Applet :
Applet can not execute any program on local machine Applet can not access any file on local machine Applet can not open socket connection to any one other than from where it is down loaded If any Applet opens any new window then that window gives warning and message box Slide Instructor’s Notes: As applet is a java code and it gets executed on client side there is much risk involved to allow applet run freely there fore to restrict applet from doing any invalid task following rule are applied on applet There are four rules for applet or we can say restriction on applet. 1. Applet can not execute any program on local machine. For applet it is not possible to execute any .exe on machine where it is loaded in browser. 2. Applet can not access any file on local machine. 3. Applet can not open socket connection to any one other than from where it is down loaded 4. If any Applet opens any new window then that window gives warning and message box

22 Container Components Applet example : 1 2 Continue //FirstApplet.java
import java.applet.*; import java .awt.Button; import java.awt.Graphics; public class FirstApplet extends Applet { Button b = new Button ("Click Me"); public FirstApplet() { b.setBounds(20,25,100,40); this.setLayout(null); this.add(b); } public void paint (Graphics g) { g.drawString(“Applet Example",14,14); 1 2 public void init() { System.out.println("Applet Initialized "); } public void start() { System.out.println("Applet Started"); public void stop() { System.out.println("Applet Stopped"); public void destroy(){ System.out.println("Applet Destroyed"); } //End Applet Class Slide Instructor’s Notes: The above is a sample applet code. To write any applet class we have to import java.awt.Applet class and by extending Applet class we design our own applet. As applet is as a container we can write any java code for creating components in it. In above example we create button on it. We can handle any event on button or any component placed on it which reacts to user input by using Listeners and Adapters. We will discuss about Listeners and Adapters later on in Events section. Continue

23 Container Components Applet life cycle Init Start Stop Destroy Init
Applet Loaded Window Closed Window Minimized /Closed Window Maximized Slide Instructor’s Notes: These are the four methods which takes part in life cycle of Applet. init method, this method is gets called when applet gets loaded for first time. This method is used for initialization of applet. Any code which is needed to executed only once and while applet is loading is put into init method. E.g. creating object, initializing variables etc. start method is used to write code which needs to be run when applet gets started. e.g starting audio file, starting animation,etc. start method gets called when applet is loaded and also when applet is maximized from minimized state. stop method is come in to picture when we need to execute code as applet is stopped or minimized. e.g. stopping audio file,etc. destroy method gets called when applet is closed or destroyed. This is normally used to release resources.

24 Container Components HTML Code to use applet in HTML file <html>
<body> <applet code= "FirstApplet.class" height= "100" width = "140" > </applet> </body> </html> Slide Instructor’s Notes: Above is a HTML code to show applet in browser. In HTML we can specify class file for applet.Using height and width we can set area size in which applet gets displayed. We can also pass the parameters to applet, this we will see after little time.

25 Container Components Figure 1 Figure 2 Slide Instructor’s Notes:
We can check applet code by executing it using appletviewer.exe. Figure 1 shows the output of execution of applet using appletviewer.exe Figure 2 shows the output when applet is loaded in browser using HTML file. Figure 1 Figure 2

26 Container Components Figure 1 Slide Instructor’s Notes:
Figure 1 : shows output of init, start, stop, destroy method code on screen Figure 1

27 Container Components Parameter passing to Applet : Constructor :
Code snippet in java file String s = new String(); public void init(){ s="Parameter :" + getParameter("Param1"); System.out.print("Applet Initialized "); } public void paint (Graphics g){ g.drawString(s,14,14); Constructor : public Button() Creates a button with no label. public Button(String label) Creates a button with the indicated label. Code snippet in HTML file <html> <body> <applet code= "FirstApplet.class“ height= "100“ width = "140" > <param name= "Param1“ value= "Cognizant"> </param> </applet> </body> </html> Slide Instructor’s Notes: We can pass parameter to Applet from HTML file. Parameter passing from HTML file is in Name-Value pair. While accessing parameter value in applet code we have to use getParameter() method which takes Name string as input and returns corresponding value string.

28 Container Components Figure 2
Slide Instructor’s Notes: Above figure shows the output of previous applet code when we pass parameter from HTML. Figure 2

29 Container Components Other Applet Attribute Tags: < APPLET
[CODEBASE = code_Base_URL] CODE = applet_File [ALT = alternate_Text] [NAME = applet_Instance_Name] WIDTH = in_Pixels HEIGHT = in_Pixels [ALIGN = alignment] [VSPACE = in_Pixels] [HSPACE = in_Pixels] > [< PARAM NAME = applet_Parameter1 VALUE = value >] [< PARAM NAME = applet_Parameter2 VALUE = value >] </APPLET> Slide Instructor’s Notes: CODEBASE = codebaseURL: This optional attribute specifies the base URL of the applet -- the directory or folder that contains the applet's code. If this attribute is not specified, then the document's URL is used. CODE = appletFile : This required attribute gives the name of the file that contains the applet's compiled Applet subclass. This file is relative to the base URL of the applet. It cannot be absolute. ALT = alternateText : This optional attribute specifies any text that should be displayed if the browser understands the APPLET tag but can't run Java applets. NAME = appletInstanceName : This optional attribute specifies a name for the applet instance, which makes it possible for applets on the same page to find (and communicate with) each other. WIDTH = pixels HEIGHT = pixels : These required attributes give the initial width and height (in pixels) of the applet display area, not cosidering any windows or dialogs that the applet brings up. ALIGN = alignment : This optional attribute specifies the alignment of the applet. The possible values of this attribute are : left, right, top, texttop, middle, absmiddle, baseline, bottom, absbottom. VSPACE = pixels HSPACE = pixels : These optional attributes specify the number of pixels above and below the applet (VSPACE) and on each side of the applet (HSPACE). < PARAM NAME = applet_Parameter VALUE = value > <PARAM> : tags are the only way to specify applet-specific parameters. Applets read user-specified values for parameters with the getParameter() method.

30 Container Components Frame Create a standard window
import java.awt.Frame Constructors : Frame() Frame(String frameTitle) Methods : setTitle(String), setVisible(boolean), setSize(int, int), setSize(Dimension) Dimension getSize(). Slide Instructor’s Notes: The Frame creates standard style window. Frame appearance is depends upon the platform on which program is getting executed. There are two constructors for creating frame. The first form of constructor is parameter less. Which creates a frame that does not have title. To specify title afterwards we can use setTitle() method of frame class. Second form creates a window with title specified by passing string to constructor. For setting size of the frame there setSize() methods, which has two forms. First form : void setSize(int width, int height); Second form : void setSize(Dimension size ); Using getSize() method we can get dimension of frame, which returns Dimension. We can hide or show window by passing boolean parameter to setVisible() method. For closing a frame window we have to implement windowListener or extend windowAdapter class for it. We see the details about writing Listener and adapter in Event section

31 Container Components Panel Subclass of container
Panel is super class for applet Intermediate level of space organization of GUI. Does not contain Title bar , Menu bar and Border add() method Slide Instructor’s Notes: Panel is a concrete subclass of container. It does not add any new method it just implements container. Panel is a superclass for an applet, therefore when output is directed to applet it is drawn on the surface of panel object. Panel is a window that does not contain any title bar, menu bar, border. Because of this we can not see title , menu, border to applet when it run inside the browser.When we run applet using appletviewer.exe we can see menu and border provided by appletviewer. Using add() method we can add components to panel. After adding components we can set Size and Position for those components.

32 Container Components Dialog Pop-up window User input Modal or Modeless
Constructors : Dialog(Frame parentWindow,boolean Mode) Dialog(Frame parentWindow, String windowTitle, boolean Mode) Example : Save Dialog box Load Dialog box etc. Slide Instructor’s Notes: Dialog box is used to accept user input. They are similar to frame window except that they are child windows of the top level window. Dialog box do not have menu there fore they are similar to frame window. You can add controls on dialog box as adding controls on frame. Dialog boxes are of two types : Modal and Modeless. When Modal dialog box is active all input is directed to it until it is closed. This means unless and until modal dialog box is open other windows are not accessible to user. When Modeless dialog box is active focus can be changed to other windows of your application. There fore other part of your program can be accessible and active There are two constructors to create dialog box. One constructor creates dialog box without Title and other create with Title. In constructor parameter, parentWindow is owner for dialog box, if mode is true then dialog box is Modal other wise it is Modeless. Title for dialog box can be passed as a windowTitle in second constructor.

33 The Menu Menus Pull-down menus Pop-up menus Classes used
Tear-off menu. Pop-up menus Classes used Menu Class MenuBar Class MenuComponet Class MenuItem Class Note : Menu can only be set to Frame Slide Instructor’s Notes: Java supports two types of menus one is pull-down and other is pop-up menu. To use pull-down menus in application we have to import java.awt.Menu. To use pull-down menus in application we have to import java.awt.PopupMenu. A Menu object is a pull-down menu component that is deployed from a menu bar. A PopupMenu class that implements a menu which can be dynamically popped up at a specified position within a component A menu can optionally be a tear-off menu. A tear-off menu can be opened and dragged away from its parent menu bar or menu. It remains on the screen after the mouse button has been released. The mechanism for tearing off a menu is platform dependent, since the look and feel of the tear-off menu is determined by its peer. On platforms that do not support tear-off menus, the tear-off property is ignored. The MenuBar class encapsulates the platform's concept of a menu bar bound to a frame. In order to associate the menu bar with a Frame object, call the frame's setMenuBar method. A menu bar handles keyboard shortcuts for menu items, passing them along to its child menus. (Keyboard shortcuts, which are optional, provide the user with an alternative to the mouse for invoking a menu item and the action that is associated with it.) The abstract class MenuComponent is the superclass of all menu-related components. In this respect, the class MenuComponent is analogous to the abstract superclass Component for AWT components All items in a menu must belong to the class MenuItem, or one of its subclasses. The default MenuItem object Represent a simple labeled menu item. Note that Menu can only be set to Frame

34 The Menu Menu bar Menu Items Slide Instructor’s Notes:
Above figure show Menu bar, Menu Items in Application menu. Separator is also called as menu item, which is created with the label "-". When a menu item is selected, AWT sends an action event to the menu item. Since the event is an instance of ActionEvent, the processEvent method examines the event and passes it along to processActionEvent. The latter method redirects the event to any ActionListener objects that have registered an interest in action events generated by this menu item. protected void processActionEvent(ActionEvent e) Processes action events occurring on this menu item, by dispatching them to any registered ActionListener objects. This method is not called unless action events are enabled for this component. Action events are enabled when one of the following occurs: An ActionListener object is registered via addActionListener. Action events are enabled via enableEvents. We will see how to use ActionListener in Events section.

35 The Menu 1 2 // Menu demo code import java.awt.*;
import java.awt.event.*; class Test extends Frame { MenuBar mb; public Test(){ mb=new MenuBar(); Menu menu=new Menu("File"); MenuItem mn=new MenuItem("New"); MenuItem mo=new MenuItem("Open"); menu.add(mn); menu.add(mo); mb.add(menu); this.setMenuBar(mb); } // Test Constructor 1 2 public static void main(String args[] ){ System.out.println("Starting Test..."); Test mainFrame = new Test(); mainFrame.setSize(200, 200); mainFrame.setTitle("Test"); mainFrame.setVisible(true); } Slide Instructor’s Notes: Above is the Menu demo code which displays pull-down menu on the screen with options New and Open. First we create class which extends Frame to achieve window functionality. In this class we define 3 kinds of variables. First one is menu bar ( mb ), menu ( menu ), menu item (mn, mo). Using mb=new MenuBar(); we create menu bar, we add menu bar to application window using this.setMenuBar(mb); statement. We add menu item mn and mo to menu using add() method.At last we attach menu to menu bar.

36 The Menu Figure 1 Figure 2 Figure 3 Slide Instructor’s Notes:
Figure 1 shows the menu created using sample code shown in previous slide. Figure 2 shows the menu with separator which can be created using menu item with caption “-”. E.g. MenuItem md=new MenuItem("-"); We can add keyboard short cut to menu using overloaded constructor of MenuItem as MenuItem(String caption, MenuShortcut ms); Figure 3

37 The Menu A PopupMenu class implements a menu which can be dynamically popped up at a specified position within a component. public class PopupMenu extends Menu As the inheritance hierarchy suggests, a PopupMenu can be used anywhere a Menu can be used. However, if you use a PopupMenu like a Menu (e.g., We add it to a MenuBar), then you can not call show on that PopupMenu. We can show Popup Menu to specified location using show() method void show(Component origin, int x, int y)          Shows the popup menu at the x, y position relative to an origin component. Slide Instructor’s Notes: A PopupMenu class implements a menu which can be dynamically popped up at a specified position within a component. public class PopupMenu extends Menu As the inheritance hierarchy suggests, a PopupMenu can be used anywhere a Menu can be used. However, if you use a PopupMenu like a Menu (e.g., We add it to a MenuBar), then you can not call show on that PopupMenu. We can show Popup Menu to specified location using show() method void show(Component origin, int x, int y)         Shows the popup menu at the x, y position relative to an origin component A component is an object having a graphical representation that can be displayed on the screen and that can interact with the user. Examples of components are the buttons, checkboxes, and scrollbars of a typical graphical user interface. The Component class is the abstract superclass of the nonmenu-related Abstract Window Toolkit components. Class Component can also be extended directly to create a lightweight component.

38 Utility classes Vectors Color 4. Resource-manipulation utilities
Dimension Insets Point Polygon Rectangle Shape Color SystemColor Slide Instructor’s Notes: There are four Types of Utility classes 1. Vectors 2. Color 3. Resource 4. Resource-manipulation utilities Under Vectors we have classes as Dimension, Insets, Point, Polygon, Rectangle, Shape Under Color type there are Color and SystemColor

39 Utility classes Resource
Cursor Font FontMetrics Graphics Image PrintGraphics PrintJob Toolkit Slide Instructor’s Notes: Under Resource there are classes as Cursor, Font, FontMetrics, Graphics, Image, PrintGraphics, PrintJob, Toolkit and under Resource-manipulation utilities there is MediaTracker

40 Utility classes Vectors
Dimension : The Dimension class encapsulates the width and height of a component in a single object. e.g.  void setSize(Dimension d) method of Component Insets : An Insets object is a representation of the borders of a container. It specifies the space that a container must leave at each of its edges. The space can be a border, a blank space, or a title. Point : A point represents an coordinate. Polygon : A polygon consists of a list of, where each successive pair of coordinates defines a side of the polygon Rectangle : A Rectangle specifies an rectangular area in a coordinate space Shape : The Shape interface provides definitions for form of geometric shape. Slide Instructor’s Notes: Vectors: Dimension : The Dimension class encapsulates the width and height of a component (in integer precision) in a single object. The class is associated with many properties of components. Many methods defined by the Component class and the LayoutManager interface uses a Dimension object as a parameter or as return value. Dimension can contain negative values as height and width. Insets : An Insets object is a representation of the borders of a container. It specifies the space that a container must leave at each of its edges. The space can be a border, a blank space, or a title. Constructor for Insets is as Insets(int top, int left, int bottom, int right) Creates and initializes a new Insets object with the specified top, left, bottom, and right insets. Point: A point representing a location in (x, y) coordinate space, specified in integer precision. Polygon : The Polygon class encapsulates a description of a closed, two-dimensional region within a coordinate space. This region is bounded by an arbitrary number of line segments, each of which is one side of the polygon. Internally, a polygon consists of a list of (x, y) coordinate pairs, where each pair defines a vertex of the polygon, and two successive pairs are the endpoints of a line that is a side of the polygon. The first and final pairs of (x, y) points are joined by a line segment that closes the polygon. Rectangle : A Rectangle specifies an area in a coordinate space that is enclosed by the Rectangle object's top-left point (x, y) in the coordinate space, its width, and its height. A Rectangle object's width and height are public fields. The constructors that create a Rectangle, and the methods that can modify these public fields, do not prevent setting a negative value for width or height. A Rectangle whose width or height is negative is considered empty. If the Rectangle is empty, then the isEmpty() method returns true. No point can be contained by or inside an empty Rectangle. The values of width and height, however, are still valid.

41 Utility classes Color Resource
Color : This class encapsulate colors using the RGB format. SystemColor : A class to encapsulate symbolic colors representing the color of native GUI objects on a system. Resource Cursor : A class to encapsulate the bitmap representation of the mouse cursor. Font : The Font class represents fonts, which are used to render text on screen. FontMetrics : The FontMetrics class defines a font metrics object, which encapsulates information about the rendering of a particular font on a screen. Slide Instructor’s Notes: Color : Color :Every color has an implicit alpha value of 1.0 or an explicit one provided in the constructor. The alpha value defines the transparency of a color and can be represented by a float value in the range 0.0 - 1.0 or 0 - 255.Color class have many overloaded constructor using them we can define custom colors. There are some static fields in Color class which specifies predefined colors. We can directly use them by using class name Color. e.g. Color. WHITE, Color. lightGray, etc. SystemColor : A class to encapsulate symbolic colors representing the color of native GUI objects on a system. For systems which support the dynamic update of the system colors (when the user changes the colors) the actual RGB values of these symbolic colors will also change dynamically. In order to compare the "current" RGB value of a SystemColor object with a non-symbolic Color object, getRGB() should be used rather than equals.

42 Utility classes Graphics : The Graphics class is the abstract base class for all graphics contexts that allow an application to draw onto components. Image : The abstract class Image is the superclass of all classes that represent graphical images. Toolkit : This class is the abstract superclass of all actual implementations of the Abstract Window Toolkit Note : Example code snippets for Dimension, Point, Polygon, Rectangle, Color,Font, Graphics, Image, Toolkit are in Topic “Painting” Slide Instructor’s Notes: Resource: Cursor : A class to encapsulate the bitmap representation of the mouse cursor. There are some static fields in Cursor class e.g. CROSSHAIR_CURSOR (The crosshair cursor type ) , DEFAULT_CURSOR(The type associated with all custom cursors) , etc. Font: The Font class represents fonts, which are used to render text on screen. A font provides the information needed to map sequences of characters to sequences of glyphs and to render sequences of glyphs on Graphics and Component objects. character is a symbol that represents a letter, a digit, or punctuation in an abstract way. For example, 'g‘. A glyph is a shape used to render a character or a sequence of characters. FontMetrics : The FontMetrics class defines a font metrics object, which encapsulates information about the rendering of a particular font on a particular screen. protected FontMetrics(Font font) Creates a new FontMetrics object for finding out height and width information about the specified Font and specific character glyphs in that Font. Graphics : A Graphics object encapsulates state information needed for the basic rendering operations that Java supports. This state information includes the following properties: The Component object on which to draw. A translation origin for rendering and clipping coordinates. The current clip. The current color. The current font. The current logical pixel operation function (XOR or Paint). Image : The abstract class Image is the superclass of all classes that represent graphical images. The image must be obtained in a platform-specific manner. Toolkit : This class is the abstract superclass of all actual implementations of the Abstract Window Toolkit. Subclasses of Toolkit are used to bind the various components to particular native toolkit implementations. Usually applications should not call any of the methods in this class directly. The methods defined by Toolkit are the "glue" that joins the platform-independent classes in the java.awt package. Some methods defined by Toolkit interact the native operating system directly.

43 AWT Components : Summary
The AWT i.e. Abstract Windowing Toolkit provides classes for developing GUI The java.awt package contains the AWT GUI classes. AWT component : Visual components , Container components , Menu components. FileDialog box : File Open dialog box , File Save dialog box. Canvas is used to create custom drawing. ScrollPane can contain child component having dimensions greater than the it. AWT Container Components : Applet, Frame, Panel, Dialog. appletrunner.exe can be used to execute applet while developing. Applet can not open socket connection to any one other than from where it is down loaded. The Graphics class is the abstract base class for all graphics contexts. Now in next Topic “Events” we will learn about how to handle user interaction with AWT components Slide Instructor’s Notes: In this chapter we learn AWT Concept, AWT Components I.e. which are AWT components how to create them, what king of common properties they have, what are special method/ properties for each component. We also learn about container components, in which we can add other components. We gone through life cycle of applet, use of applet, passing parameters to an applet. We learn to create Menus We also discussed some utility classes which are vary commonly use in any JAVA application. In short the summary of the Topic is : The AWT i.e. Abstract Windowing Toolkit provides classes for developing GUI The java.awt package contains the AWT GUI classes. AWT component are of three type as Visual components , Container components , Menu components. FileDialog box are of type File Open dialog box , File Save dialog box. Canvas is used to create custom drawing. ScrollPane can contain child component having dimensions greater than the it. Applet, Frame, Panel, Dialog are AWT Container Components. appletrunner.exe can be used to execute applet. Applet can not open socket connection to any one other than from where it is down loaded. The Graphics class is the abstract base class for all graphics contexts. Now in next Topic “Events” we will learn about how to handle user interaction with AWT components

44 9.0 Events : Overview Introduction Objective
Platform-independent class Encapsulates events from the platform's Graphical User Interface Event handling using Listeners and Adapters Java uses Event Delegation Model for handling events. Objective After completing this Topic, you will be able to capture and handle AWT Component Events using Listeners/Adapters . In this Topic we will cover   Event Delegation Model Event Hierarchy   Event Listeners   Event Adapters Slide Instructor’s Notes: Event is a platform-independent class that encapsulates events from the platform's Graphical User Interface. In JAVA component events are handled by using Event Listeners and Adapters. Java uses Event Delegation Model for handling events. Event delegation model has 4 entities involved : Source of event, Receiver of event, Listener for Event and Event. Objective: After completing this Topic, you will be able to capture and handle AWT Component Events using Listeners/Adapters. In this Topic we are going to cover   Event Delegation Model Event Hierarchy   Event Listeners   Event Adapters

45 Event Delegation Model
Event Delegation Model : Event delegation model means Events which are generated by Event Source for Event Receiver are processed by Event Listener. Event Source Receiver Slide Instructor’s Notes: Event Delegation Model : Event delegation model means Events which are generated by Event Source for Event Receiver are processed by Event Listener. In the event delegation model, a component may be told to notify object or objects (listener/adapters) when the component generates a particular kind of events. If component is not interested in processing event, then those events are not propagated to listener or adapters. Event Listener

46 Event Hierarchy Java.util.EventObject Java.awt.AWTEvent ActionEvent
AdjustmentEvent ComponentEvent TextEvent ItemEvent Slide Instructor’s Notes: This is the hierarchy for Events in JAVA. ActionEvent : as a result of Activation of components AdjustmentEvent : as a result of Adjustment of adjustable components like scroll bar TextEvent : as a result of text component is modified ItemEvent : as a result of item is selected from a list, choice etc. ComponentEvent is divided in to : ContainerEvent : as a result of components are added to or removed from container FocusEvent : as a result of receiving and loss of focus WindowEvent : as a result of window activities such as minimizing, closing etc. PaintEvent : as a result of component painted InputEvent is divided into : MouseEvent : as a result of Mouse interaction KeyEvent : as a result of Key board interaction by user InputEvent ContainerEvent FocusEvent WindowEvent PaintEvent MouseEvent KeyEvent

47 Event Listeners Event Listener Event Handler
Contains different methods to handle different event Add method of syntax add<Listener Name> to add listener to component e.g. addActionListener() Slide Instructor’s Notes: An “Event Listener” is an object which handles a particular kind of event delegated by component. When component receives input, an event of the appropriate type is constructed, and this event is passed to listeners as a parameter to method call. A listener implements the interface that contains event handling method.

48 Event Listeners Table : Event Listener Interfaces and their methods
Slide Instructor’s Notes: Table lists the listener interfaces, with the interface methods and add<ActionListener Name>() methods. We can add WindowListener to frame class by using method addWindowListener() and passing object of class which implements WindowListener. We can remove event listner from a component’s list by using a method remove<Listener Name>(), passing in the listner to be removed. Continued …

49 Event Listeners Table : Event Listener Interfaces and their methods
Slide Instructor’s Notes:

50 Event Listeners Adding Listener to component : Method 1 // Test.java
import java.awt.*; import java.awt.event.*; public class Test extends Frame{ public static void main(String args[]) { Frame mainFrame =new Test (); myWinList myWL=new myWinList(); mainFrame.setVisible(true); mainFrame.setBounds(10,10,200,200); mainFrame.addWindowListener(myWL); } Slide Instructor’s Notes: Test is the class which extends Frame I.e. it displays window on screen. When we just create window, we can not close it. This is because event which we are firing on window is not getting processed. To process user interaction event we have to add Listener class to an component. Adding listener to component can be done in 3 ways, two by using listeners and one is using adapter. In this chapter we will see two methods of using listener interface. Method 1 : We define class myWinList which implements WindowListener. Then create an object of this listener class and using addWindowListener() method we add listener to window class.

51 Event Listeners // myWinList class implements WindowListner
class myWinList implements WindowListener{ public void windowActivated ( WindowEvent we) {} public void windowClosed ( WindowEvent we) {} public void windowClosing ( WindowEvent we) {System.exit(0);} public void windowDeactivated ( WindowEvent we){} public void windowDeiconified ( WindowEvent we){} public void windowIconified ( WindowEvent we) {} public void windowOpened ( WindowEvent we) {} } Slide Instructor’s Notes: This myWinList class implements all the methods of WindowListener interface. We put code for application exit in windowClosing() method (). This method gets called when we try to close window. All other methods are have empty implementations. WindowEvent , is a low-level event that indicates that a window has changed its status. This low-level event is generated by a Window object when it is opened, closed, activated, deactivated, iconified, or deiconified, or when focus is transfered into or out of the Window.

52 Event Listeners Adding Listener to component : Method 2 // Test.java
import java.awt.*; import java.awt.event.*; public class Test extends Frame implements WindowListener{ public static void main(String args[]) { Frame mainFrame =new Test (); myWinList myWL=new myWinList(); mainFrame.setVisible(true); mainFrame.setBounds(10,10,200,200); } Test(){ addWindowListener(this); Slide Instructor’s Notes: In second method : Class Test itself implements WindowListener. Class test implements all method of WindowListener. Code for closing window is written in windowClosing() method. We addWindowListener for Test class in it’s constructor and pass it reference of itself. So that all events are handled by class itself.

53 Event Listeners public void windowActivated ( WindowEvent we) {}
public void windowClosed ( WindowEvent we) {} public void windowClosing ( WindowEvent we) {System.exit(0);} public void windowDeactivated ( WindowEvent we){} public void windowDeiconified ( WindowEvent we){} public void windowIconified ( WindowEvent we) {} public void windowOpened ( WindowEvent we) {} } // End Test Slide Instructor’s Notes:

54 Event Listeners Example : How to Use ActionListener for Button
import java.awt.*; import java.awt.event.*; public class Test extends Frame { public static void main(String args[]) { Frame mainFrame =new Test (); myAction myA = new myAction(); Button b1=new Button("Button 1"); mainFrame.setVisible(true); mainFrame.setBounds(10,10,200,200); mainFrame.setLayout(null); b1.setBounds(40,100,80,40); b1.addActionListener(myA); mainFrame.add(b1); } //main } //Class Test Slide Instructor’s Notes: Above example shows how ActionListener is used for handling the button events. We can add ActionListener to button by using addActionListener( ) method, pass object of ActionListener class to it.

55 Event Listeners Output after pressing button b1: { //call method 1 }
class myAction implements ActionListener { public void actionPerformed ( ActionEvent ae){ System.out.println(ae.getActionCommand()); } } //Class myAction Output after pressing button b1: Slide Instructor’s Notes: getActionCommand() Returns the command name of the action event fired by this button. If the command name is null (default) then this method returns the label of the button.As we have not set the command name in above example method return caption of button. Depending upon command name we can have different code for different buttons (using if.. Then.. Else ..). e.g. if (ae.getActionCommand()).equals(“Add”)) { //call method 1 } else if (ae.getActionCommand()).equals(“Modify”)) //call method 2 Figure 1 shows output of executing sample program.

56 Event Adapters Event Adapters : Empty implementation of Listener interface Example : import java.awt.*; import java.awt.event.*; public class Test extends Frame { public static void main(String args[]) { Frame mainFrame =new Test (); myWinAd myWA = new myWinAd (); mainFrame.setVisible(true); mainFrame.setBounds(10,10,200,200); mainFrame.addWindowListener(myWA); } }//Class Test End class myWinAd extends WindowAdapter { public void windowClosing ( WindowEvent we){ System.exit(0); } } //Class Adapter End Slide Instructor’s Notes: While using Event listener interfaces we have to implement each and every method form that interface. Some Listener interfaces have more than one methods and we might not need all those in our application then we have to give empty implementation for those methods which are not needed. This makes inconvenience while writing code. To avoid this, we can use Adapter classes. Adapter classes have empty implementation for all the methods of Listeners. So when we extend the Adapter needed we can just use method we need

57 Event Adapters Adapter classes and corresponding interfaces
Slide Instructor’s Notes: Adapter classes are only for those listeners which have more than one method in it. Other Listeners than WindowListener, ComponentListener, ContainerListener, KeyListener, MouseListener, MouseMotionListener and FocusListener are have only one method in it, there fore no use of defining adapter classes for them.

58 Events : Summary Event is a platform-independent class
Event handling is done by using Listeners and Adapters Event delegation model entities : Event, Source, Receiver and Listener Event listener Contains different methods to handle different event Using add<Listener Name> method of component we can add listener Event Adapters : Empty implementation of Listener interface Slide Instructor’s Notes: Event is a platform independent class to represent event. In java we use Listener and adapters for event handling. For event handling java uses Event Delegation Model, which has four entities involved Event, Source, Receiver, Listener. Event listeners has different methods to handle events. There are some adapter classes provided as a wrapper to listener classes. There adapter classes has empty implementation of all methods in listener classes. We can add listener to component using method add<Listener Name>

59 : Quiz Which are the entities in Event-Delegation model ?
What is the use of event listeners ? Which method of component is used to attach event listener to component ? What getActionCommand() method returns ? What are event adapters ? Slide Instructor’s Notes:

60 10.0 Layout Managers : Overview
Introduction Layout Managers defines the interface to set Layout for containers Performs layout management for the components within the container Objective After completing this Topic, you will be able to create GUI with specified appearance robust by handling runtime exceptions. In this Topic we will cover   Types of Layout Managers   GrigBag Layout Manager Slide Instructor’s Notes: Defines the interface for classes that know how to lay out Containers. Layout management is the process of determining the size and position of components. By default, each container has a layout manager which is an object that performs layout management for the components within the container. Components can provide size and alignment hints to layout managers, but layout managers have the final control on the size and position of those components. We are considering GridBag Layout manager as a separate topic because of it’s vast scope.

61 Layout Manager Overview
Defines the interface for classes that know how to lay out Containers. Recommend that we use layout managers We can perform layout without them. By setting a container's layout property to null, we make the container use no layout manager (absolute positioning). In absolute positioning, we must specify the size and position of every component within that container. Drawback of absolute positioning :It doesn't adjust well when the top-level container is resized Slide Instructor’s Notes: Layout Manager Defines the interface for classes that know how to lay out Containers. Although it is recommend that we use layout managers, We can perform layout without them. By setting a container's layout property to null, we make the container use no layout manager. This strategy is called as absolute positioning, we must specify the size and position of every component within that container. One drawback of absolute positioning is that it doesn't adjust well when the top-level container is resized, nor does it adjust well to differences between users and systems, such as different font sizes. Some layout managers automatically put space between components; others don't. Foe those which do not put space themselves, we have to specify the amount of space between components. No matter what the layout manager, you can affect the apparent amount of space between components by adding empty borders to components. The best candidates for empty borders are components that typically have no default border, such as panels and labels.

62 Types of Layout Managers
FlowLayout Manager GridLayout Manager BorderLayout Manager CardLayout Manager GridBagLayout Manager Slide Instructor’s Notes: There are five types of Layout managers : 1> Flow Layout Manager : The FlowLayout is the default manager type for panels and applets. It arranges components in horizontal row I.e. simply lays out components from left to right, starting new rows, if necessary. 2> Grid Layout Manager : GridLayout simply makes a bundle of components equal in size and displays them in the requested number of rows and columns. 3> Border Layout Manager : BorderLayout is the default layout manager for content pane. The content pane is the main container in all frames, applets, and dialogs. A BorderLayout has five areas available to hold components: north, south, east, west, and center. All excess space is placed in the center area. 4> Card Layout Manager : The CardLayout class lets you implement an area that contains different components at different times. A CardLayout is normally controlled by using a combo box, with the state of the combo box determining which panel I.e. group of components the CardLayout displays. An option for using CardLayout is a tabbed pane. 5> GridBag Layout : GridBagLayout is a advanced, flexible layout manager. It aligns components by placing them within a grid of cells, allowing some components to span more than one cell. The rows in the grid can have different heights, and grid columns can have different widths. As GridBagLayout is advanced and has many features, we will see GridBagLayout Manager in separate topic.

63 Types of Layout Managers
FlowLayout Manager Default manager type for panels and applets Arranges components in horizontal row (left to right, starting new rows, if necessary). The FlowLayout class has three constructors: public FlowLayout() public FlowLayout(int alignment) public FlowLayout(int alignment, int horizontalGap, int verticalGap) Slide Instructor’s Notes: FlowLayout puts components in a row. If the horizontal space in the container is too small to put all the components in one row, FlowLayout 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. You can specify that it stick to the left or right side by using a FlowLayout constructor that takes an alignment argument. You can also specify how much vertical or horizontal padding is put around the components. The FlowLayout class has three constructors: public FlowLayout() public FlowLayout(int alignment) The alignment argument can be FlowLayout.LEADING, FlowLayout.CENTER, or FlowLayout.TRAILING. When the FlowLayout controls a container with a left-to-right component orientation (the default), LEADING specifies that the components be left-aligned and TRAILING specifies right alignment. public FlowLayout(int alignment, int horizontalGap, int verticalGap) The horizontalGap and verticalGap arguments specify the number of pixels to put between components. If you don't specify a gap value, FlowLayout uses 5 for the default gap value.

64 Types of Layout Managers
FlowLayout Manager Example import java.awt.*; public class Test extends Frame { public static void main(String args[]) { Frame mainFrame =new Test (); myAction myA = new myAction(); mainFrame.setVisible(true); mainFrame.setBounds(10,10,350,100); mainFrame.setLayout(new FlowLayout()); // Important Line mainFrame.add(new Button("Button 1")); mainFrame.add(new Button("Button 2")); mainFrame.add(new Button("Button 3")); mainFrame.add(new Button("Button 4")); } Slide Instructor’s Notes: Above is the program to set FlowLayout Manager to frame i.e. application window. By passing FlowLayout manager object to setLayout() method of frame we can specify layout for frame.

65 Types of Layout Managers
FlowLayout Manager Example Output Figure 1 If we change size of windows then Output Figure 2 Slide Instructor’s Notes: The figure 1 shows how output when we execute program. All buttons are get arranged in one row.But as we change the window size placement of buttons gets changed as shown in figure 2 and 3. Figure 3

66 Types of Layout Managers
FlowLayout Manager If we change line commented as //Important Line mainFrame.setLayout(new FlowLayout()); mainFrame.setLayout(new FlowLayout(0)); Figure 1 Slide Instructor’s Notes: We can pass parameter to FlowLayout constructor for alignment of components as new FlowLayout(0), where 0 : specifies Left alignment, 1 : specifies center alignment, and 2 : specifies right alignment. When we specify parameter as 0 in code we get out put as shown in figure 1 and 2, buttons are left aligned. Figure 2

67 Types of Layout Managers
GridLayout Manager Places components in a grid of cells Each component takes all the available space within its cell Resize the GridLayout window, changes the cell size The GridLayout class has two constructors public GridLayout(int rows, int columns) public GridLayout(int rows, int columns, int horizontalGap, int verticalGap) ) Slide Instructor’s Notes: A GridLayout 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 we resize the window having GridLayout manager, we will see that the GridLayout changes the cell size so that the cells are as large as possible, given the space available to the container. The GridLayout class has two constructors: public GridLayout(int rows, int columns) At least one of the rows and columns arguments must be nonzero; the rows argument has precedence over the columns argument. public GridLayout(int rows, int columns, int horizontalGap, int verticalGap) The horizontalGap and verticalGap arguments to the second constructor allow you to specify the number of pixels between cells. If you don't specify gaps, their values default to zero.

68 Types of Layout Managers
GridLayout Manager Example : import java.awt.*; public class Test extends Frame { public static void main(String args[]) { Frame mainFrame =new Test (); myAction myA = new myAction(); mainFrame.setVisible(true); mainFrame.setBounds(10,10,400,100); mainFrame.setLayout(new GridLayout(0,2)); // Important Line mainFrame.add(new Button("Button 1")); mainFrame.add(new Button("Button 2")); mainFrame.add(new Button("Button 3")); mainFrame.add(new Button("Button 4")); } Slide Instructor’s Notes: Above is the program to set GridLayout Manager to frame i.e. application window. By passing GridLayout manager object to setLayout() method of frame we can specify layout for frame.

69 Types of Layout Managers
GridLayout Manager : Example Output Figure 1 If we change size of windows then Output Figure 2 Slide Instructor’s Notes: The figure 1 shows how output when we execute program. All buttons are get arranged in one row.But as we change the window size, size of buttons gets changed as shown in figure 2 and 3. Figure 3

70 Types of Layout Managers
GridLayout Manager : If we change line commented as //Important Line mainFrame.setLayout(new GridLayout(0,2)); mainFrame.setLayout(new GridLayout(0,2,10,10)); Figure 1 And If we change line commented as //Important Line mainFrame.setLayout(new GridLayout(0,2)); mainFrame.setLayout(new GridLayout(0,2, 0,10)); Slide Instructor’s Notes: We can pass parameter to GridLayout constructor for The horizontalGap and verticalGap arguments so that we can specify the number of pixels between cells. If you don't specify gaps, their values default to zero. In figure 1 : we have mentioned both horizontalGap and verticalGap In figure 2 : we have mentioned only horizontalGap Figure 2

71 Types of Layout Managers
BorderLayout Manager A BorderLayout has five areas : PAGE_START, PAGE_END, LINE_START, LINE_END, and CENTER. Instead of using PAGE_START, LINE_START, PAGE_END, LIEN_END , we can use NORTH, SOUTH, EAST, and WEST. By default component will get added to the center By default BorderLayout does not put gap between the components Constructors : public BorderLayout() public BorderLayout(int horizontalgap, int verticalgap) Slide Instructor’s Notes: If you enlarge the window, 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. Often, a container uses only one or two of the areas of the BorderLayout — just the center, or center and bottom, etc. a BorderLayout has five areas. These areas are specified by the BorderLayout constants PAGE_START, PAGE_END, LINE_START, LINE_END, and CENTER. It is strongly recommend that we specify the component's location (for example, BorderLayout.LINE_END) as one of the arguments to the add method. If we leave it out, the component will be added to the center. If we find that a component is missing from a container controlled by a BorderLayout, make sure that we have specified the component's location and that we didn't put another component in the same location. BorderLayout defines a Two constructors and some methods for adding space between components. By default, a BorderLayout puts no gap between the components. We can specify gaps (in pixels) using the constructor: BorderLayout(int horizontalGap, int verticalGap) We can also use the following methods to set the horizontal and vertical gaps, respectively : void setHgap(int) void setVgap(int) BorderLayout() :   Constructs a new border layout with no gaps between components. BorderLayout(int horizontalGap, int verticalGap) : Constructs a border layout with the specified gaps between components.

72 Types of Layout Managers
BorderLayout Manager Example : import java.awt.*; public class Test extends Frame { public static void main(String args[]) { // All frame creation and display code will come here mainFrame.setLayout(new BorderLayout()); mainFrame.add(new Button("Button(PAGE_START)"), BorderLayout.PAGE_START); Button button = new Button("Button(CENTER)"); button.setSize(new Dimension(200, 100)); mainFrame.add(button, BorderLayout.CENTER); mainFrame.add(new Button("Button(LINE_START)"), BorderLayout.LINE_START); mainFrame.add(new Button("LongButton(PAGE_END)"), BorderLayout.PAGE_END); mainFrame.add(new Button("5(LINE_END)"), BorderLayout.LINE_END); } Slide Instructor’s Notes: Above is the program to set GridLayout Manager to frame i.e. application window. By passing GridLayout manager object to setLayout() method of frame we can specify layout for frame. While adding component to frame I.e. application window we have set the area where that component should get displayed. Instead of using PAGE_START, LINE_START, PAGE_END, LIEN_END , we can use NORTH, SOUTH, EAST, and WEST.

73 Types of Layout Managers
BorderLayout Manager Example Output Figure 1 If we change size of windows then Output Figure 2 Slide Instructor’s Notes: The figure 1 shows how output when we execute program. All buttons are get arranged in one row.But as we change the window size , size of buttons gets changed as shown in figure 2 and 3. Figure 3

74 Types of Layout Managers
BorderLayout Manager : If we change line commented as //Important Line mainFrame.setLayout(new BorderLayout()); mainFrame.setLayout(new BorderLayout(10,10)); Figure 1 BorderLayout Manager : If we change line commented as //Important Line mainFrame.setLayout(new BorderLayout()); mainFrame.setLayout(new BorderLayout(0,10)); Slide Instructor’s Notes: We can pass parameter to BorderLayout constructor for The horizontalGap and verticalGap arguments so that we can specify the number of pixels between components. If you don't specify gaps, their values default to zero. In figure 1 : we have mentioned both horizontalGap and verticalGap In figure 2 : we have mentioned only horizontalGap Figure 2

75 Types of Layout Managers
CardLayout Manager CardLayout treats each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards. The first component added to a CardLayout object is the visible component when the container is first displayed. The CardLayout API : void first(Container) void next(Container) void previous(Container) void last(Container) void show(Container, String) Constructors : public CardLayout() public CardLayout(int horizontalgap, int verticalgap) Slide Instructor’s Notes: A CardLayout object is a layout manager for a container. It treats each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards. The first component added to a CardLayout object is the visible component when the container is first displayed. The CardLayout class helps us to manage two or more components that share the same display space. When using CardLayout, we need to provide a way to let the user choose between the components. Each component a CardLayout manages is like a playing card in a stack, where only the top card is visible at any time. We can choose the card that's showing in any of the following ways: By asking for first or last card, in the order it was added to the container. (Using API : first() , last() , show()) By flipping the deck backwards or forwards. (Using API : next() , previous(), show()) By specifying a card name. When we add a component to a container that a CardLayout manages, we must specify a string that identifies the component. Constructors : public CardLayout() : Creates a new card layout with gaps of size zero. public CardLayout(int horizontalgap, int verticalgap) : Creates a new card layout with the specified horizontal and vertical gaps.

76 Types of Layout Managers
CardLayout Manager Example : import java.awt.*; import java.awt.event.*; public class Card extends Panel { private Panel cardPanel = new Panel (); private CardLayout cardLayout= new CardLayout(); private Panel controlPanel = new Panel(); private Button b1 = new Button ("Panel 1"); private Button b2 = new Button ("Panel 2"); // Constructor here public static void main(String args[]){ Frame f= new Frame("Example"); Card card = new Card (); // Check the Constructor on next slide f.add(card); f.pack(); f.setVisible(true); } //Main } //Class Above is the program show how to use CardLayout Manager in application. We define class which extends Panel. We also define some private variables as cardPanel , cardLayout, controlPanel , b1 and b2 , which get used in Constructor. We create two Buttons and set ActionListener for them in Constructor. These Buttons are use as a option selector in this sample application. In main() method we create frame and object of Card class. Add Card object to frame. Then we call pack method on frame and set frame visible to true. public void pack() : This causes Window to be sized to fit the preferred size (The preferred size of a component is the minimum component size that will allow the component to display normally) and layouts of its sub-components. If the window and/or its owner are not yet displayable, both are made displayable before calculating the preferred size. The Window will be validated after the preferred Size is calculated.

77 Types of Layout Managers
1 2 public Card(){ Panel p1 = new Panel(); Panel p2 = new Panel(); p1.add(new TextField("This is Panel 1")); p2.add(new Button("This is Panel 2")); cardPanel.setLayout(cardLayout); cardPanel.add(p1,"1"); cardPanel.add(p2,"2"); add(cardPanel,BorderLayout.CENTER); b1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae) { cardLayout.first(cardPanel); }}); b2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { cardLayout.last(cardPanel); }}); Panel cp_1 = new Panel(); Panel cp_2 = new Panel(); cp1.add(b1); cp1.add(b2); controlPanel.add(cp1); controlPanel.add(cp2); add(controlPanel,BorderLayout.SOUTH); } //Constructor Slide Instructor’s Notes: Above is the constructor for card class. In constructor we create actual card pack means we create two panes , one of then only visible at a time depending upon user input. One panel contains TextField and other contains Button. We set cardLayout to cardPanel and add two already created panels to it. Add cardPanel to card with setting BorderLayout.CENTER. Then here we set ActionListener for buttons b1 and b2. In ActionListener write code to display required panel, using first() and last() methods of cardLayout. We create Panel cp_1 and cp_2 for holding Buttons b1 and b2. Then these panels cp_1 and cp_2 , we add them to controlPanel. Add controlPanel to card which is outer most panel with setting BorderLayout.SOUTH. Now we will see the summary of this program because program is little difficult to understand. Summary of program : We create on frame (f) and add it panel object (card) of our class. In that outer panel ( card ) we set two Panels called cardPanel and controlPanel. cardPanel is used to show options on it, like TextField or Button and controlPanel is used to show buttons depending upon user action on them options are . cardPanel itself contain two panels p1 and p2 which contains actual options I.e. TextField and Button on them respectively. controlPanel contains two panels cp_1 and cp_2 which has Buttons b1 and b2 inside them respectively. Continue

78 Types of Layout Managers
CardLayout Manager Example Output Figure 1 Figure 2 Slide Instructor’s Notes: The figure 1 shows how output when we execute program.By default panel 1 is getting displayed (First card). The figure 2 shows what is the output when we click the button with caption “Panel 2” (Second card). The figure 3 shows what is the output when we click the button with caption “Panel 1” (First card). There fore CardLayout is used, when we need functionality as a tabbed control.I.e. when depending on some option we need to show different set of components on screen. Figure 3

79 GridBagLayout Manager
GridBagLayout is the most sophisticated, flexible layout manager This layout manager aligns components by placing them within a grid of cells Allows some components to span more than one cell. GridBagConstraints class used to hold all layout position information Constructor : public GridBagLayout() Slide Instructor’s Notes: GridBagLayout is the most sophisticated, flexible layout manager the Java platform provides. This layout manager aligns components by placing them within a grid of cells, allowing some components to span more than one cell. The GridBagLayout class is a flexible layout manager that aligns components vertically and horizontally, without requiring that the components be of the same size, I.e. the rows in the grid aren't necessarily all the same height; similarly, grid columns can have different widths. GridBagConstraints class used to hold all layout position information. We will see details about GridBagConstraints in next slide Each component managed by a GridBagLayout is associated with an instance of GridBagConstraints Constructor: public GridBagLayout() : Creates a grid bag layout manager.

80 GridBagLayout Manager
GridBagConstraints public GridBagConstraints(int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty, int anchor, int fill, Insets insets, int ipadx, int ipady) Parameters: gridx - The initial gridx value. gridy - The initial gridy value. gridwidth - The initial gridwidth value. gridheight - The initial gridheight value. weightx - The initial weightx value. weighty - The initial weighty value. anchor - The initial anchor value. fill - The initial fill value. insets - The initial insets value. ipadx - The initial ipadx value. ipady - The initial ipady value. GridBagConstraints : public GridBagConstraints(int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty, int anchor, int fill, Insets insets, int ipadx, int ipady) Creates a GridBagConstraints object with all of its fields set to the passed-in arguments. Note: Because the use of this constructor hinders readability of source code, this constructor should only be used by automatic source code generation tools. Parameters: gridx : Specifies the cell containing the leading edge of the component's display area, where the first cell in a row has gridx = 0. gridy : Specifies the cell at the top of the component's display area, where the uppermost cell has gridy = 0. gridwidth : Specifies the number of cells in a row for the component's display area. gridheight : Specifies the number of cells in a column for the component's display area. weightx : Specifies how to distribute extra horizontal space. weighty : Specifies how to distribute extra vertical space anchor : This field is used when the component is smaller than its display area. It determines where, within the display area, to place the component. fill : This field is used when the component's display area is larger than the component's requested size. It determines whether to resize the component insets : This field specifies the external padding of the component, the minimum space between the component and the edges of its display area. ipadx : This field specifies the internal padding of the component, how much space to add to the minimum width of the component. ipady : This field specifies the internal padding, that is, how much space to add to the minimum height of the component. The number of rows and columns in a GridBagLayout is the greater of the number of cells used or the size of rowHeights and columnWidths arrays if given. Default size do a column or row is that of the biggest component in it or corresponding entry in arrays rowHeights and columnWidths if specifies. Stretchiness of columns or rows is controlled by corresponding weight.

81 GridBagLayout Manager
import java.awt.*; import java.awt.event.*; public class GB extends Panel { private Panel p1=new Panel(); private Panel p2=new Panel(); public GB() { p1.setLayout(new GridLayout(2,1)); p1.add(new Button("Panel1UP")); p1.add(new Button("Panel1Down")); p2.setLayout(new GridLayout(2,1)); p2.add(new Button("Panel2UP")); p2.add(new Button("Panel2Down")); setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx=0; c.gridy=0; add(new Button("TopLeft"),c); c.gridx=1; add(new Button("TopCentre"),c); c.gridx=2; add(new Button("TopRight"),c); c.gridy=1; add(p1,c); add(p2,c); } public static void main(String args[]) { Frame f=new Frame("CTS"); f.add(new GB()); f.pack(); f.setVisible(true); 1 2 Above is the program show how to use GridBagLayout Manager in application. We define class which extends Panel. In main() method we create frame and object of GB class. Then we call pack method on frame and set frame visible to true. public void pack() : This causes Window to be sized to fit the preferred size and layouts of its sub-components. If the window and/or its owner are not yet displayable, both are made displayable before calculating the preferred size. The Window will be validated after the preferred Size is calculated. In above program, in the constructor, we have created two panels namely p1 and p2. Both individually use GridLayout and each panel contains two buttons. Using setLayout() we set the Layout of current panel to GridBagLayout. An object ‘c’ of GridBagConstraints is created and used for positioning all the components. There are three columns and two rows in above example. Which cell to add the component in, is decided by setting gridx and gridy properties of the GridBagConstraint. The output of above code is shown on the next page. Continue

82 GridBagLayout Manager
Controlling the cell size for a component How to specify if a component occupies multiple cells ? The gridwidth and gridheight parameters Example In the previous example if we modify the code to make ‘panel1’ occupy first and second columns, the output will look as - The code is like this c.gridx=0; c.gridy=1; c.gridwidth=2; add(p1,c); c.gridx=2; c.gridwidth=1; add(p2,c); If the components don’t fit in a single grid cell then you can make it span over multiple cells. You can do this by setting the gridwidth and gridheight properties of the GridBagConstraints. The gridwidth specifies how many columns the component will occupy and gridheight specifies how many rows it will span. In the previous example if we are to modify the code to make ‘panel1’ occupy first and second columns, then replace the code in yellow background with the above one. The output will be as shown in the figure.

83 Summary : Layout Managers
Layout Managers defines the interface for classes that know how to layout Containers. Types of LayoutManager : FlowLayout Manager, GridLayout Manager, BorderLayout Manager, CardLayout Manager, GridBagLayout Manager. FlowLayout Manager is default manager type for panels and applets. FlowLayout Manager arranges components in horizontal row . GridLayout Manager places components in a grid of cells. In GridLayout Manager each component takes all the available space within its cell. BorderLayout has 5 areas: PAGE_START, PAGE_END, LINE_START, LINE_END, and CENTER. In BorderLayout By default component will get added to the center. CardLayout treats each component in the container as a card. While using CardLayout Only one card is visible at a time. A GridBagConstraints object is associated with every component that contains detail information regarding the position of the component. Slide Instructor’s Notes:


Download ppt "8.0 AWT Components : Overview"

Similar presentations


Ads by Google