🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Document Details

WellRoundedTurtle

Uploaded by WellRoundedTurtle

Tags

Java AWT GUI programming computer science

Full Transcript

Chapter 1 Abstract Window Toolkit Prepared by Prof.Suwarna Thakre INTRODUCTION AWT is an API to develop GUI or window based applications in Java Java AWT components are platform dependent i.e components are displayed accor...

Chapter 1 Abstract Window Toolkit Prepared by Prof.Suwarna Thakre INTRODUCTION AWT is an API to develop GUI or window based applications in Java Java AWT components are platform dependent i.e components are displayed according to the view of the OS In java GUI can be designed using some pre-defined classes. All these classes are defined in java.awt package CLASS HIERARCHY FOR PANEL AND FRAME AWT CLASS HIERARCHY Component:- All the elements like buttons, text fields, scrollbars etc are known as components. Container:-A container is a place wherein we add components like text field, button, checkbox etc. There are four types of containers available in AWT: Window, Frame, Dialog and Panel. AWT CLASS HIERARCHY Window:It has no border and no title. It uses BorderLayout as default layout manager. Panel: panel is the container that doesn’t contain title bar and menu bar.It can have other components like text field,button etc. DIALOG AND APPLET Dialog:-Dialog class has border and title. Frame:It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners. APPLET:-An applet is a Java program that can be embedded into a web page. It runs inside the web browser and works at client side. An applet is embedded in an HTML page using the APPLET tag and hosted on a web server. The AWT supports the following types of controls:  Labels  TextField  TextArea  Buttons  Check boxes  Choice  Lists  Menu These controls are subclasses of Component. ADDING 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( ),which is defined by Container. The add( ) method has several forms. Component add(Component compObj) Here, compObj is an instance of the control that we want to add. A reference to compObj is returned. Once a control has been added, it will automatically be visible whenever its parent window is displayed. REMOVING CONTROLS Sometimes you will want to remove a control from a window when the control is no longer needed. To do this, call remove(). This method is also defined by Container. It has this general form: void remove(Component obj) Here, obj is a reference to the control we want to remove. we can remove all controls by calling void removeAll( ). LABELS The easiest control to use is a label. A label is an object of type Label, and it contains a string, which it displays. Labels are passive controls that do not support any interaction with the user. Label defines the following constructors: Label( ): It version creates a blank label Label(String str) :It creates a label that contains the string specified by str. This string is left-justified. Continue… Label(String str, int how):It creates a label that contains the string specified by str using the alignment specified by how. The value of how must be one of these three constants: Label.LEFT,Label.RIGHT,orLabel.CENTER. Program Using Label Class import java.awt.*; import java.applet.*; public class label123 extends Applet { public void init() { Label l1=new Label("one"); Label l2=new Label("two"); add(l1); add(l2); } } METHODS OF LABEL CLASS: void setText(String str): ):- It is used to set the label. String getText( ):- it is used to return the current label void setAlignment(int how):-We can set the alignment of the string within the label. int getAlignment( ):- To obtain the current alignment, Here, how must be one of the alignment constants shown earlier. BUTTON The most widely used control is the push button. A push button is a component that contains a label and that generates an event when it is pressed. Constructors are: Button( ): It creates an empty button. Button b1=new Button() Button(String str): It creates a button that contains str as a label. Button b2=new Button(―login‖) Program Using Button Class import java.awt.*; import java.applet.*; public class Button12 extends Applet { public void init() { setBackground(Color.red); setForeground(Color.blue); Button b1 =new Button("yes"); Button b2=new Button("no"); add(b1); add(b2); } } BUTTON Methods of button class: setLabel( ):It is used to set the label. syntax: void setLabel(String str) getLabel( ): It is used to obtained the label syntax: String getLabel( ) CHECKBOX A check box is a control that is used to turn an option on or off. It consists of a small box that can either contain a check mark or not. There is a label associated with each check box that describes what option the box represents. We change the state of a check box by clicking on it. Check boxes can be used individually or as part of a group. Check boxes are objects of the Checkbox class. CHECKBOX CONSTRUCTORS Checkbox supports these constructors: Checkbox( ): It creates a check box whose label is initially blank. The state of the check box is unchecked. Checkbox c1=new Checkbox() Checkbox(String str) :It creates a check box whose label is specified by str.The state of the check box is unchecked Chectbox c2=new Checkbox(―ENG‖); CHECKBOX CONSTRUCTORS Checkbox(String str, boolean on): It allows to set the initial state of the check box. If on is true, the check box is initially checked; otherwise, it is cleared. Checkbox c3=new Checkbox(―Windows/NT‖,true) Checkbox(String str, boolean on, CheckboxGroup cbGroup) Checkbox(String str, CheckboxGroup cbGroup, Program Using Checkbox import java.awt.*; import java.applet.*; public class check1 extends Applet { public void init() { Checkbox b1 =new Checkbox("c++"); Checkbox b2 =new Checkbox("java",true); add(b1); add(b2); } } METHODS OF CHECKBOX boolean getState( ):To retrieve the current state of a check box void setState(boolean on) :It is used to set the state. String getLabel( ):-It is used to obtained the current label associated with a check box Checkbox Method continue.. void setLabel(String str) :-It is used to set the label. Here, if on is true, the box is checked. If it is false, the box is cleared. The string passed in str becomes the new label associated with the invoking check box. PART-II Radiobutton ,choice and list CHECKBOXGROUP It 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 one time. These check boxes are often called radio buttons, because they act like the station selector on a car radio— only one station can be selected at any one time. To create radio button we can use fourth or fifth constructor of Check box. Constructors to create Radio Button Checkbox(String str, boolean on, CheckboxGroup cbGroup) Checkbox(String str, CheckboxGroup cbGroup, boolean on) METHODS OF CHECKBOXGROUP Checkbox getSelectedCheckbox( ) It is used to determine which check box in a group is currently selected void setSelectedCheckbox(Checkbox which) we can set a check box Here, which is the check box that you want to be selected. The previously selected check box will be turned off. Program to create Radiobutton import java.awt.*; import java.applet.*; public class radio1 extends Applet { public void init() { CheckboxGroup cbg=new CheckboxGroup(); Checkbox b1 =new Checkbox("M",cbg,false); Checkbox b2 =new Checkbox("F",cbg,true); add(b1); add(b2);} CHOICE CONTROL The Choice class is used to create a pop-up list of items When the user clicks on it, the whole list of choices pops up, and a new selection can be made. Each item in the list is a string that appears as a left-justified label in the order it is added to the Choice object. Choice only defines the default constructor, which creates an empty list. Eg. Choice() Choice c1=new Choice(); CHOICE CLASS METHODS To add a selection to the list, call add( ).It has this general form: void add(String name) Here, name is the name of the item being added. Items are added to the list in the order in which calls to add( ) occur. String getSelectedItem( ) :It returns a string containing the name of the item. int getSelectedIndex( ):-It returns the index of the item. The first item is at index 0. By default, the first item added to the list is selected. CHOICE CLASS METHODS int getItemCount( ):To obtain the number of items in the list. void select(int index) Or void select(String name) we can set the currently selected item using the select( ) method with either a zero-based integer index or a string that will match a name in the list. Continue… String getItem(int index):-We can obtain the name associated with the item at that index by Here, index specifies the index of the desired item Program Using Choice class import java.awt.*; import java.applet.*; public class choice1 extends Applet { public void init() { Choice c1=new Choice(); c1.add("Win/xp"); c1.add("win/nt"); c1.add("win/2000"); add(c1); } } LIST CLASS The List class provides a compact, multiple-choice, scrolling selection list. 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. CONSTRUCTOR OF LIST CLASS List( ) It creates a List control that allows only one item to be selected at any one time. List(int numRows):- The value of numRows specifies the number of entries in the list that will always be visible (others can be scrolled into view as needed). List(int numRows, boolean multipleSelect): if multipleSelect is true, then the user may select two or more items at a time.If it is false, then only one item may be selected. Chapter 1 Abstract Window Toolkit PART-III AWT Compontes---TextField,TextArea Prepared by Prof.Suwarna Thakre TextField The TextField class implements a single-line text-entry area, usually called an edit control. Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and paste keys, and mouse selections. TextField is a subclass of TextComponent. Constructors of TextField TextField( ):- creates a default text field TextField(int numChars):-creates a text field that is numChars characters wide. TextField(String str):-It initializes the text field with the string contained in str. TextField(String str, int numChars) The fourth form initializes a text field and sets its width. Methods of TextField Methods are as follows: String getText( ):it is used to obtain the string currently contained in the text field. void setText(String str):it is used to set the text in text field.Here, str is the new string. Methods Of TextField void setEchoChar(char ch) boolean echoCharIsSet( ) char getEchoChar( ) Here, ch specifies the character to be echoed. First method specifies a single character that the TextField will display when characters are entered (thus, the actual characters typed will not be shown) Program using TextField import java.awt.*; import java.applet.*; public class textfield1 extends Applet { public void init() {setLayout(new FlowLayout()); TextField c1=new TextField(); TextField c2=new TextField(20); TextField c3=new TextField("information"); TextField c4=new TextField(" info",30); add(c1);add(c2);add(c3);add(c4); } } Program Using TextField import java.awt.*; import java.applet.*; public class textfield2 extends Applet { public void init() { Label l=new Label("enter name"); Label l1=new Label("enter password"); TextField c1=new TextField(20); TextField c2=new TextField(20); c2.setEchoChar('*'); add(l);add(c1);add(l1);add(c2); } } TextArea Sometimes a single line of text input is not enough for a given task. To handle these situations, the AWT includes a simple multiline editor called TextArea. Following are the constructors for TextArea: TextArea( ) TextArea(int numLines, int numChars) TextArea(String str) TextArea(String str, int numLines, int numChars) Constructor Of TextArea TextArea(String str, int numLines, int numChars, int sBars) Here, numLines specifies the height, in lines, of the text area, and numChars specifies its width, in characters. Initial text can be specified by str. In the fifth form we can specify the scroll bars that we want the control to have. TextArea is a subclass of TextComponent Scroll Bar Constants sBars must be one of these values: SCROLLBARS_BOTH SCROLLBARS_NONE SCROLLBARS_HORIZONTAL_ONLY SCROLLBARS_VERTICAL_ONLY Methods Of TextArea it supports the getText( ), setText( ), getSelectedText( ) methods of TextField. TextArea adds the following methods: void append(String str): It appends the string specified by str to the end of the current text. Methods Of TextArea void insert(String str, int index):inserts the string passed in str at the specified index. void replaceRange(String str, int startIndex, int endIndex):-Itreplaces the characters from startIndex to endIndex–1, with the replacement text passed in str. Program Using TextArea import java.awt.*; import java.applet.*; public class textarea extends Applet { public void init() { String str="The TextArea control in AWT provide us multiline editor area"; TextArea ta3=new TextArea(str); ta3.setBounds(20,30,80,120); ta3.append(" we can append data"); ta3.insert(" is powerful",13); add(ta3); } } Menu Bars and Menus A 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. To create a menu bar, first create an instance of MenuBar. This class only defines the default constructor. Next, create instances of Menu that will define the selections displayed on the bar. Constructors of Menu Following are the constructors for Menu: Menu( ) Menu(String optionName) Menu(String optionName, boolean removable) Here, optionName specifies the name of the menu selection. If removable is true, the pop-up menu can be removed and allowed to float free. Otherwise, it will remain attached to the menu bar MenuItem Constructors It defines these constructors: MenuItem( ) MenuItem(String itemName) MenuItem(String itemName, MenuShortcut keyAccel) Methods of Menu Class We can disable or enable a menu item by using the setEnabled( ) method. Its formis shown here: void setEnabled(boolean enabledFlag) If the argument enabledFlag is true, the menu item is enabled. If false, the menu item is disabled. Methods of Menu class We can determine an item’s status by calling isEnabled( ). This method is shown here: boolean isEnabled( ):It returns true if the menu item on which it is called is enabled. Otherwise,it returns false. void setLabel(String newName): we can change the name of menu item String getLabel( ) we can retrieve the current name CheckboxMenuItem we can create a checkable menu item by using a subclass of MenuItem called CheckboxMenuItem. It has these constructors: CheckboxMenuItem( ) CheckboxMenuItem(String itemName) CheckboxMenuItem(String itemName, boolean on) Program using setEnabled Method import java.awt.*; class framemenu2 class framemenu21 extends Frame { {framemenu21(String s) public static void main(String arg[]) { { super(s); framemenu21 f=new setSize(200,200); framemenu21("demo"); setVisible(true); MenuBar mb= new MenuBar(); setMenuBar(mb); } Menu m1= new Menu("file"); } mb.add(m1); Menu m2= new Menu("edit"); mb.add(m2); MenuItem f1=new MenuItem("New"); MenuItem f2=new MenuItem("Open"); MenuItem e1=new MenuItem("cut"); m1.add(f1);m1.add(f2);m2.add(e1); f2.setEnabled(false); }} Program using Menu ,MenuItem,CheckboxMenuItem import java.awt.*; class framemenu class framemenu1 extends Frame { {framemenu1(String s) public static void main(String arg[]) { { super(s); framemenu1 f=new setSize(200,200); framemenu1("demo"); setVisible(true); MenuBar mb= new MenuBar(); setMenuBar(mb); } Menu m1= new Menu("file"); } mb.add(m1); CheckboxMenuItem c=new CheckboxMenuItem("open",true); MenuItem m2=new MenuItem("save"); m1.add(c);m1.add(m2); }} Layout Manager Each Container object has a layout manager associated with it. A layout manager is an instance of any class that implements the LayoutManager interface. The layout manager is set by the setLayout( ) method. If no call to setLayout( ) is made, then the default layout manager is used. Whenever a container is resized (or sized for the first time), the layout manager is used to position each of the components within it. Layout Managers The layout manager is set by the setLayout( ) method. Syntax: void setLayout(LayoutManager layoutObj) Types of layout managers for general use: BorderLayout FlowLayout GridLayout GridbagLayout CardLayout FlowLayout FlowLayout is the default layout manager of Applet. Components are laid out from the upper-left corner, left to right and top to bottom. When no more components fit on a line, the next one appears on the next line. A small space is left between each component, above and below, as well as left and right. Constructors FlowLayout( ) FlowLayout(int how) FlowLayout(int how, int horz, int vert) The first form creates the default layout, which centers components and leaves five pixels of space between each component. The second form lets you specify how each line is aligned. Valid values for how are as follows: FlowLayout Costants FlowLayout.LEFT FlowLayout.CENTER FlowLayout.RIGHT These values specify left, center, and right alignment, respectively. The third form allows you to specify the horizontal and vertical space left between components in horz and vert, respectively. Program using FlowLayout import java.awt.*; import java.applet.*; public class flowlayout extends Applet { public void init() {setBackground(Color.green); Button b1=new Button("b1"); Button b2=new Button("b2"); Button b3=new Button("b3"); Button b4=new Button("b4"); Button b5=new Button("b5"); add(b1);add(b2);add(b3); add(b4);add(b5); }} FlowLayout program using constants import java.awt.*; import java.applet.*; public class flowlayout1 extends Applet { public void init() {setBackground(Color.green); setLayout(new FlowLayout(FlowLayout.LEFT)); Label l1=new Label("enter your name"); Label l2=new Label("enter password"); add(l1);add(l2); }} FlowLayout program using constants import java.awt.*; import java.applet.*; public class flowlayout extends Applet { public void init() {setBackground(Color.green); setLayout(new FlowLayout(FlowLayout.CENTER,40,40)); Button b1=new Button("b1"); Button b2=new Button("b2"); Button b3=new Button("b3"); Button b4=new Button("b4"); Button b5=new Button("b5"); add(b1);add(b2);add(b3); add(b4);add(b5); } } BorderLayout The BorderLayout class implements a common layout style for top-level windows. It has four narrow, fixed-width components at the edges and one large area in the center. The four sides are referred to as north, south, east, and west. The middle area is called the center. constructors BorderLayout( ): The first form creates a default border layout BorderLayout(int horz, int vert):The second allows you to specify the horizontal and vertical space left between components in horz and vert, respectively. Continue… BorderLayout defines the following constants that specify the regions: BorderLayout.CENTER BorderLayout.SOUTH BorderLayout.EAST BorderLayout.WEST BorderLayout.NORTH Program Using BorderLayout import java.awt.*; add(b3,BorderLayout.NORTH); import java.applet.*; add(b4,BorderLayout.SOUTH); } public class border1 extends Applet { public void init() { Button b1=new Button("EAST"); Button b2=new Button("WEST"); Button b3=new Button("NORTH"); Button b4=new Button("SOUTH"); Button b5=new Button("CENTER"); setLayout(new BorderLayout()); add(b1,BorderLayout.EAST); add(b2,BorderLayout.WEST); GridLayout GridLayout lays out components in a two-dimensional grid. In GridLayout, we can define the number of rows and columns. The constructors supported by GridLayout( ):-creates a single-column grid layout. GridLayout(int numRows,int numColumns) creates a grid layout with the specified number of rows and columns. Continue.. GridLayout(int numRows, int numColumns, int horz, int vert) The third form allows you to specify the horizontal and vertical space left between components in horz and vert, respectively. Program using First Constructor import java.awt.*; import java.applet.*; public class gridlayout extends Applet { public void init() { setLayout(new GridLayout()); Button b1=new Button("b1"); Button b2=new Button("b2"); Button b3=new Button("b3"); Button b4=new Button("b4"); Button b5=new Button("b5"); add(b1);add(b2);add(b3); add(b4);add(b5); } } Program using second constructor import java.awt.*; import java.applet.*; public class gridlayout1 extends Applet { public void init() { setLayout(new GridLayout(2,3)); Button b1=new Button("b1"); Button b2=new Button("b2"); Button b3=new Button("b3"); Button b4=new Button("b4"); Button b5=new Button("b5"); add(b1);add(b2);add(b3); add(b4);add(b5); } } Program using Third Constructor import java.awt.*; import java.applet.*; public class gridlayout2 extends Applet { public void init() { setLayout(new GridLayout(2,3,15,15)); Button b1=new Button("b1"); Button b2=new Button("b2"); Button b3=new Button("b3"); Button b4=new Button("b4"); Button b5=new Button("b5"); add(b1);add(b2);add(b3); add(b4);add(b5); } } Frame It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners. Here are two of Frame’s constructors: 1.Frame( ) It creates a standard window that does not contain a title. 2.Frame(String title) It creates a window with the title specified by title. METHODS OF FRAME CLASS void setSize(int newWidth, int newHeight) void setSize(Dimension newSize) 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. void setTitle(String str): -It is used to set title to the frame. void setVisible(boolean on ): -Set frame is visible or not Program Using Frame import java.awt.*; public static void main(String args[]) public class frame extends Frame { { frame f1=new frame("framedemo"); frame(String s) f1.setSize(0,0); { f1.setVisible(true); super(s); } setLayout(new FlowLayout()); } Label l1=new Label("enter name:"); TextField t1=new TextField(20); Label l2=new Label("enter password"); TextField t2=new TextField(20); t2.setEchoChar('*'); Button b1=new Button("submit"); add(l1);add(t1); add(l2);add(t2); add(b1); } Program Using Frame import java.awt.*; public static void main(String args[]) public class frame extends Frame { { frame f1=new frame("framedemo"); frame(String s) f1.setSize(200,200); { f1.setVisible(true); super(s); } setLayout(new FlowLayout()); } Label l1=new Label("enter name:"); TextField t1=new TextField(20); Label l2=new Label("enter password"); TextField t2=new TextField(20); t2.setEchoChar('*'); Button b1=new Button("submit"); add(l1);add(t1); add(l2);add(t2); add(b1); } Program Using Frame import java.awt.*; f.add(l1);f.add(t1); class frame2 f.add(l2);f.add(t2); { f.add(b1); public static void main(String f.setSize(200,200); args[]) f.setVisible(true); { } Frame f=new Frame("frame } demo"); f.setLayout(new FlowLayout()); Label l1=new Label("enter name:"); TextField t1=new TextField(20); Label l2=new Label("enter password"); TextField t2=new TextField(20); t2.setEchoChar('*'); Button b1=new Button("submit");

Use Quizgecko on...
Browser
Browser