Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
G Devender 1 UNIT II Constructors and Methods APPLETS Applet Tag in HTML Parameter Tag Some Sample Applets AWT Button and Label Button Class Label Class Applet with Buttons and Labels Button in Action Check Box and List Check Box Check Box Group List Menu Text Components Text Component Class Text Field Class Text Area Class Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 2 Applets An applet is a program that can be referenced by the HTML source code of a webpage. It is dynamically downloaded from a webserver to a browser. The applet then executes within the environment provided by the browser. Alternatively, we can use a tool such as an appletviewer to run it. Loading Applets in a Web Page The applet will be executed by a Java-enabled web browser when it encounters the APPLET tag within the HTML file. To view and test an applet more conveniently, simply include a comment at the head of your Java source code file that contains the APPLET tag. This way, your code is documented with the necessary HTML statements needed by your applet, and you can test the compiled applet by starting the applet viewer with your Java source code file specified as the target. Here is an example of such a comment: /* <applet code="MyApplet.class" width=200 height=60> </applet> */ This comment contains an APPLET tag that will run an applet called MyApplet in a window that is 200 pixels wide and 60 pixels high. Since the inclusion of an APPLET command makes testing applets easier. appletviewer MyApplet.html Once you know your applet runs within the appletviewer, it is important to test your applet running in a web browser by loading the applet's web page into the browser window. The browser can retrieve the class files either from the internet or from the local working directory used during development. If you make changes to your applet's code while it is loaded in the browser, then you must recompile the applet and press the "Shift + Reload" button in the browser to load the new version. Applets vs. Applications Applet Application 1. Downloaded from web and run on a browser 2. Applets have many restrictions: a. cannot read/write to local filesystems b. cannot communicate with any server other than from where it is loaded c. cannot run any program on user’s system 3. They use init(), start(), stop() lifecycle methods. 1. stand-alone program 2. They do not have restrictions that applets have. They are typically executed by JVM 3. They use only main() function When to write Applets vs. Applications In the early days of Java, one of the critical advantages that Java applets had over Java applications was that applets could be easily deployed over the web while Java applications required a more cumbersome installation process. Additionally, since applets are downloaded from the internet, by default they have to run in a restricted security environment, called the "sandbox", to ensure they don't perform any destructive operations on the user's computer, such as reading/writing to the file system. Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 3 The Applet Class The Applet class defines the methods shown in Table 19-1. Applet provides all necessary support for applet execution, such as starting and stopping. It also provides methods that load and display images, and methods that load and play audio clips. Applet extends the AWT class Panel. In turn, Panel extends Container, which extends Component. These classes provide support for Java's window-based, graphical interface. Thus, Applet provides all of the necessary support for window-based activities. Table 19-1 The Methods Defined by Applet Method void destroy( ) Description Called by the browser just before an applet is terminated. Your applet will override this method if it needs to perform any cleanup prior to its destruction. AppletContext getAppletContext( ) Returns the context associated with the applet. String getAppletInfo( ) Returns a string that describes the applet. AudioClip getAudioClip(URL url) Returns an AudioClip object that encapsulates the audio clip found at the location specified by url. AudioClip getAudioClip(URL url, String clipName) Returns an AudioClip object that encapsulates the audio clip found at the location specified by url and having the name specified by clipName. URL getCodeBase( ) Returns the URL associated with the invoking applet. URL getDocumentBase( ) Returns the URL of the HTML document that invokes the applet. Image getImage(URL url) Returns an Image object that encapsulates the image found at the location specified by url. Image getImage(URL url, String imageName) Returns an Image object that encapsulates the image found at the location specified by url and having the name specified by imageName. Locale getLocale( ) Returns a Locale object that is used by various locale-sensitive classes and methods. String getParameter(String paramName) Returns the parameter associated with paramName .null is returned if the specified parameter is not found. String[ ] [ ] getParameterInfo( ) Returns a String table that describes the parameters recognized by the applet. Each entry in the table must consist of three strings that contain the name of the parameter, a description of its type and/or range, and an explanation of its purpose. void init( ) Called when an applet begins execution. It is the first method called for any applet. Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 4 boolean isActive( ) static final AudioClip newAudioClip(URL url) void play(URL url) void play(URL url, String clipName) void resize(Dimension dim) void resize(int width, int height) final void setStub(AppletStub stubObj) void showStatus(String str) void start( ) void stop( ) Returns true if the applet has been started. It returns false if the applet has been stopped. Returns an AudioClip object that encapsulates the audio clip found at the location specified by url. This method is similar to getAudioClip() except that it is static and can be executed without the need for an Applet object. If an audio clip is found at the location specified by url, the clip is played. If an audio clip is found at the location specified by url with the name specified by clipName, the clip is played. Resizes the applet according to the dimensions specified by dim. Dimension is a class stored inside java.awt. It contains two integer fields: width and height. Resizes the applet according to the dimensions specified by width and height. Makes stubObj the stub for the applet. This method is used by the run-time system and is not usually called by your applet. A stub is a small piece of code that provides the linkage between your applet and the browser Displays str in the status window of the browser or applet viewer. If the browser does not support a status window, then no action takes place. Called by the browser when an applet should start (or resume) execution. It is automatically called after init() when an applet first begins. Called by the browser to suspend execution of the applet. Once stopped, an applet is restarted when the browser calls start() The Lifecycle of an Applet A java application begins execution at the main() methods of a class. An applet executes within an environment provided by a web browser or a tool such as the appletviewer. Therefore it does not have a main() method. Instead there are four methods that are called during the life cycle of an applet: init(), start(), stop() and destroy() Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 5 They are defined by java.applet.Applet class and therefore are inherited by every applet. When an applet begins, the AWT calls the following methods, in this sequence: init() start() paint() When an applet is terminated, the following sequence of method calls takes place: stop() destroy() Let's look more closely at these methods. init() - The init() method is the first method to be called. This is where you should initialize variables. This method is called only once during the run time of your applet. start() - The start() method is called after init(). It is also called to restart an applet after it has been stopped. Whereas init() is called once—the first time an applet is loaded— start() is called each time an applet's HTML document is displayed onscreen. So, if a user leaves a web page and comes back, the applet resumes execution at start(). paint() - The paint() method is called each time your applet's output must be redrawn. This situation can occur for several reasons. For example, the window in which the applet is running may be overwritten by another window and then uncovered. Or the applet window may be minimized and then restored. paint() is also called when the applet begins execution. Whatever the cause, whenever the applet must redraw its output, paint() is called. The paint() method has one parameter of type Graphics. This parameter will contain the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever output to the applet is required. stop() - The stop() method is called when a web browser leaves the HTML document containing the applet—when it goes to another page, for example. When stop() is called, the applet is probably running. You should use stop() to suspend threads that don't need to run when the applet is not visible. You can restart them when start() is called if the user returns to the page. destroy() - The destroy() method is called when the environment determines that your applet needs to be removed completely from memory. At this point, we free up any resources the applet may be using. The stop() method is always called before destroy(). Simple Applet Display Methods Applets are displayed in a window and they use the AWT to perform input and output. Although we will examine the methods, procedures, and techniques necessary to fully handle the AWT windowed. To output a string to an applet, use drawString(), which is a member of the Graphics class. It is called from within either update() or paint(). It has the following general form: void drawString(String message, int x, int y) Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 6 Here, message is the string to be output beginning at x, y. In a Java window, the upper left corner is location 0, 0. The drawString() method will not recognize newline characters. If you want to start a line of text on another line, you must do so manually, specifying the precise X, Y location where you want the line to begin. To set the background color of an applet's window, use setBackground(). To set the foreground color, use setForeground(). These methods are defined by Component, and they have the following general forms: void setBackground(Color newColor) void setForeground(Color newColor) Here, newColor specifies the new color. The class Color defines the constants shown here that can be used to specify colors: Color.BLACK Color.MAGENTA Color.BLUE Color.ORANGE Color.CYAN Color.PINK Color.DARKGRAY Color.RED Color.GRAY Color.WHITE Color.GREEN Color.YELLOW Color.LIGHTGRAY For example, this sets the background color to green and the text color to red: setBackground(Color.GREEN); setForeground(Color.RED); A good place to set the foreground and background colors is in the init() method. You can change these colors as often as necessary during the execution of your applet. The default foreground color is black. The default background color is light gray. You can obtain the current settings for the background and foreground colors by calling getBackground() and getForeground(), respectively. They are also defined by Component and are shown here: Color getBackground() Color getForeground() Here is a very simple applet that sets the background color to cyan, the foreground color to red, and displays a message that illustrates the order in which the init(), start(), and paint() methods are called when an applet starts up: /* A simple applet that sets the foreground and background colors and outputs a string. */ import java.awt.*; import java.applet.*; /* <applet code="Sample.class" width=300 height=50> </applet> */ public class Sample extends Applet{ String str=” “; Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 7 // set the foreground and background colors. public void init() { setBackground(Color.CYAN); setForeground(Color.RED); str += "Inside init( ) —"; } // Initialize the string to be displayed. public void start() { str += " Inside start( ) —"; } // Display str in applet window. public void paint(Graphics g) { str += " Inside paint( )."; g.drawString(str, 10, 30); } } This applet generates the window shown here: The HTML APPLET Tag The APPLET tag is used to start an applet from both an HTML document and from an applet viewer. An applet viewer will execute each APPLET tag that it finds in a separate window, while web browsers like Netscape Navigator, Internet Explorer, and HotJava will allow many applets on a single page. So far, we have been using only a simplified form of the APPLET tag. Now it is time to take a closer look at it. The syntax for the standard APPLET tag is shown here. Bracketed items are optional. <APPLET [CODEBASE = codebaseURL] CODE = appletFile [ALT = alternateText] [NAME = appletInstanceName] WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels] > [< PARAM NAME = AttributeName VALUE = AttributeValue>] [< PARAM NAME = AttributeName2 VALUE = AttributeValue>] . . . [HTML Displayed in the absence of Java] </APPLET> Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 8 Let's take a look at each part now. CODEBASE CODEBASE is an optional attribute that specifies the base URL of the applet code which is the directory that will be searched for the applet's executable class file. The HTML document's URL directory is used as the CODEBASE if this attribute is not specified. The CODEBASE does not have to be on the host from which the HTML document was read. CODE CODE is a required attribute that gives the name of the file containing your applet's compiled .class file. This file is relative to the code base URL of the applet, which is the directory that the HTML file was in or the directory indicated by CODEBASE if set. ALT The ALT tag is an optional attribute used to specify a short text message that should be displayed if the browser understands the APPLET tag but can't currently run Java applets. This is distinct from the alternate HTML you provide for browsers that don't support applets. NAME NAME is an optional attribute used to specify a name for the applet instance. Applets must be named in order for other applets on the same page to find them by name and communicate with them. To obtain an applet by name, use getApplet(), which is defined by the AppletContext interface. WIDTH and HEIGHT WIDTH and HEIGHT are required attributes that give the size of the applet display area. ALIGN ALIGN is an optional attribute that specifies the alignment of the applet. This attribute is treated the same as the HTML IMG tag with these possible values: LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and ABSBOTTOM. VSPACE and HSPACE These attributes are optional. VSPACE specifies the space, in pixels, above and below the applet. HSPACE specifies the space, in pixels, on each side of the applet. They're treated the same as the IMG tag's VSPACE and HSPACE attributes. PARAM NAME and VALUE The PARAM tag allows you to specify applet-specific arguments in an HTML page. Applets access their attributes with the getParameter() method. HANDLING OLDER BROWSERS Some older web browsers can't execute applets and don't recognize the APPLET tag. Although these browsers are now nearly extinct (having been replaced by Java compatible ones), you may need to deal with them for a while longer. The best way to design your HTML page to deal with such browsers is to include HTML text and markup within your <applet> </applet> tags. If the applet tags are not recognized by your browser, you will see the alternate markup. If Java is available, it will consume the entire markup between the <applet> </applet> tags and disregard the alternate markup. Here's the HTML to start an applet called SampleApplet in Java and to display a message in older browsers: Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 9 <applet code="SampleApplet" width=200 height=40> If you were driving a Java powered Navigator, you'd see "e;A Sample Applet"e; here.<p> </applet> Passing Parameters to Applets As just discussed, the APPLET tag in HTML allows you to pass parameters to your applet. To retrieve a parameter, use the getParameter() method. It returns the value of the specified parameter in the form of a String object. Thus, for numeric and Boolean values, you will need to convert their string representations into their internal formats. Here is an example that demonstrates passing parameters: // Use Parameters import java.awt.*; import java.applet.*; /* <applet code="ParamDemo.class" width=300 height=80> <param name=fontName value=Courier> <param name=fontSize value=14> <param name=leading value=2> <param name=accountEnabled value=true> </applet> */ public class ParamDemo extends Applet { String fontName; int fontSize; float leading; boolean active; public void start() { String param; fontName = getParameter("fontName"); if(fontName == null) fontName = "Not Found"; param = getParameter("fontSize"); try { if(param != null) // if not found fontSize = Integer.parseInt(param); else fontSize = 0; } catch(NumberFormatException e) { fontSize = -1; } param = getParameter("leading"); try { if(param != null) // if not found leading = Float.valueOf(param).floatValue(); else leading = 0; } catch(NumberFormatException e) { leading = -1; Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 10 } param = getParameter("accountEnabled"); if(param != null) active = Boolean.valueOf(param).booleanValue(); } // Display parameters. public void paint(Graphics g) { g.drawString("Font name: " + fontName, 0, 10); g.drawString("Font size: " + fontSize, 0, 26); g.drawString("Leading: " + leading, 0, 42); g.drawString("Account Active: " + active, 0, 58); } } Sample output from this program is shown here: As the program shows, you should test the return values from getParameter(). If a parameter isn't available, getParameter() will return null. Abstract Windowing Toolkit Introduction: The Abstract Windowing Toolkit (AWT) is a library of java packages that forms part of the java API. It includes over 25 packages that define hundreds of classes used for GUI. The AWT classes contained in the java.awt packages. The following diagram shows the component hierarchy: Button - A Button component is a simple pushbutton that displays a string label and responds to mouse presses from the user. Canvas - A Canvas is a blank area suitable for drawing in. You can use a Graphics object to put polygons or images on the Canvas. Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 11 Checkbox - A Checkbox is a small box with two states: either it's checked or unchecked. Clicking the mouse over an enabled Checkbox toggles its state. It can have a string label. CheckboxGroup - You put Checkboxes in a CheckboxGroup in order to make them exhibit "radio button" behavior: when one is checked, the others become unchecked. Only one Checkbox from the group can be checked at any time. Choice - A Choice component allows the user to specify one of a short list of choices, which appear on a little popup menu next to the current choice. Label - A Label component displays a line of text. The text can be aligned to the left, right, or center of the Label. The user isn't allowed to edit the text in a Label. List - A List presents a scrollable list of items, identified by string names. Use this instead of a Choice when multiple selections are meaningful or when there may be too many items to conveniently display on a single popup menu. Scrollbar - Most Scrollbar components are automatically generated when required by List or TextArea components. If you want to create your own scrollbars, you can do so. The orientation is specified by the constants Scrollbar.HORIZONTAL and Scrollbar.VERTICAL. TextField - A TextField component holds a single line of text in a little window. The text is allowed to be longer than the window, in which case only part of it shows. TextArea A TextArea is a pane containing lines of text. Like a TextField, it can be editable or not. Layout Managers When we add a component to an applet or a container, the container uses its layout manager to decide where to put the component. Different LayoutManager classes use different rules to place components. java.awt.LayoutManager is an interface. Classes in the java.awt package implement it: GridLayout, BorderLayout & FlowLayout GridLayout A GridLayout divides an applet into a specified number of rows and columns which form a grid of cells, each equally sized and spaced. As components are added to the layout, they are placed in the cells, starting at the upper left hand corner and moving to the right and down the page. Each component is sized to fit into its cell. //Program to demonstrate GridLayout import java.applet.*; import java.awt.*; /* <applet code ="GridLayoutApplet.class" width=200 height=200> </applet> */ public class GridLayoutApplet extends Applet{ public void init(){ Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 12 setLayout (new GridLayout(3,2)); Button b1 = new Button("A"); Button b2 = new Button("B"); Button b3 = new Button ("C"); Button b4 = new Button("D"); Button b5 = new Button ("E"); Button b6 = new Button("F"); add(b1);add(b2);add(b3); add(b4);add(b5);add(b6); } } BorderLayout A BorderLayout organizes an applet into North, South, East, West and Center sections. North, South, East and West are the rectangular edges of the applet. They're continually resized to fit the sizes of the widgets included in them. Center is whatever's left over in the middle. //Program to demonstrate BorderLayout import java.applet.*; import java.awt.*; /* <applet code="BorderLayoutApplet.class" width=300 height=300> </applet> */ public class BorderLayoutApplet extends Applet{ public void init(){ setLayout (new BorderLayout(5,5)); Button b1 = new Button("North"); Button b2 = new Button ("South"); Button b3 = new Button ("East"); Button b4 = new Button ("West"); Button b5 = new Button ("Center"); add(b1,"North");add(b2,"South"); add(b3,"East");add(b4,"West"); add(b5,"Center"); Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 13 } } FlowLayout A FlowLayout arranges widgets from left to right until there's no more space left. Then it begins a row lower and moves from left to right again. Each component in a FlowLayout gets as much space as it needs and no more. A FlowLayout is useful for laying out buttons but not for much else. This is the default LayoutManager for applets and panels //Program to demonstrate FlowLayout import java.applet.*; import java.awt.*; /* <applet code="FlowLayoutApplet.class" width=300 height=200> </applet> */ public class FlowLayoutApplet extends Applet{ public void init(){ setLayout (new FlowLayout (FlowLayout.LEFT,5,5)); for (int i=0;i<20;i++){ add (new Button ("Button"+i)); } } } Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 14 Buttons and Labels The Button Class A Button is a component that simulates the appearance of a push button on an electronic instrument. With user’s mouse click inside its boundaries, the button changes its appearance to provide feedback for the user. The major resources of the Button class are given in Table 2.9. Table 2.9 Major resources of the Button class. The first, default, constructor will create a Button without a label. The first two methods allow the Button's label to be changed or obtained. The remaining methods are concerned with the Button's listener and the command string sent to it. Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 15 //Program To Demonstrate Button import java.awt.*; import java.applet.Applet; /* <applet code="ButtonApplet.class" width=200 height=200> </applet> */ public class ButtonApplet extends Applet{ public void init(){ Button b1,b2,b3; b1 = new Button("Apple"); b2 = new Button("Banana"); b3 = new Button("Grapes"); add(b1); add(b2);add(b3); } } The Label Class A Label is a string that appears on a GUI. Labels are very frequently used in programs. Often placed before text fields to inform the user about the input that is expected. This is a relatively simple class and provides a convenient point to start the tour. Table 2.1 lists the major methods and other resources of the class. Table 2.1 Major resources of the Label class. Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 16 The data attributes of a Label instance are the text which it will display and the alignment of the text. The possible alignments for the text are enumerated by the three Label class wide constants CENTER, LEFT and RIGHT, with a default of LEFT when it is not explicitly specified otherwise. Follow these steps to use a Label in an Applet: 1. create a Label object 2. invoke the add() method to add the Label object to the Applet //Program To Demonstrate Label import java.awt.*; import java.applet.Applet; /* <applet code="LabelApplet.class" width=200 height=200> </applet> */ public class LabelApplet extends Applet { public void init() { setLayout(new GridLayout(3,1)); setBackground(Color.YELLOW); Label l1 = new Label("This Text is Left Aligned", Label.LEFT); Label l2 = new Label("This Text is Center Aligned", Label.CENTER); Label l3 = new Label("This Text is Right Aligned", Label.RIGHT); add(l1); add(l2); add(l3); } } Checkbox and List Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 17 The Checkbox Class The Checkbox class provides a text label and an associated on/ off state indicator. It is used to implement check buttons and, in conjunction with the CheckboxGroup class, radio buttons. The major resources of this class are presented in Table 2.11. A Checkbox instance has three data attributes, the label which it will display, the CheckboxGroup to which it might belong and the state (on or off) of its indicator. If a Checkbox instance is not a member of a CheckboxGroup it will behave as a check button and its state can be set or unset independently of all other Checkbox buttons. If a Checkbox instance is a member of a CheckboxGroup it will behave as a radio button, where only one member of the group can be checked at any one instant and checking one of the buttons in the group will automatically unset all other buttons. The first two constructors are comparable to the first two constructors of the Label class given above. The third constructor specifies its initial state, the last the initial state and the CheckboxGroup to which it belongs. Table 2.11 Major resources of the Checkbox class. //Program To Demonstrate Checkbox import java.applet.Applet; import java.awt.*; Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 18 public class Check extends Applet{ public void init(){ setLayout(new GridLayout(3,1)); Checkbox c1=new Checkbox("Tamil", true); Checkbox c2=new Checkbox("English", false); Checkbox c3=new Checkbox("Telugu", false); add(c1); add(c2); add(c3); } } /* <applet code="Check.class" width=200 height=200> </applet> */ The CheckboxGroup Class In order to configure Checkbox instances as radio buttons an instance of the CheckboxGroup class has to be created and specified as the group attribute of the set of buttons. The major resources of the CheckboxGroup class are given in Table 2.13. Table 2.13 Major resources of the CheckboxGroup class. The CheckboxGroup class encapsulates the identities of the Checkboxes which comprise its group and maintains knowledge of which one is currently selected. It has a single default constructor and an enquiry and a modifier method for the currently selected component. Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 19 //Program To Demonstrate CheckBoxGroup import java.applet.Applet; import java.awt.*; public class checkbg extends Applet{ public void init(){ setLayout(new GridLayout(3,1)); CheckboxGroup cbg=new CheckboxGroup(); Checkbox c1=new Checkbox("Tamil",cbg,true); Checkbox c2=new Checkbox("English",cbg,false); Checkbox c3=new Checkbox("Telugu",cbg,false); add(c1); add(c2); add(c3); } } /* <applet code="checkbg.class" width=200 height=200> </applet> */ The List Class The List class provides a scrolling, list box which allows the user to select one or a number of options, from a list of choices. The major resources of this class are given in Table 2.15. Table 2.15 Major resources of the List class. An instance of the List class encapsulates a list of Strings, known as items, which represent the choices to be presented to the user. It also knows if it is available for single or multiple selections and the number of items in the list (rows) which are to be visible. Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 20 The third constructor requires the number of rows to be specified and a boolean value to indicate if multiple selections are to be allowed. The two add() methods allow an item to be added to end or at a specific location within list. The two remove() methods allow a single item or a continuous range of items to be deleted and removeAll() clears the list. The getItemCount() method indicates the number of items in the list. The two methods, setMultipleMode() and isMultipleMode(), allow the multiple selection state of the list to be set or queried. The select() and deSelect() methods are supplied to allow items within the list to be selected & the isSelected() boolean method indicates the state of an individual item. The getRows() and getVisibleIndex() methods indicate the number of visible items and the first item which is visible. The makeVisible() method specifies item is visible somewhere within the list's window. The getSelectedIndex() should only be used if the List is in single selection mode and returns the index of the currently selected item or -1 if none are selected. If the list is in multiple selection mode the getSelectedIndexes() method will return an array of the indexes of the currently selected items. The getSelectedItem() and getSelectedItems() methods return a String //Program To Demonstrate List import java.awt.*; import java.applet.Applet; public class MyList extends Applet{ public void init(){ List icecream = new List(6,true); icecream.add("Chocolate"); icecream.add("Vanilla"); icecream.add("Strawberry"); icecream.add("Casata"); icecream.add("Rumraisin"); icecream.add("ButterScotch"); icecream.add("Mintchip"); add(icecream); } } /* <applet code = "MyList.class" width="200" height="200"> </applet> */ Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 21 Table 2.15 Major resources of the List class Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 22 The Menu Class Java provides two types of menu: pull down and popup menu. Pull down menus are accessed via menu bar. It may contain many menus. Menu bars may only appear in a frame Steps for Creating pull down Menus: 1. Create an object for the MenuBar class 2. Attach the MenuBar to the Frame 3. Create Menu class for each Menu you want on the MenuBar The Menu class takes a single argument of the menu class that is caption of the menu. 4. Add Menu to MenuBar 5. Create an Object for MenuItem or CheckboxMenuItem class for each submenu item. 6. Add the MenuItem to Menu class //Program To Demonstrate Menu import java.awt.*; public class MyMenu { public static void main(String args[]) { Frame f=new Frame(“This is test for Menu”); MenuBar main=new MenuBar(); f.setMenuBar(mb); Menu filemenu = new Menu("File"); Menu editmenu = new Menu("edit"); Menu helpmenu = new Menu("Help"); mb.add(filemenu); mb.add(editmenu); mb.add(helpmenu); MenuItem MenuItem MenuItem MenuItem MenuItem new1 = new MenuItem("New"); open = new MenuItem("open"); save = new MenuItem("save"); close = new MenuItem("close"); line = new MenuItem("-"); CheckboxMenuItem print = new CheckboxMenuItem("print"); MenuItem exit = new MenuItem("exit"); filemenu.add(new1); filemenu.add(open); filemenu.add(save); filemenu.add(line); filemenu.add(print); filemenu.add(exit); MenuItem cut = new MenuItem("cut"); Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 23 MenuItem copy = new MenuItem("copy"); MenuItem paste = new MenuItem("paste"); MenuItem undo= new MenuItem("undo"); editmenu.add(cut); editmenu.add(copy); editmenu.add(paste); editmenu.add(undo); undo.setEnabled(false); Menu more= new Menu("More"); helpmenu.add(more); more.add("commands"); more.add("about"); f.setSize(200,200); f.setVisible(true); } } OUTPUT: Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 24 The TextComponent, TextArea and TextField Classes These three classes supply facilitates for the input, and output, of text information. The TextComponent class is not intended to be instantiated, although it is not declared abstract, and provides common behavior for the single line TextField & multiline TextArea classes. The major resources of the TextComponent class are presented in Table 2.19. Table 2.19 Major resources of the TextComponent class. There is no constructor for this class as it is only intended that instances of the TextField or TextArea classes will be created. TextArea TextArea class handles the multilines of text. This is also derived from TextComponent. Textarea components are useful for getting a large amount of data from a user, or for displaying a large amount of data that is free to be modified. They take up more screen real estate than textfields, but can conserve quite a lot of room because they have support for scrollbars. The major resources added by the TextArea class are presented in Table 2.20. //Program To Demonstrate TextArea import java.applet.*; import java.awt.*; public class TextArea1 extends Applet{ Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 25 public void init(){ TextArea ta = new TextArea(5,8); Label l1 = new Label(“Text Area”, Label.CENTER); ta.setText(“This \n is the\n Test\n for Text Area \n with \n non editable \n mode"); add(l1); add(ta); ta.setEditable(false);//cannot edit } } /* <applet code=”TextArea1.class” height=200 width=200> </applet> */ TextField TextField components are useful for obtaining short pieces of information from users. They are limited to single line input (for multiple lines, use a TextArea instead). Whenever a user types data into a text field, and hits enter or changes focus, the textfield will generate an event. //Program To Demonstrate TextField import java.applet.*; import java.awt.*; public class Text extends Applet{ public void init(){ Label l1 = new Label("Enter the Username", Label.CENTER); TextField t1 = new TextField(10); Label l2 = new Label("Enter Password", Label.CENTER); TextField t2 = new TextField(10); t2.setEchoChar('*'); add(l1); add(t1); add(l2);add(t2); } } /* <applet code="Text.class" height=200 width=200> </applet> */ Nizam College B.Com(E-Com) 3rd yr 5/4/2017 G Devender 26 Table 2.20 Major resources of the TextField class. The constructors allow various combinations of the String to be initially displayed and the number of columns to be specified. The number of columns defaults to the number of characters in the String for the second constructor and zero for the default constructor. The String contained within the TextComponet can be longer than the number of columns in which case it can be scrolled to the left and right by the user's actions. If the echoChar attribute is set then the specified character will be used to give the user feedback as they type in the field, as will be demonstrated below. Nizam College B.Com(E-Com) 3rd yr 5/4/2017