Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
21 views
GUI With AWT
Uploaded by
3083surajthapa
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save 3. GUI with AWT For Later
Download
Save
Save 3. GUI with AWT For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
21 views
GUI With AWT
Uploaded by
3083surajthapa
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save 3. GUI with AWT For Later
Carousel Previous
Carousel Next
Save
Save 3. GUI with AWT For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 26
Search
Fullscreen
GUI with AWT After comprehensive study of this chapter, you will be able to: Todescribe AWT and its features Todiscuss AWT class hierarchy with containers and components ‘To demonstrate development of GUI application using Frame ‘Touse AWT containers and components in developing GUL Tediscuss Menubars and Menus and program it Todemonstrate dialog boxes in AWTae s GUI or window, Java AWT (Abstract Windowing Toolkit) isan a. as —— . application in java, Java’ AWT components eS siwr is heavyweight ie. its compen, resources a. an calls native platform (Operating sys... uses the res of system. Actually, a checkbox, button etc. For example if w. , atin for creating components such as textbox, actually asking OS to cieate a text box fy instantiating a text box in AWT that means . ES ee reins syste, ae a oli ei ice like a windows application when it runs , = cs look like a Mac application when runs on Mac Os, Windows, but the same ap) TextField, Label, TextAr, i for AWT API such as «2 ‘The javaawt package provides eee WT is rarely used now days because of its platfom, Oe ae satiieative java.awt package contains the core AWT 8taphig lasses: * GUI Container c! (such as Frame, Pan. Dialog and ScrollPane) ‘Layout managers (such as FlowLayout, BorderLayout and GridLayout) Event Handling Classes (such as AWTEvent, AWTEventMultiCaster) Custom graphics classes (such as Graphics, Color and Font). The ultimate super class of all the GUI components both in AWT as the java.awt.Component. The hierarchy of wi, well as Swing idely used Java AWT classes is given below: Figure 3.1: AWT Hierarchy eR oases ws weet sk Se SB a . ‘ 1 ‘ « i aaas Swing j low: GuIwith AWT QO Chapter 3 a 3.5 WINDOW FUNDAMENTALS class hierarchy that adds functionality and lies below in AWT class hierarchy is window that lies above in the class ed from Panel and AWT defines windows according to. a with each level. This means windows that ore functionality and is special case of the ‘The two most commonly used windows are those deriv specificity provides ™ hierarchy: those deriv 3.3.1 Components hierarchy is the Component class. Component is an abstract class that onent. All user interface elements that are displayed on the screen and that interact with the user are subclasses of Component. It defines hundred public methods that are responsible for managing managing events. is responsible for remembering the current current foreground and currently selected text font, and current text alignment. ed from Frame. Lets discuss each of the class in the AWT window hierarchy. ‘At the top of the AWT encapsulates allof the attributes of a comp over a Component object background colors, 3,3.2 Containers a subclass of Component. It has additional features that alloy placed within it. Other Container objects can also be stored inside of a themselves instances of Component. Thus, allowing multileveled tioning any component placed on it. It Default layout is present in each ‘The Container class it w other Component objects to be Container since they are containment system. A container is responsible for posit does this through the use of various layout managers. which can be overridden using setLayout method. container 3.3.3 Panel ‘The class Panel is the simplest container class. It provides space in which an application can It uses FlowLayout as default layout attach any other component, including other panels. hat doesn't contain any title bar or menubar. It is usually manager. It is a border less window th added to another container like the Frame. The main purpose of a panel is to group components. Commonly used Constructors - Panel():- Creates a new panel using the default layout manager ~ Panel(LayoutManager layout):- Creates a new panel with the specified layout manager Other components can be added to a Panel object by its add() method (inherited from Container). Once these components have been added, you can position and resize them manually using the setLocation(_), setSize( ), setPreferredSize( ), or setBounds() methods defined by Component.yp BZ Advanced Java Programming, tained with The Window class creates a top-level window. A top-level window is not con May akc Generally, we won't create objects ee cy ame hee Le a Soke ‘of Window called Frame or Dialog. yy "5 directly. Instead, we ibclass ad fil ih BorderLayout as default layout manager. ee Commonly used Constructors a new, initially invisible window wit, é . Window (Brame owner):-Constructs ‘specified Frame as its owner Fe paren ital’ invisible window with», . Window (Window owner): ‘specified Window as its owner. Window(Window owner, GraphicsConfiguration go):- Constructs a new, initia) ‘ i i d a GraphicsConfigurat, i i ywner Window an c invisible window with the specified 0 ‘ofa screen device < = x lass of Window class which has a title bar, menu bar, borders and is re-sizable wi, 3 Se Sos detault This is what we use in our programs to create windows. - Frame():Constructs a new instance of Frame that is initially invisible = Frame(String title): Constructs a new, initially invisible Frame object with the ‘specified title | 3.3.6 Dialog Boxes Dialog box is 2 window with a title bar but with no minimize or maximize options. It is a direc sub-class of Window and comes with default BorderLayout. An instance of the Dialog class cannot exist without an associated instance of the Frame class. It can be constructed with parent, typically a Frame or another dialog. Dialogs are divided into types, Modal and Modeles: (default). A modal dialog blocks user input of top-level windows of the dialog (i.e. its paren's but not its children) while a modeless dialog doesn't. We will discuss about it in detail later. WSimny 3.3.7 Canvas ¥ Although it is not part of the hierarchy for applet or frame class windows, canvas is one other typ? q of window that we will find valuable, Canvas encapsulates a blank window upon which we ca" Fi draw. S ; ie Commonly used Constructors a ‘Canvas():- Constructs a new Canvas. * Canvas(GraphicsConfiguration config):- Constructs a new Canvas given * GraphicsConfiguration object.ut with Wr O - Chapter 3) 8% "ine 8 of wl weer 5 ty WITH FRAME WINDOWS Diag. 1 frame is widely used window used to create child windows within applets, and top-level or child window for stand-alone applications. There are several key methods that we can 2B tase when working with Frame windows, They are examined here. u ., . dow x + Setting the Window's Dimensions: The setSize( ) method is used to set the 4 dimensions of the window. Its signature is shown here: Winds void setSize(int newWidth, int newHeight) Wg void setSize(Dimension newSize) ts The new size of the window is specified by newWidth and newHeight, or by the : width and height fields of the Dimension object passed in newSize. The dimensions are specified in terms of pixels. ‘ The getSize( ) method is used to obtain the current size of a window. signature is shown here: Dimension getSize( ) ies ‘This method returns the current size of the window contained within the width 2s be and height fields of a Dimension object. ; + Hiding and Showing a Window: Aftera frame window has been created, it will not be visible until we call setVisible( ) method. Its signature is shown a below: oid setVisible(boolean visibleFlag) object wit The component is visible if the argument to this method is hidden. Setting a Window's Title: We can change the title in a frame window using setTitle() method, which has this general form: void setTitle(String newTitle) panels 164 Here, newTitleis the new title for the window. the Dials. CJoging a Frame Window: Whenusing a frame window, our program must screen when it is closed, by calling setVisible() Its true. Otherwise, it is structed ¥ remove that window from the dal and Nee method. For this we need to handle events generated by frame window which will (ie. its be discussed in later chapters. detail" simple example of AWT Frame by inheritance import java.awt.*; class FirstFrame extends Frame one ot" { 1 which FirstFrame() £ Button b=new Button("click me"); b.setBounds(3@, 100,80, 30);// setting button position setTitle("Frame by Inheritance") ;//setting frame title yas ge add(b);//adding button into framea GA“ Aavaited jave Programming setSize(300,300);//frame size 300 width and 300 height Pe = ~~ SetLayout(null);//no- aa, py default not visit), setVisible(true);//now frame will be visible, public static void main(String args[]) t FirstFrame f=new FirstFrame(); } } Qutput Note: 30, bet an events Frame Creati 2 of the object D we ne //Simple example of AWT by association = import java.awt."5 7 class SecondFrame we Examp alin, Here Frame f=new Frame(); //creating frane impor Button b=new Button(“click me"); impor b. setBounds (38, 160, 80,38);// setting button position ‘impor f.setTitle("Frame by Association"); //setting frame title i* .add(b);//adding button into frame £,setSize(300, 300) ;//frame size 300 width and 300 height ‘appl #.setLayout(null);//no layout manager WU Public class AppletFrame extends Applet { Frame £; Public void init()ra BB Advanced Java Programming x ga Adding and Removin € = new Frame("A Frame Window") 5 3 eacontrolin a window, .setsize(1se, 150); roineude instance of the desir #.setvisible(true); eee hich is defined by Con : petnoe gne one that is used widely Ae public void start() sor component_add(Compon t : cee bjs an instance of the cr ' F.setvisible(true); Her ophas been added w splayed: voi isp! wally 4 stop() cometimes youwill want ©. Te fed, To dothis, we need . £.setvisible(false); me defined by Container. Ihe d remove (Compon public void paint(Graphics 8) ae et i | Here obj is @ reference to t g-drawstring("This is in applet window", 15, 38) | calling removeAll() method. were 3.6.2 Responding to C ‘Output | beet for Labels, which are | | ser, For example, when the push button. In general, ou register an event listener | handling chapter, once a list This section will explain th 3.7.1 Label Class label is a passive control = control is an object ¢ TZ, can be changed by th Controls are components that allow a user to interact with your application in various wit] “*Y For example, a commonly used control is the push button, AWT provides many 3) Commont; Const and reusable GUI components, The frequently-used are: Button, TextField, T ree eee Checkbox, CheckboxGroup (radio buttons), List, Choice, ScrollBarr etc. All ‘extArea, 2 Public Label String subclasses of Component. A Component is an abstract super class for GUI a Public Label(Striny represents an object with graphical representation. opuey. ~ public Label);cut with AWT QO Chapter 3) 87 3.6.1 Adding and Removing Controls To include a control in a window, we must add it to the window. To do this, we must first create an instance of the desired control and then add it to a window by calling add) method, which is defined by Container. The add() method has several forms. The following form is the one that is used widely: Component add(Component obj) Here, obj is an instance of the control that you want to add. A reference to obj is returned. Once control has been added, it will automatically be visible whenever its parent window is displayed. Sometimes you will want to remove a control from a window when the control is _no longer needed. To do this, we need to call remove( ) method of container class. This method is also defined by Container. It has this general form: void remove(Component obj) Here, obj is a reference to thecontrol we wantto remove. We can remove all controls by calling removeAll) method. _ 3.6.2 Responding to Controls Except for Labels, which are passive, all controls generate events when they are accessed by the user. For example, when the user clicks on a push button, an event is sent that identifies the _ push button. In general, our program needs to implement the appropriate interface and then register an event listener for each control that we need to monitor. As explained in event handling chapter, once a listener has been installed, events are automatically sent to it. aire are __ This section will explain the list of commonly used controls in designing GUI using AWT. 3.7.1 Label Class Label is a passive control because it does not create any event when accessed by the user. The label control is an object of Label. A label displays a single line of read-only text. However the can be changed by the application programmer but cannot be changed by the end user in any way, nin vatit® Commonly used Constructors > public Label(String strLabel, int alignment); ~ public Label(String strLabel); ~ public Label();©8 Advanced Java Programming ‘The first constructor constructs a Label object with the given text oem the Bing alignment. Note that _ three static constants Label. LEFT. LabelRIGHT, NF Label. CENTER are defined in the class for us to specify the alignment (rather 4, asking you to memorize arbitrary integer values) The second constructor constructs @ Label object with the given text string default of left-aligned. ' The third constructor constructs a Label object with an initially empty string. ‘could set the label text via the setText() method later Commonly used Public Methods = public String getText(); //returns text of label control - public void setText(String strLabel); //sets label text > public int getAlignment();/ /returns alignment of Jabel text ~ public void setAlignment(int alignment); //sets alignment of label text 3.7.2 Button Class Button is 2 control component that has a label and generates an event when pressed. When, bumon is pressed and released, AWT sends an instance of ActionEvent to the button, by calli processEvent on the button. If an application wants to perform some action based on a Sy ‘being pressed and released, it should implement ActionListener and sede He TeWwi : receive events from this button, by calling the button's mie iaceaot a listener Commonly used Constructors lic Button(String buttonLabel); _// Construct a Button with the given label ay public Button); // Construct a Button with empty label Button class has two 2 5 i = fiver el a ae Brees Batbt jae Sn & label Painted over the button. The second constructor create otal ig tes a Button object with x Commonly used Public Methods Public String getLabel(); // Get the label of this ; 226! public void setLabel(String bi Button instance uttonLabel); / / Set the label of thi Public void setEnable(boo of this Button instance lean enable); // Enable or 3.7.3 TextField Cl; oei Ry GUIwith wT QO Ghapter3) 89 Mey ly used Constru tw Commonly nstructors Bive, + public TextField(String strInitialText , int columns); // Construct a TextField ; instance with the giv en initial text string with the number of columns. ly \ * public TextField(String strinitialText); // Construct a TextField instance with “py, the given initial text string. a * public TextField(int columns); _// Construct a TextField instance with the number of columns, Commonly used Public Methods . public String getText(); // Get the current text on this TextField instance . public void setText(String strText); // Set the display text on this TextField instance tt * public void setEditable(boolean editable); // Set this TextField to. editable (read/write) or non-editable (read-only) 3.7.4 TextArea Class aN Presseg ; 5 s button, 3, Ik The TextArea control in AWT provides us multiline editor area. The user can type here as much eg Beast as he wants. When the text in the text area become larger than'the viewable area the scroll bar is Rabe automatically appears which help us to scroll the text up & down and right é& left. >thod. Commonly used Constructors TextArea(); / / Constructs a new text area with the empty string as text. * _ TextArea(int rows, int columns); //Constructs a new text area with the specified fen label number of rows and columns and the empty string as text. TextArea(String text); //Constructs a new text area with the specified text. TextArea(String text, int rows, int columns); //Constructs a new text area with the specified text, and with the specified number of rows and columns. TextArea(String text, int rows, int columns, int scrollbars); //Constructs a new ees text area with the specified text, and with the tows, columns, and scroll bar fade visibility as specified. Commonly used Public Methods * void append String stx)//Appends the given text to the text area's current text. - int getColumns(); //Returns the number of columns in this text area. | * int getRows(); //Returns the number of rows in the text area. void setColumns(int columns); //Sets the number of columns for this text area 1 eo gay * void setRows(int rows); /Sets the number of rows for this text area ssed, an ‘a * void insert(String str, int pos); /nserts the specified text at the specified position possible in this text area. ene ae» 88 Advanced Java Programming 3.7.5 CheckBox Class ‘Checkbox control is used to turn an option on(true) checkbox representing what the checkbox does.The sta clicking on it. an a box with an empty string for its label. ‘box(); //Creates a check box wit y : “3 ; cee label); //Creates a check box with the specified . Checkborsting label, boolean state); Creates a check box with the specified lap, . Bais: fee wa, boolean state, CheckboxGroup group); //Constructs , : ae inet label, set to the specified state, and in the specifi, wit | check box group. or offffalse). There is label for te of a checkbox can be changeg * String getLabel(); /Gets the label of this check box. . Pinsinge the ac whether this check box is in the on or off state * void setState(boolean state); /Sets the state of this check box to the specified state = void setCheckboxGroup(CheckboxGroup g); //Sets this check box's group to the specified check box group. + Object{] getSelectedObjects(); //Returns an array (length 1) containing th, checkbox label or null if the checkbox is not selected. 3 * void setLabel(String label); Sets this check box's label to be the string argument, |" is possible to create a set of mutually exclusive check boxes in which one and only one check box in the group can be checked at any onetime, These check boxes are often called radio buttons. To create a set of mutually exclusive check boxes, you must first define the group to which they will belong and then specify that group when we construct checkboxes, Commonly used Constructors CheckboxGroup(); //Creates a new instance of CheckboxGroup. Commonly used Public Methods Checkbox getSelectedCheckbox(); /Gets the current choice ~ void setSelectedCheckbox(Checkbox box); group to be the specified check box. 3.7.7 Choice Class from this check box group ‘ets the currently selected check box in th Choice control is used to show popup menu of choices, Selected choice is shown on the top of the menu, Thus, a Choice control is a form of menu, When inactive, a Choice component takes up only enough space to show the currently selected item. When the user clicks on it, the whole list of choices pops up, and a new selection can be made.Only one de ten called ni e the grow: < box group eck box in onthe nit thew GUI with AWT OQ Chapter 3) a Commonly used Constructors Choice(); //Creates a new choice menu, Commonly used Public Methods void add (String item); //Adds an item to this Choice menu. String getltem{int index),/Gets the string at the specified index in this Choice menu, int getItemCount()/Returns the number of items in this Choice menu. int getSelectedIndex(); //Returns the index of the currently selected item. String getSelectedItem(); //Gets a representation of the current choice as a string. void remove(int position)//Removes an item from the choice menu at the specified position. void removeAll()//Removes all items from the choice menu. void select(int pos),//Sets the selected item in this Choice menu to be the item at the specified position. void select(String stz); //Sets the selected item in this Choice menu to be the item whose name is equal to the specified string. 3.7.8 List Class The List represents a list of text items. The list can be configured to that user can choose either one item or multiple items. Unlike the Choice object, which shows only the single selected item in the menu, a List object can be constructed to show any number of choices in the visible window. Commonly used Constructors 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. Commonly used Public Methods void add(String item); //Adds the specified item to the end of scrolling list. void add(String item, int index); //Adds the specified item to the the scrolling list at the position indicated by the index. void deselect(int index); //Deselects the item at the specified index. String getltem/(int index); //Gets the item associated with the specified index. int getltemCount(); //Gets the number of items in the list. Stringf] getItems(); /Gets the items in the list.82 Advanced Java Programming, * int getSelectedindex); //Gets the index ofthe selected item on the list + int{] getSelectedindexes(); /AGets the selected indexes on the list * String getSelecteditem); (Gets the selected item on this scrolling list. + Stringf] getSelectedtems(); /Gets the selected items on this scrolling list * boolean isindexSelected(int index); //Determines if the specified item in thj ‘scrolling list is selected. F * void remove(int position); //Removes the item at the specified position from this scrolling list. = void remove(String item); //Removes the first occurrence of an item from the list eS ‘void removeAllQ;//Removes all items from this list. ; : Pcie ing newValue, int index); Replaces the item at the specified index in the scrolling list with the new string. 3.7.9 ScroliBar Class i lect from ran; Sgcrollbar control represents a scroll bar component in order to enable user 19 ge of. several individual parts. Each end has of values. Ascroll bar is actuallya composite 1 n tom the current value of the scroll bar one unit in the direction ate Ne arrow that a = of thearrow. = Commonly used Constructors ‘ — q Scrollbar(}; [Constructs a new vertical scrol , Scrollbar{int orientation); //Constructs a new scro! a Scrollbarfint orientation, int value, int visible, int minimum, int maximum); //Constracts a new scroll bar with the specified orientation, initial value, visible amount. and minimum and maximum values. Static Constants HORIZONTAL ~A constant that indicates a horizontal scroll bar. VERTICAL --A constant that indicates a vertical scroll bar. Commonly used Public Methods int getMaximum();//Gets the maximum value of this scroll bar. . int getMinimum(); //Gets the minimum value of this seroll bar. - int getOrientation(); //Returns the orientation of this scroll bar, - iim getValue(; /Gets the current value of this scroll bar. - void setMaximum(); //Sets the maximum value of this scroll bar. - void setMinimum(); //Sets the minimum value of this scroll bar. void setOrientation(); //Sets the orientation of this scroll bar. void setValue(); //Sets the current value of this scroll bar. void setValues(int value, int visible, int minimum, int maximum); //Sets the values of four properties for this scroll bar: value, visibleAmount, minimum, and maximum.in thy, ing ifieg 45 of Pa Exat Ws cuwin wt O Ghapees) © mple tudent Registration form created by using AWT Contris import java-awt.*; cla { gs Student extends Frame Iblhd-new Label("Student details", Label CENTER); //neading Label Iblname=new Label(“Name",Label.LEFT); //Name Label Iblage=new Label( “Age” ,Label.LEFT); //Age Label Iblsex-new Label("Sex(M/F)",Label.LEFT); //Sex Label Ibladdress=new Label("Address”, Label. LEFT) ;//Address Label Label Label Label Label Label Label Label 1lblsem=new Label( "Semester", Label 17=new Label("",Label.RIGHT) 5 Label lblhobbies=new Label("Hobbies" , TextField txtname=new TextField(); //Name Textfield e=new Choice(); //choice list for age lblcourse=new Label("Course" ,Label.LEFT);//Course Label Label.LEFT);//Semester Label Label.LEFT) ; //Hobbies Label Choice chagt CheckboxGroup cbg=new CheckboxGroup() ; Checkbox chkmale=new Checkbox("Male”,true,cbg); //male checkbox Checkbox chkfemale=new Checkbox("Female" false, cbg) ; //female checkbox List hb=new List(3,true); //Hobbies list box with multiple selection enabled Textarea txtaddress=new Textarea("", 180,98, Textarea. SCROLLBARS_VERTICAL_ONLY); Choice course=new Choice(); Choice sem=new Choice(); Choice age=new Choice(); Button b1=new Button("save"); Student() { setBackground(Color.cyan);//sets background color of frame setForeground(Color. black); setLayout (null); Lblhd. setBounds (10,48, 280, 28) 5 add(1b1hd) ;} 84 Advanced Java Programming | Ublname. setBounds(25, 65,90, 20) ; add(1biname) ; txtname. setBounds (120,65, 170, 20); add(txtname) ; Iblage. setBounds (25,90, 90,20) ; add(1blage) ; chage, setBounds (120, 98, 50, 20) add(chage); chage.add("17"); chage.add("18"); chage.add("19"); chage.add("2@"); chage.add("21") 5 Iblsex.setBounds (25,120, 9, 28) ; add(1blsex); chkmale. setBounds(120,120, 52, 20) ; chkfenale. setBounds (172,128, 60,22); add(chkmale) ; add(chkfemale) ; Lb1hobbies. setBounds (25,158, 98,20); add(1blhobbies) ; hb. setBounds (120, 15@,90,5@) ; add(hb); hb. add("Playing"); hb. add("Visiting"); hb. add("Reading"); hb. add("Swiming"); Ibladdress .setBounds (25,230, 90,20); add(1bladdress); | txtaddress.setBounds (120, 230, 178,68); add(txtaddress) ;Iblcourse. setBounds(25, 305, 90,28); add(1blcourse) ; course. setBounds(120, 305,100, 28); course.add("BSc CSIT"); course. add("BIM") ; course.add("BIT"); course. add("BCA") ; course.add("B.E. Computer"); add(course) ; Iblsem.setBounds(25, 335,98, 26); add(1blsem) ; sem.add("1") ; sem.add("2"); sem.add(“3"); sem.add("4") ; sem.add("5"); sem.add("6"); sem.add("7"); sem.add("8"); sem. setBounds(120, 335,5@,2@); add(sem) ; 17. setBounds(25,225, 98,20); add(17); b1. setBounds (120, 400,50, 30); add(b1); } Public static void main(String g[]) { Student stu=new Student(); stu.setSize(new Dimension(5@@,5@0)); stu.setTitle("Student Registration"); stu. setVisible(true) ; GUI with WT O- Ghapter3) 95A top-level window can have a menu bar associated with it. A menu bar displays a list of top level menu choices. Each choice is associated with a drop-down menu. Commonly used Constructors of MenuBar Class - MenuBar(); //Creates a new menu bar. Commonly used Public Methods of MenuBar Class Menu add(Menu m); //Adds the specified menu to the menu bar. - Menu getMenu(int i); //Gets the specified menu. : - int getMenuCount(); /Gets the number of menus on the menu bar. - void remove(int index); //Removes the menu located at the specified index from th menu bar. ~ void remove(MenuComponent m); //Removes the specified menu component from ti | menu bar.GUI with AWT QO Chapter 3) ©. 3.8.1 Menu Class The Menu class represents pull-down menu component which is deployed from a menu bar. ‘We can create a hierarchy of submenus within a menu. Commonly used Constructors of Menu Class Menu(; //Constructs a new menu with an empty label Menu(String label); //Constructs a new menu with the specified label. Menu(String label, boolean tearof); /Constructs a new menu with the specified label, indicating whether the menu can be torn off. Commonly used Public Methods of Menu Class Menultem add(Menultem mi); //Adds the specified menu item to this menu. void addSeparator(); //Adds a separator line, or a hypen, to the menu at the current Menultem getltem(int index); //Gets the item located at the specified index of this menu. int getItemCount(); //Get the number of items in this menu. void insert(Menultem menuitem, int index); //Inserts a menu item into this mena at the specified position. void insertSeparator(int index); //Inserts a separator at the specified position. void remove(int index); //Removes the menu item at the specified index from this menu. void remove(MenuComponent item); //Removes the specified menu item from this menu. void removeAll(); //Removes all items from this menu. 3.8.2 Menultem Class ‘All items in a menu should derive from class Menultem, or one of its subclasses. By default, it embodies a simple labeled menu item. Commonly used Constructors of Menultem Class Menultem(); //Constructs a new Menultem with an empty label and no keyboard shortcut. Menultem(String label); //Constructs a new Menultem with the specified label and no keyboard shortcut. - Menultem(String label, MenuShortcut s); //Create a menu item with an associated keyboard shortcut. y Commonly used Public Methods of Menultem Class wa index . void deleteShoricut();/Delete any MenuShortcut object associated with this menu item. 3 String getActionCommand() //Gets the command name of the action event that is fired by this menu item. displays a listo ea i a a oeyp / 98 Advanced Java Programming i * String getLabel(); Gets the label for this menu item. et bled. Pr i this menu item is enal ; wars ka ieie a, pets the command name oy | 4 - f Cre | i action event thats fired by this menu item. ‘ wa his menu item can be cho, { setEnabled(boolean b); //Sets whether or not # : ¢ void a sy the label for this menu item to the spo. (String label); //Sets ae 8); /Set the MenuShortcut object associateg " . ) this menu item. 3.8.3 CheckBoxMenultem Class CheckboxMeni hich can be included in a my, Jass represents a check box wi “ anaes Bek te a) changes control's state from on tooff or from off to on, ‘Commonly used Constructors — CheckboxMenultem();//Create a check box menu item with an empty label. ; — CheckboxMenultem(label); /Create a check box menu item with the specified label - CheckboxMenultem(label, boolean state); //Create a check box menu item with y, specified label and state. Commonly used Public Methods boolean getState(); //Determines whether the state of this check box menu item is "on' “off void setState boolean b); /Sets this check box menu item to the specifed state. 3.8.4 PopupMenu Class Po Pup menu represents a menu which can be dynamically popped up at a specified poste ‘within a component. Hierarchy of classes used in Menus and ManuBars is given below: Fig 3.2: AWT Menu Hierarchyified post relow: oT aut with wt prample * ynport Java,ant.* fc class MenuDemo extends Frame publ Textarea taj public Menudemo( ) { MenuBar mBar = new MenuBar(); // create menu bar setMenuBar(mBar); —// add menu bar to frame // create menus Menu files = new Menu("Files"); Menu date = new Menu("Date"); Menu exit = new Menu("Exit"); ta = new TextArea(10, 40); ta. setBackground(Color.cyan) ; add(ta)} // add menus to menu bar mBar.add( files); mBar, add(date) ; mBar .add(exit); // create menu items to menus Menu mnew = new Menu("New"); files.add(mnew) ; Menultem save = new MenuItem("Save"); files.add(save); MenuItem open = new MenuItem("Open"); files.add(open); files.addSeparator(); MenuItem print= new MenuItem("Print"); files.add(print); CheckboxMenuItem tb= new CheckboxMenuItem("Toolbar") ; files.add(tb); date. add(new Menultem("Today")); exit.add(new MenuItem("Close"))5 setSize(500, 300) ; setVisible(true) ; Chapter 4WO Advanced Java Programming } , public static void main(String args[]) { . new MenuDemo() ; } - } Output Dialog control represents a top-level window with a title and a 1 of input from the user or to provide some information to users. windows of a top-level window. Dialog boxes don't have menu bars, but in other 5, they function like frame windows. We can add controls to them, for example, in the same Way tha you add controls to a frame window. Dialog boxes may be modal or modeless. When a mod dialog box is active, all input is directed to it until itis closed. This méans that we cannot acces other parts of our program until we have closed the dialog box. When a modeless dialog box is active, input focus can be directed to another window in your program. Thus, other parts o our program remain active and accessible, e Commonly used Constructors ~ _ Dialog(Dialog owner); //Constructs an initially invisible, modeless Dialog with te specified owner Dialog and an empty title. = Dialog(Dialog owner, String title); //Constructs an initially invisible, modeless Dialos with the specified owner Dialog and title. ; Dialog(Dialog owner, String title, boolean modal); //Constructs an initially invisible Dialog with the specified owner Dialog, title, and modality, Dialog(Frame owner); //Constructs an initially invisible, modeless Dialog’ with th specified owner Frame and an empty title.GUI with AWT QO Chapter 3) m1 Dialog(Frame owner, boolean modal); //Constructs an initially invisible Dialog with the specified owner Frame and modality and an empty title. Dialog(Frame owner, String title); //Constructs an initially invisible, modeless Dialog with the specified owner Frame and title Dialog(Frame owner, String title, boolean modal); //Constructs an initially invisible Dialog with the specified owner Frame, title and modality. commonly Used Public Methods String getTitle(); //Gets the title of the dialog, poolean isModal(); //Indicates whether the dialog is modal. poolean isResizable(); //Indicates whether this dialog is resizable by the user void setModal(boolean modal); /Specifies whether this dialog should be modal. void setResizable(boolean resizable); //Sets whether this dialog is resizable by the user. void setTitle(String title); //Sets the title of the Dialog. void setVisible(boolean b); /Shows or hides this Dialog depending on the value of parameter b. Example import java.awt.*; public class DialogDemo extends Frame Some { Often ¢ public DialogDemo() Spects, { ne Way § setSize(500, 302); REN a mi setVisible(true); Mnnot ace setTitle("Dialog Box Example"); | dialog setLocation(300,30@) ; her pat Dialog d=new Dialog(this, “This is Dialog Box", true); Label l=new Label("Modal Dialog", Label.CENTER); d.add(1); 2 , wih? d, setSize(300, 200) ; d, setVisible(true) ; } Jess DA public static void main(String a[]) { y inv new Dialogbemo(); ‘ ’WZ Advanced Java Programming i i ich the user can select a file, To crea FileDialog control represents a dialog window from which : file. 7 " a file dialog box, instantiate an object of type FileDialog. This causes a file dialog, ‘be displayed. Usually, this is the standard file dialog box provided by the operating system . ‘Commonly Used Constructors Commonly Used Public Methods 2 “String getDirectory();//Gets the directory of this file dialog, FileDialog(Frame parent); //Creates a file dialog for loading a file. FileDialog(Frame parent, String title); //Creates a file dialog window with th: specified title for loading a file. FileDialog(Frame parent, String title, int mode); //Creates a file dialog window with the specified title for loading or saving a file, Mode is either FileDilog.LOAD or FileDialog.SAVE. String getFile(; /Gets the selected file of this fle dialog. int getMode(); /ndicates whether this file dialog box is for loading from a fie for saving toa file. void setDirectory(String dir); /Sets the directory of this file dialog window tot the specified directory void setFile(String file); /Sets the selected file for this file dialog window to be the specified file. void setMode(int mode); /Sets the mode of the file dialog.cutwith awt O Ghapter 3) 3 Example japort java.awt.*5 public class FileDialogdemo extends Frame public FileDialogdemo() { setSize(800, 500) ; setVisible(true) ; | setTitle("Dialog Box Example"); setLocation (30, 300) ; FileDialog d=new FileDialog(this, “Open Dialog Box", FileDialog.LOAD); : 3 d.setSize(20@, 100) ; ect a file, 7, d.setLocation(100,100) ; . file dy, d.setVisible(true) ; ating s, , } public static void main(String a[]) e. { : E indow yi, new FileDialogdeno() ; file dialog ving FileDilog ding from a fit ialog window 3 window to184 Advanced Java Programming, - Write a program to create a form to enter employee What is abstract window toolkit (AWT)? Present 'AWT class hierarchy showing all ma components and containers. Differentiate between components and containers. Explain different AWT contajp, ‘How can we create GUI by using AWT frames? Explain the techniques with suitay . Differentiate between frames and panels. Explain different SWT components briefly. data like employee id, name, Do; Salary, Gender, Country, Remarks and two buttons add and cancel by using fram, panels and appropriate components. How modal dialog boxes are different from modeless dialog boxes? Explain creation ; dialog boxes by using example. How can we create open and save file dialog boxes? Explain with suitable example. Discuss AWT components TextField, TextArea, Label, CheckBoxe, and CheckBoxGrou; briefly. Differentiate between Choice class and List class in AWT with suitable description an‘ example. Explain creation of menu bar, menu, and menu items with suitable java code segment. go0
You might also like
Java Content2
PDF
No ratings yet
Java Content2
76 pages
Java Swing and Awt
PDF
No ratings yet
Java Swing and Awt
99 pages
Introducing AWT
PDF
No ratings yet
Introducing AWT
23 pages
unit3_Introduction_toAWT
PDF
No ratings yet
unit3_Introduction_toAWT
18 pages
Chapter 1 Graphical User Interface (GUI)
PDF
No ratings yet
Chapter 1 Graphical User Interface (GUI)
53 pages
1 1awt
PDF
No ratings yet
1 1awt
86 pages
CH 2-Abstract Window Toolkit
PDF
No ratings yet
CH 2-Abstract Window Toolkit
85 pages
UNIT-5 OOP Lecture Notes
PDF
No ratings yet
UNIT-5 OOP Lecture Notes
99 pages
Java AWT unit5
PDF
No ratings yet
Java AWT unit5
108 pages
Chapter - 1: An Overview of The AWT
PDF
No ratings yet
Chapter - 1: An Overview of The AWT
72 pages
Basic Terminologies: Java AWT (Abstract Windowing Toolkit) Is An API To Develop GUI or Window
PDF
No ratings yet
Basic Terminologies: Java AWT (Abstract Windowing Toolkit) Is An API To Develop GUI or Window
23 pages
1 AWT Notes
PDF
No ratings yet
1 AWT Notes
44 pages
awt
PDF
No ratings yet
awt
96 pages
Unit 3 Introducing The AWT
PDF
No ratings yet
Unit 3 Introducing The AWT
8 pages
ajp chp 1
PDF
No ratings yet
ajp chp 1
62 pages
Unit Ii
PDF
No ratings yet
Unit Ii
51 pages
Bbit2205-01 Awt 2024
PDF
No ratings yet
Bbit2205-01 Awt 2024
94 pages
AWT Class44
PDF
No ratings yet
AWT Class44
17 pages
Container: Useful Methods of Component Class
PDF
No ratings yet
Container: Useful Methods of Component Class
32 pages
Abstract Windows Toolkit
PDF
No ratings yet
Abstract Windows Toolkit
35 pages
Lecture 9 GUI Basic JLabel, Jbutton, JFrame
PDF
No ratings yet
Lecture 9 GUI Basic JLabel, Jbutton, JFrame
49 pages
Ch 1
PDF
No ratings yet
Ch 1
83 pages
AJP Unit I AWT
PDF
No ratings yet
AJP Unit I AWT
70 pages
Module 5
PDF
No ratings yet
Module 5
30 pages
Unit-I Abstract Window Toolkit (Autosaved)
PDF
No ratings yet
Unit-I Abstract Window Toolkit (Autosaved)
101 pages
UNIT-I
PDF
No ratings yet
UNIT-I
87 pages
Java - 1 AWT
PDF
No ratings yet
Java - 1 AWT
31 pages
Awt Swing Event Handling
PDF
No ratings yet
Awt Swing Event Handling
36 pages
Unit 5 Awt - Swing
PDF
No ratings yet
Unit 5 Awt - Swing
22 pages
Abstract Window Toolkit: (AWT) : Java AWT Classes Hierarchy
PDF
No ratings yet
Abstract Window Toolkit: (AWT) : Java AWT Classes Hierarchy
29 pages
VIPS Unit 3 AWT COMPONENTS, Event, Anonymous Class, Layout Manager
PDF
No ratings yet
VIPS Unit 3 AWT COMPONENTS, Event, Anonymous Class, Layout Manager
64 pages
Unit 1 - Awt
PDF
No ratings yet
Unit 1 - Awt
35 pages
Unit 3 and 4
PDF
No ratings yet
Unit 3 and 4
27 pages
PDF - JP-II UNIT 1 - 186 - N3
PDF
No ratings yet
PDF - JP-II UNIT 1 - 186 - N3
29 pages
Oop Chapter 4 - Gui
PDF
No ratings yet
Oop Chapter 4 - Gui
85 pages
AWT Hierarchy
PDF
No ratings yet
AWT Hierarchy
7 pages
JAVA_-_UNIT_4
PDF
No ratings yet
JAVA_-_UNIT_4
20 pages
Java Unit 4
PDF
No ratings yet
Java Unit 4
34 pages
1st unit
PDF
No ratings yet
1st unit
43 pages
Advanced Programming-Chapter 1,2,3, 4,5,6 and 7
PDF
No ratings yet
Advanced Programming-Chapter 1,2,3, 4,5,6 and 7
74 pages
JPR Assignments 4-5-6
PDF
No ratings yet
JPR Assignments 4-5-6
86 pages
Java Notes
PDF
No ratings yet
Java Notes
65 pages
Chap4_1.awt
PDF
No ratings yet
Chap4_1.awt
78 pages
8 Java AWT ButtonNew
PDF
No ratings yet
8 Java AWT ButtonNew
42 pages
Java Unit 3
PDF
No ratings yet
Java Unit 3
68 pages
Chap_01_Abstract Windowing Toolkit(modify)
PDF
No ratings yet
Chap_01_Abstract Windowing Toolkit(modify)
78 pages
Java AWT and Swing
PDF
No ratings yet
Java AWT and Swing
93 pages
Lecture 19 AWT
PDF
No ratings yet
Lecture 19 AWT
52 pages
Swing Notes
PDF
No ratings yet
Swing Notes
25 pages
Chapter - 1 Final
PDF
No ratings yet
Chapter - 1 Final
80 pages
Awt and Swings
PDF
No ratings yet
Awt and Swings
39 pages
Core Java AWT and Swings
PDF
No ratings yet
Core Java AWT and Swings
108 pages
Lesson No. 9 AWT SWING
PDF
No ratings yet
Lesson No. 9 AWT SWING
18 pages
Object Oriented Programming - Chapter Five - GUI
PDF
No ratings yet
Object Oriented Programming - Chapter Five - GUI
85 pages
Java AWT
PDF
No ratings yet
Java AWT
4 pages
Adj 01
PDF
No ratings yet
Adj 01
49 pages
Abstract Windowing Toolkit AWT
PDF
No ratings yet
Abstract Windowing Toolkit AWT
96 pages
Unit 1 - AWT (ABSTRACT WINDOW TOOLKIT)
PDF
No ratings yet
Unit 1 - AWT (ABSTRACT WINDOW TOOLKIT)
30 pages
Advanced Programming - Chapter 6
PDF
No ratings yet
Advanced Programming - Chapter 6
64 pages