You are on page 1of 43
yr wae 137 ent Helis f SYNOPSIS i i 111 What is Event & Event Handling? | 112. The Delegation Event Model i 113 Event Sources i 114 Event Listeners i 11.5 Event Classes i 115.1 The ActionEvent Class i 11.5.2 The AdjustmentEvent Class i 115.3. The ComponentEvent Class i 115.4 The ContainerEvent Class i 11.5.5 The FocusEvent Class i 11.5.6 The InputEvent Class i 115.7 The ItemEvent Class i 115.8 The KeyEvent Class dl 115.9 The MouseEvent Class i 115.10 The TextEvent Class ae i 11,5.11 The WindowEvent Class | 116 Sources of Events 4 {117 Event Listener Interfaces i 11.7.1 The ActionListener Interface i 11.7.2 The AdjustmentListener Interface i 11.7.3 The ComponentListenér Interface I 11.74 The ContainerListener Interface i 11.7.5" The FocusListener Interface } 11.7.6 The ItemListener Interface } 11.7.7 The KeyListener Interface t 11.7.8 The MouseListener Interface ! 113.9 The MouseMotionListener Interface i 117.10 The MouseWheelListener Interface 11.7.1 The TextListener Interface 11,7.12 The WindowFocusListener Interface 1.7.13 The WindowListener Interface 11.8 Using the Delegation Event Model 119 Adapter Classes 11.10 Inner Classes Questions tie _ roe 19 ud WHATS EVENT & EVENT HANDLING? = The event with regards to computer user is the interaction medium between user and ommputer Event means anything that happens at that instance of the time. In GUI the jxonts Tike mouse click, key press are familiar to all of us. An event is an object that gesribes a state change in a source. It can be generated as a consequence of a person iqeracting with the elements in a graphical user interface. Some of the activities that quae events to be generated are pressing a button, entering a character via the keyboard, ‘gesting an item in a list, and clicking the mouse. - For any programming language, the event generated by the user or the system must te informed, registered and processed for the proper user response. The java language provides a very good mechanism to handle the events. 2 THE DELEGATION EVENT MODEL ‘There are three parts to the event delegation model in Java. These all three aspects ar known as the event delegation model. The delegation event model defines standard and consistent mechanisms to generate and process events. A source generates an event and sends it to one or more listeners, The listener simply waits until it receives an event. once an event is received, the listener processes the event and then returns. In the delegation event model, listeners must register with a source in order to receive an event rolification. This provides an important benefit: notifications are sent only to listeners that want to receive them. This is a more efficient way to handle events. Events, Events Classes, Listener and Adapters are the parts of the delegation event noel. L_ Event object This is an object of a Java class that contains the characteristics of the event. For ample, if the event is generated from clicking a mouse button, the event object would contain information such as the coordinates of the mouse cursor, which button was dlcked, how many times it was clicked, ete. IL Dispatching Class/Method This is an object, which finds that an event has occurred and is then responsible for iforming other objects of the event, passing the appropriate event object to those objects. These other objects are "listeners" for the event. Most AWT components, such as Button, Ust, Textfield, etc. are examples of dispatching classes. These methods are ‘addxxListener (to add an object as a listener) for example Yormally named like, AddKeyListener. th, istener Interface For the dispatching to work properly, the dispatching class must be able to trust on. thod that it executes when the event occurs. This is “ch of its listeners to contain the me . curs ‘ly done in Java through the use of an Interface class, The important point is that a ‘85, which is going to be a listener, must implement that interface. Core Jaa (8. B.Se. (LT.)~ Sem, yy aa ras" 11.3 EVENT SOURCES ‘An event source is a graphical component that is capable of fe eof es Ge tig an object that generates an event.This occurs when the inter ton ae i object changes. Event sources can be any graphical component (¢.8 el i create CKBox, etc..) the user can interact with. For example, when a Button is clicked #t creates a button click event which can be processed by the Java application. A source must register listeners in order for the listeners to ee notification about a specific type of event. Each type of event has its own registration method. The general form of it as: public void addTypeListener(TypeListenerel) Here, Type is the name of the event, and el is a reference t example, . ‘A method that registers a keyboard event listener is called addKeyListenert ). 114 EVENT LISTENERS | 10 the event listener. For An event listener is used to process events. It is an object that is notified when an event occurs. For example, a graphical component like a Button or TextField is known as event sources. This means they can generate events - when a user clicks on the Button or types text into the TextField. The event listeners job is to catch those events and do | something with them. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications. For example, the MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved. 11.5 EVENT CLASSES The classes that represent events are at the core of Java's event handling mechanism. The super class of all event classes is java.util.EventObject and AWTEvent is a super class of all AWT events that are handled by the delegation event model. Some of the important classes and their hierarchy is shown below. Some methods related to Events are : Object getSource() : This method is defined in the Event Object class. It returns the object that originated the event. So if the user has clicked a Push button, the method getSource returns the object corresponding to Push button is generated, intgetID0 ; This method returns the integer value corr event. For example if the user has clicked on the mouse, the integer defined as MouseEvent: MOUSE_CLICKED. esponding to the type of method getID returns the yy lin speent Ho idling: , vow a } Commonly used constructors at , 7 | 4 aowing sections : nd_methods in each class are described in the java.lang.Object java.util. EventObject! java.awt.AWTEvent mam) [os [ ActionEv fjustmentEvent] _ [Componentiivent] [ ItemEvent ] [_tentevent ota L ContainerEvent Poousivent InputEvent PaintEvent ‘| WindowEvent 115.1 The ActionEyent Class _ The ActionEvent is generated by an AWT component, such as a button, when a component. action is performed. The action event is generated when a button is pressed, a list item is double-clicked, or a menu item is selected. tion of the constructor of the ActionEvent class Following syntax shows the declarat is: . ‘ActionEvent(Object src, int type, String cmd) ‘ActionEvent(Object stc, int type, String cmd, int modifiers) ActionEvent(Object src, int type, String cmd, Iong when, int modifiers) | Here, srcis a reference to the object that generated this event. The type of the event is specified by type, and its command string is cmd. The argument modifiers indicates which modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed when the event was generated. The when param en the event occurred. The important methods includes String getActionCommand() It is used to obtain the name of command. For example, when a button is pressed, an action event is generated that ha: d name equal to the label on that button. s a comman 1152 The AdjustmentEvent Class The AdjustmentEvent is generated w! , Scrollbar is the only GUI control that receives the AdjustmentEvent. ya scroll bar. There are five types of adjustments i ant is generated by that eae with a eeplibar as BLOCK_DECREMENT, BLOCK_INCREMENT, TRACK, UNIT_DECREMENT and 'UNIT_INCREMENT. ‘There is an integer constant "ADJUSTMENT_VALUE_ CHANGED that indicates that is an int ‘ @ change has occurred. eter specifies wh din the Action Event class is : hen the user adjusts the position of a scrollbar. - Jaga (S.Y.B.Se. (LT.)~ Sem. —1y) i go's" Core d by the getAdjustmentType( ) The type of the adjustment event may be obtaine ‘The general form ig method, It returns one of the constants defined by AdjustmentE vent: shown here : int getAdjustmentType( ) ‘The amount of the adjustment can be obtained from the here: getValue( ) method, shown int getValue( ) For example, when a scroll bar is manipulated, this represented by that change. 11.5.3 The ComponentEvent Class The ComponentEvent is generated when the size, position, oF visibility ofa component is changed. There are four types of component events, 08 hidden, Moved, Resized, Shown. The ComponentEvent class defines _integer__ constants (COMPONENT_HIDDEN, COMPONENT MOVED, COMPONENT_RESIZED, and COMPONENT_SHOWN) that can be used to identify them. ‘ComponentEvent has following constructor : ComponentEvent(Component sre, int type) Here, src is a reference to the object that generated this event. The type of the event is specified by type, 11.5.4 The ContainerEvent Class The Containerlivent is generated when a component is added to or removed from 2 container. There are two types of container events. The ContainerEvent class defines int constants that can be used to identify them: COMPONENT_ADDED and COMPONENT_REMOVED. They indicate that a component has been added to or removed from the container. ContainerEvent has following constructor : ContainerEvent(Component src, int type, Component comp) Here, src is a reference to the container that generated this event. The type of the event is specified by type, and the component that has been added to or removed from the container is comp. 11.55 The FocusEvent Class This event is generated when a component gains or losses focus. Focus may be gained by bringing the mouse over a component (or by using the tab key). The component that has the focus receives all user keyboard events. Focus events at generated by objects of Component class and all its subclasses, These events are identified by the integer constants FOCUS_GAINED and FOCUS_LOST. FocusEvent has following constructors : 5 method returns the value FocusEvent(Component src, int type) FocusEvent(Component sre, int type, Boolean tempFlag) FocusEvent(Component src; inttype, Boolean tempFlag, Component other) Here, src is a reference to the component that generated this event. The type of the event is specified by type. The argument tempFlag is ‘ i iB is set to t vent iS temporary. Otherwise, it is set to false. rue if the focus e' yr estos oor = 156 The InputEvent Class ‘the abstract class InputEvent is a subclass of ComponentEvent and is the superclass ie component input events. Its subclasses are KeyEvent and Mousefivent. inputBvent defines several integer constants that represent any modifiers, such as the control Key being pressed, that might be associated with the event. 1157 The ItemEvent Class ‘AnltemEvent is generated when an item is selected or deselected. Following qmponents generate ItemEvents, @ CheckBox generate ItemEvent when the state of the CheckBox is changed. @ CheckBoxMenultem generate ItemEvent when the state of a Menultem is changed. | @ Choice generate ItemEvent when the state of a ChoiceBox is changed. © List generate ItemEvent when an item in list is selected or deselected. The ItemEventhas following constructor : ItemEvent(ItemSelectable src, int type, Object entry, int state) Here, src is a reference to the component that generated this event. For example, this night be a list or choice element. The type of the event is specified by type. The specific jem that generated the item event is passed in entry. The current state of that item is in state The getltem( ) method can be used to obtain a reference to the item that generated an event. The getltemSelectable( ) method can be used to obtain a reference to the temSelectable object that generated an event. The getStateChange( ) method returns the state change for the event. 1158 The KeyEvent Class A KeyEvent is subclasses of abstract InputEvent class. It is generated when keyboard input occurs. There are three types of key events, which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. Other integer constants defined by KeyEvent class areVK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbers and letters. The VK constants specify virtual key codes and are independent of any modifiers, such as control, shift, or alt. ‘The Constructor for KeyEvent Class is as follows : KeyBvent(Component st¢, int type, long when, int modifiers, int code, char ch) Here, src is a reference to the component that generated the event. The type of the ‘vent is specified by type- The KeyEvent class defines many methods, such as getKeyChar( ), getKeyCode( ), Which returns the key Char & code. 1159 The MouseEvent Class ‘A MouseRvent is subclasses of abstract InputEvent class. There are eight types of "mouse events that can be identified by Integer constants like MOOUSE_CLICKED, MOUSE DRAGGED, MOOUSE_ENTERED, MOOUSE_EXITED, MOOUSE_MOVED, MOOUSE_PRESSED, MOOUSE_RELEASED, MOOUSE_WHEEL, Core java (S.Y.B-Se. (LT) ~ Sem. —1y) 4 vas MouseEvent Class Constructor is written as : MouseEvent(Component src, int type, long when Int x, inty, int clicks, Boolean triggersPopup) ie the class are getX( ),8et™() int modifiers, ‘The general methods provided by and getPoint( ) which obtains the coordinates of the mouse, 115.10 The TextEvent Class TextEvent class in java.awteve text area is _changed.Integer TEXT_VALUE_CHANGED. The Constructor TextEvent(Object src, int type) ints created when text field o; by TextBvent class is “iefined by TextBvent class as follows: snt package handles eve! constant defined 11.5.1 The WindowEvent Class indowEvent are generated for the ted if an operation is performed WindowEvent is a subclass of ComponentEvent Wi Window class and its subclasses. These events are genera! ona window. The operation could be closing of window, opening of window, activating a window etc. There are ten types of window events for that we have integer constants as @ =WINDOW_OPENED: When window is opened. WINDOW. CLOSED When window is closed. WINDOW _CLOSING When user instructed window to be closed. WINDOW_ACTIVATED: When window is ‘WINDOW_DEACTIVATED: When window WINDOW_ICONIFIED When window is iconified. WINDOW_DEICONIFIED: When window is deiconified. WINDOW_GAINED_FOCUS: When window gained input focus. WINDQW_LOST_FOCUS: When-window lost input focus. WINDOW _STATE_CHANGED: When state of window is changed. Class defines several constructors a5 ~ WindowEvent(Window src, int type) WindowEvent(Window src, int type» Window other) Window vent(Window sr int type, int fromState int toState) int type, Window other, int fromState, int toStafe) ‘WindowEvent(Window sre, i src is a reference to the object that generated this event. The type of the event is type, other specifies the opposite vindow when a focus or activation event occurs. The fromState specifies the prior state of the window, and toState specifies the new state that the window will have when a window state change occurs, ‘The dass provides method getWindow( ) which returns the Window object generated the event. = [11.6 SOURCES OF EVENTS pi J The Source of event is always 4 component or a control that causes to trigger the nt source is a graphical component that is capable of firing off an event nical component (e.g, Button, List, Combo Box, Check Box activated. is deactivated. Here, that event. An evel Event sources can be any grap! rr su el vee me List, Menu Item, Scroll Bar, Text Components, with. For example, when a Button is clicked it creates a button sed by the Java applicatior Window etc...) the user can choice oO click event which interact can be POSE qi7_EVENT LISTENER INTERFACES Tj event listener is used to process events. For example, a graphical component like gutton oF TextField is known as event sources. This means they can generate events - wren a user clicks on the Button or types text into the TextField. The event listener's job jzto catch those events and do something with them. Java provides @ good range of event fstener interface to implement them. To write an Action Listener, We can use the steps given below : 1. Declare an event handler class and specify that the class either implements 2" ‘ActionListener interface or extends a class that implements an ActionListener interface. For example : public class TClass implements ActionListener { .. 2. Register an instance of the event handler class as a listener on one or more components. For example : someComponent.addActionListener(instanceOfTClass); 3, Include code that implements the methods in listener interface. For example : public void actionPerformed(ActionEvent e) { ..//code that reacts to the action... } 11.7.1 The ActionListener Interface ‘This interface defines the actionPerformed( ) method that is invoked when an action event occurs. Its general form is shown here : void actionPerformed(ActionEvent ae) 1172 The AdjustmentListener Interface This interface defines the adjustmentValueChanged( ) method that is invoked when anadjustment event occurs. Its general form is shown here : void adjustmentValueChanged(AdjustmentEvent ae) 1173 The ComponentListener Interface This interface defines four methods that are invoked when a component is resized, moved,shown, or hidden. Their general forms are shown here : void componentResized(ComponentEvent ce) void componentMoved(ComponentEvent ce) void componentShown(ComponentEvent ce) void componentHidden(ComponentEvent ce) Y.B.Se.(.T.) ~Sem.~ TV) 146 222" Care java (5 11.7.4 The ContainerListener Interface This interface contains two methods. When @ compo! ieee : ed fr container,componentAdded( ) is invoked. When 2 component i aes ‘om a container,componentRemoved( ) is invoked. Their general forms are sho 2 void componentAdded(ContainerEvent ce) void componentRemoved(ContainerEvent ce) nent is added to a 11.7.5 The FocusListener Interface This interface defines two methods, When 4 component obtains keyboard focus, focusGained( ) is invoked. When a component loses keyboard focus, focusLost( ) is called, ‘Their general forms are shown here : void focusGained(FocusEvent fe) void focusLost(FocusEvent fe) 11.7.6 The ItemListener Interface “This interface defines the itemStateChanged( ) method that isi of an item changes. Its general form is shown here : invoked when the state void itemStateChanged (ItemEventie) 41.7.7 The KeyListener Interface ‘This interface defines three methods. The keyPressed( ) and keyReleased(.) methods Jy. The keyTyped( ) method is are invoked when a key is pressed and released, respective! invoked when a character has been entered. For example, if a user presses and releases the A key, three events 2°© generated in sequence: key pressed, typed, and released. If a user preset and releases the HOME key, two key events are generated in sequence: key pressed and released. ‘The general forms of these methods are shown here : void keyPressed(KeyEvent ke) void keyReleased(KeyEvent ke) void keyTyped(KeyEvent ke) 11.7.8 The MouseListener Interface ‘This interface defines five methods. If the mouse is pressed and released at the same point, mouseClicked( ) is invoked. When the mouse enters a component, the penuseEntered( ) method is called. When it leaves, mouseExited( ) is called. The mousePressed( ) and mouseReleased( ) methods are invoked when the mouse is pressed and released, respectively. ‘The general forms of these methods are show here : void mouseClicked(MouseEvent me) void mouseEntered(MouseEvent me) void mouseExited(MouseEvent me) void mousePressed(MouseEvent me) void mouseReleased(MouseEvent me) r ent Hats rrr “ ‘The MouseMotionListener Interface This interface defines two methods. The mouseDragged( ) method is called multiple jmes as the mouse is dragged. The mouseMoved( ) method is called multiple times as the fpouse is moved. Their general forms are shown here : void mouseDragged(MouseEvent me) __-void mouseMoved(MouseEvent me) 11740 The MouseWheelListener Interface This interface defines the mouseWheelMoved( ) method that is invoked when the ouse wheel is moved. Its general form is shown here : void mouseWheelMoved(MouseWheelEvent mwe) 11711 The TextListener Interface This interface defines the textChanged( ) method that is invoked when a change eccurs in a text area or text field. Its general form is shown here : void textChanged(TextEvent te) 117.12 The WindowFocusListener Interface This interface defines two methods: windowGainedFocus(_) and vwindowLostFocus( ). These are called when a window gains or loses input focus. Their general forms are shown here : void windowGainedFocus(WindowEvent we) void windowLostFocus(WindowEvent we) 11743 The WindowListener Interface This interface defines seven methods. The _windowActivated(__)__and windowDeactivated( ) methods are invoked when a window is activated or deactivated, respectively. ‘If a window is iconified, the windowlconified( ) method is called. When a window is deiconified, the windowDeiconified( ) method is called. When a window is opened or closed, the windowOpened( ) or windowClosed( ) methods are called, respectively. The windowClosing( ) method is called when a window is being closed. The general forms of these methods are — void window Activated(WindowEvent we) void windowClosed(WindowEvent we) void windowClosing(WindowEvent we) void windowDeactivated(WindowEvent we) void windowDeiconified(WindowEvent we) void windowlconified(WindowEvent we) void windowOpened(WindowEvent we) * 22's" Core java (S.Y-B.Sc. (LT) - Sem, 11.8 USING THE DELEGATION EVENT MODEL model in practice program. Following Keyboard events. Now we are ready to use the delegation event simple java program demonstrates the handling of mouse and Example: /*Demonstrate use of MouseKeyEvent"/ import java.awt.*; import java.awt.event.*; import java.applet:*; r ‘MouseKeyEvents" width=500 height-200> public class TMouseKeyEvents extends Applet implements MouseListener, KeyListener { String mymsg ="; int X = 0,'Y = 0; // coordinates of mouse public void init( ) { addMouseListener(this); addKeyListener(this); } // Here is the cdde for mouse clicked. public void mouseClicked(MouseEvent me) ( // save coordinates X=0; 3 Y¥ =10; 7 mymsg = "You have clicked the Mouse Ke; repaint( ); } // Here is the code for mouse entered. public void mouseEntered(MouseEvent me) { |/ save coordinates mymsg =" Now Mouse entered in the window."; repaint(); } | Here is the code for mouse exited. pent Harling ree 49 public void mouseExited(MouseEvent me) | yjsave coordinates X=0; y=10; mymsg = "Now Mouse exited from the window.": repaint( ); ' || Here is the code for mouse button pressed. public void mousePressed(MouseEvent me) { I] save coordinates X=me.getX( ); Y= me.get¥(); mymsg = "Down"; repaint( ); } || Here is the code for mouse button released. public void mouseReleased(MouseEvent me) { II save coordinates X=megetX(); Y= megetY(); mymsg = "Up"; repaint(); ' : || Here is the code for keyboard key Pressed. public void keyPressed(KeyEvent ke) { showStatus(" You have Pressed keyboard Key Down"); } | Here is the code for keyboard key Released public void keyReleased(KeyEvent ke) { showStatus("You have Pressed keyboard Key Up"); ' I/ Here is the code for keyboard key typed public void keyTyped(KeyBvent ke) { mymsg += ke.getKeyChar( ); repaint ); } ia Ma Display mymsg in applet window Se, (LT.).-Core Java (Sem.-IV) Core Java (S-Y-B.Se. (LT.)~ Sem.—1y) 150 20" public void paint(Graphics g) { , g.drawString(mymsg, X, Y); ) ) Running the Program weer aud Ck lion ‘Applet Now Mouse entered in the window. syooatd Key UP You have Pressed ke applet started 11.9 ADAPTER CLASSES ‘entation of all methods in an event ‘An adapter class provides the default implem listener interface. An adapter class provides an empty implementation of all methods in an event listener interface i.e this class itself write definition for methods. which.are piesent if: particular event listenet interface. Adapter classes are very useful when you want to process only few of the events that are handled by a particular event listener Interface. We can define a new class by extending one of the adapter classes and implement only those events relevant to us: “Every listener that includes more than one abstract method has got a corresponding adapter class”. The advantage of adapter is that Wve can override any one or two methods we like instead of all. ‘Adapter classes are usefull when you want fo receive and process only some of the events that are handled by a particular event listener interface. We can define a new class to act as an event listener by extending one of the adapter classes and implementing only those events in which we are interested. For example, the MouseMotionAdapter class has two methods, mouseDragged( } and mouseMoved( ), which are the methods defined by th .MotionListenerinterface. If you were interested in only mouse drag events, then MouseMotionAdapterand override mouseDragged( ). The empty ) would handle the mouse motion events for us. Mouse we could simply extend implementation of mouseMoved( ‘Adapter classes are mentioned below. Some of the ComponentAdapter_| KeyAdapter ContainerAdapter _| MouseAdapter FocusAdapter MouseMotionAdapter WindowAdapter pee Hoang vee mt sample program of Adapter class is shown below: import java.applet.*; import java.awt-*; import java.awtevent.; public class TAdapterDemo extends Applet{ public void init( ){ addMouseListener( new MouseAdapter( ){ int X, Y; public void mouseReleased(MouseEvent me){ X=me.getX(); Y= me.getY( ); Graphics g = TAdapterDemo..this.getGraphics(); g.drawString("Mouse Realeased", X,Y); } Ds ' } Output : POPC CC ERC ac cad (Pa T=TE3) Applet Mouse Realeased Mouse Realeased applet started 11.10 INNER CLASSES In object-oriented programming , an inner class or nested class is a class declared entirely within the body of another class ot interface. Itis distinguished from a subclass. So an inner class is a class defined within another class, or even within an expression. Inner classes can be used to simplify the code when using event adapter classes as shown below. ‘Inner class demo. import java.applet*; import java.awtevent"; a's"! core jou (S.¥-B:Se(1.T.)~ Sem. yy 152 r a public class TinnerClass extends Applet { public void init() { addMouseListener(new TMouseAdapter()); } class TMouseAdapter extends MouseAdapter { public void mousePressed(MouseEvent me) { showStatus("Now Mouse is Pressed"); 1 ' } > Anonymous Inner Classes our code more concise. They enable you to ‘They are like local classes except that they lass only once. An anonymous ‘Anonymous classes enable you to make y declare and instantiate a class at the same time. do not have a name. Use them if you need to use a local inner class is one that is not assigned a name. 1/ Anonymous inner class demo. Import java.applet.*; import java.awtevent-"; p v public class TanonInnerClass extends Applet { public void init() { addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { showStatus(”Mouse Pressed”); 4 »; 1 } vor — ____ QUESTIONS Event & Event Handling? st als _ yhat one 3 parts of Delegation Event model? List and explain the event sources. 1 Explain Event Listeners & Event Class. Explain any five Event classes in detail. Write short note on Event Listener classes. Write short note on Adapter classes. Write short note on inner classes. Core java (5.¥.B.Se. UT) ~ Sem —1y, xe ABSTRACT WINDOW TOOLKIT 154 oes’ SYNOPSIS 12.1 What is GUI? 12.2 AWT 12.3 Window Fundamentals 12.3.1 Component 12.3.2 Container 123.3 Panel 123.4 Window 12.3.5 Frame 12.3.6 Canvas 12.4 Working with Frame Windows 12.5 Control Fundamentals 12.5.1 Labels 12.5.2 Buttons 12.5.3 Check Boxes & Checkbox Group 12.5.4 Choice Controls 12.55 Lists 12.5.6 Scroll Bars 12.5.7 TextField 12.5.8 TextArea Questions Fr rar anrect W 21 WHAT IS GUI? : medium provided by it is the a oa al days of computer we remember several of A GUL is @ graphical user interface to a compute' re for a human to interact with the computer. In initi eit ly through the console & using keyboard. We have to . interact 071 Vg, keyt aaa ivpmnand for interaction, The DOS OS is the example of console, keyboard ae ‘ample. The GUI provides us images, Buttons, colors for easy understanding & for *tymmand using keyboard & mouse both. advantages of GUIs 1. Iteasier to learn and use. 2. GUI provides immediate visual feedback to user of his every action. 3, With visual support, GUI simplifies the way to take advantage of multitasking facility of OS. 4. Because ease of use GUI is now used in almost every kind of software. 5, GUI gives more help to understand the use OS and its facilities even if user is new to computer. ‘java facilates JFC to us for developing GUI components”. JFC is short for Java foundation Classes, which include a group of features to help developer for building graphical user interfaces. 122 AWT fava’s Abstract Window Toolkit provides classes and other tools for buildin; P B programs that have a graphical user interface. © The term “Abstract” refers to the AWT's ability to run on multiple platforms. © Building a GUI involves creating “abstract” components such as buttons and Windows, which are then mapped to “concrete” components for a specific platform. java.awt is a standard package of Java. It is a GUI (Graphical User Interface) package, which has classes in it such as Frame, Panel, and Button. Most of the package was later replaced with the javax.swing package, which has most of the same classes, only with a J prepended to them (JFrame, JPanel, JButton). However the java.awt package still includes some event handlers that are considered standard in java (java.awtevent). AWT stands for Abstract Window Toolkit. The AWT is a code library that provides components for graphical user interfaces, eg, buttons, labels, textboxes. It was the first version of graphical components for Java. Programmers now use the next generation of components for user interfaces found in Swing. AWT (the Abstract Window Toolkit) is the part of Java classes, designed for creating User interfaces and painting graphics and images. It is a set of classes planned to provide Support for @ developer to create a graphical interface for any Java applet or Application, Most AWT components are derived from the java.awt.Component class, . Ar cee reer of Core Java (S.Y-B.Se. (L.) ~ Sem. ~ IY) 156 res [12.3_ WINDOW FUNDAMENTALS The AWT defines windows according to a class hierarchy that adds specificity with each level. 12.3.1 Component , A component is an object having a graphical representation that can be displayed on the screen and that can interact with the user. Examples of components are the buttons, checkboxes, and scrollbars of a typical graphical user interface. The Component class is the abstract super class of the non-menu related Abstract Window Toolkit components, Class Component can also be extended directly to create a lightweight component. A lightweight component is a component that is not associated with a native opaque window. 12.3.2 Container A generic Abstract Window Toolkit (AWT) container object is a component that can contain other AWT components. A container is a component which can contain other components inside itself. It is also an instance of a subclass of java.awt.Container so containers are themselves components. In general components are contained in a container. An applet is a-container. Other containers include windows, frames, dialogs, and panels, Containers may contain other containers. In short containers contain components. Components are positioned inside the container according to a LayoutManager. Object | | ‘Component = Panel Window | Ly ‘Applet functionality and Frame Dialog +] FileDialog 12.3.3 Panel Panel is the simplest container class. A panel provides space in which an application can attach any other component, including other panels. Panels play a very important role in layout management. Panels in combination with layout managers render the desired layout to the programmer. ‘As we can see from above the hierarchy, a panel is both a component and a container as it is a subclass of both Component and Container. As a component it can be added to another container and as a container it can be added with components, Panels work bot! _ways. It is known as child window. As a child window, it does not have a border. We ca" ‘also nest the Panels known as nested panels. . yy pent window Toolkit 22 a pot Window ‘the Window object is a top-level window with no borders and no pen me it layout for a window is BorderLayout. At indow is not contained within gefault lays yout. Atop-level windo' nat cae other object; it sits directly on the desktop. A window must have ei alos, another window defined as its owner when it's constructed. 35 Frame ‘A Frame is a top-level window with a title and a border. The. size of the mame igdudés any area designated for the border. The dimensions of the border area may be ed using the getinsets( ) method, however, since these dimensions are platform indent, a Valid insets value cannot be obtained until the frame is made displayable by sher calling pack or show. 1236 Canvas ‘A Canvas component represents.a blank rectangular area of the screen onto which. te application can draw or from which the application can trap input events from the use, An application must subclass the Canvas class in order to get useful functionality tach as creating a custom component, It designed for displaying simple graphics created ty constructing Lines, FilledOvals, FilledRects, or any of the other objectdraw classes that implement DrawableInterface. The paint method must be overridden in order to perform astom graphics on the canvas. [a4 WORKING WITH FRAME WINDOWS. The frame in java works like the main window where components (controls) are added to develop an application. In the Java AWT, top-level windows are represented by the Frame class. Java supports the look and feel and decoration for the frame. For creating java standalone application we must provide GUI to the user. The most common method of creating a frame is by using single argument constructor of the Frame-class. that contains the single string argument which is the title of the window or frame. There are two of Frame’s constructors : ® Frame() : This will create standard window without title. _ @ Frame(String title) : This will create standard window with ttle. There are several methods provided by the Frame class to work with them. _ The setSize( ) method is used to set the dimensions of the window. void setSize(int newWidth, int newHeight) void setSize(Dimension newSize) © After creating the frame we need to make it able for display. For that we have to use the setVisible( ) method. void setVisible(boolean visibleFlag) Bae component is visible if the argument to this method is true. Otherwise, it is © We can additionally set the title to windows using setTitle( ) method. void setTitle(String newTitle) ® After finishing the work we need to close the window. We can use windowClosing( ) method. oy Core jv (S.Y.B.Sc. 1.7) Sem. ry) ul ree Creating a Frame Window in an Applet Creating a new frame window using an applet is very easy: First, create 2 subclass of Frame. Next, override any of the standard applet methods, such as init( ), start(), ang stop( ), to show or hide the frame as needed. Finally, implement the windowClosing( ) method of ‘the WindowListenerinterface, calling setVisible(false) when the window js closed. Once we have defined a Frame subclass, we can create an object of that class, This causes a frame window to come into existence, but it will not be initially visible. We make it visible by calling setVisible( ). When created, the window is given @ default height ang width. We can set the size of the window explicitly by calling the setSize( ) method. Following program shows the simple Applet to create frame and handle the events, 1! To handle mouse events in both child and applet windows. import java.awt."; import java.awtevent.*; import java.applet.*; a _/ sapplet code="TWindowEvents" width=300 height-50> | serve // Create a subclass of Frame. class SampleFrame extends Frame implements MouseMotionListener { String msg ="; int X=10, Y=40; int movX=0, movY=0; SampleFrame(String title) { super(title); /[ register this object to receive its own mouse events addMouseMotionListener(this); // create an object to handle window events MyWindowAdapter adapter = new MyWindowAdapter(this); // register it to receive those events addWindowListener(adapter); } public void mouseDragged(MouseEvent me) { } // Handle mouse moved. public void mouseMoved(MouseEvent me) { J/ save coordinates movX = me.getX(); movY = me.getY(); Yr st Win Toi roo ” a repaint(0, 0, 100, 60); 1 public void paint(Graphics g) { g.drawString(msg, x, Y); gdrawString("Mouse at " + movX +", "+movy, 10, 40); 1 1 classMyWindow Adapter extends Window Adapter { SampleFramesample Frame; public MyWindow A dapter(SampleFramesampleFrame) { this sampleFrame = sampleFrame; } public void windowClosing(WindowEvent we) { sampleFrame.setVisible(false); } } // Applet window. Public class TWindowEvents extends Applet implements MouseMotionListener { . SampleFrame § String msg ="; int X=0, Y=: int movX=0, movY=0; J/ Create a frame window. Public void init() { f=new SampleFrame("T Mouse Events"); fsetSize(300, 200); fsetVisible(true); /I register this object to receive its own mouse events addMouseMotionListener(this); } /1 Remove frame window when stopping applet, Public void stop() { fsetVisible(false); } 4/ Show frame window when starting applet, Public void start() { fsetVisible(true); } / Handle mouse moved. vos Core Jaca (S.Y-B.Se.(LT-)~ Sem, 1) 160 public void mouseMoved(MouseEvent me) { I] save coordinates e-geX(); movY = me.getY(; repaint(0, 0, 100, 20); 1 public void mouseDragged(MouseEvent me) { } // Display msg in applet window. movX =m public void paint(Graphics g) { g.drawString(msg, X, Y); g-drawString("Mouse at " + movX +", "+ movY, 0, 10); } } OUTPUT LTC cece CLT ne eee SSR ‘Mouse at 14, 90 fouse at 202, 48 Applet started, 125 CONTROL FUNDAMENTALS Abstract Window Toolkit (AWT) package provides Several Controls through the classes. Controls are components that allow a user to interact with our application in various ways for example; a commonly used control is the push button. The AWT supports the following types of controls which are the subclass of Component : Labels Checkboxes [Lists | | Push buttons Choice lists | Scroll bars Text editing © To add the control to frame, first you have to create instance of the required control then we have to add it using add() method provided by Container class. Component add(Component compObj) © To remove the control from the frame we can use remove() method. void remove(Component obj) © We can remove all controls by calling removeAll). 12.5.1 Labels Label is the simple control to use. A label is an obj ject of type Label, and it contains a string, which it displays. Labels are passive controls that do not support any interaction with the user. eas | sn Wide Toit rrr yo Label defines the following constructors @ Label() throws HeadlessException : Create a blank Label. ¢ Label(String str) throws HeadlessException : Create a Label with string. fe Label(String. str, Alignments, ahods provided by Label Class @ void setText(String str): Assigns a new string to label. @ String getText( ): Reads the string From label. inthow) throws HeadlessException : Create a Label with ¢ void setAlignment(inthow) ; Sets the alignment as LEFT, RIGHT etc. to label control. @ int getAlignment( ): Reads the alignment of a label control. Note: “Use of Label Control you can see in the Layout Manager Examples.” 152 Buttons Ik very useful and most used control. A push button is a component that contains a uieland that generates an event when it is pressed. Push buttons are objects of type futton. Button defines these two constructors as follows : © Button() throws HeadlessException : Create the Empty button. ¢ Button(String str) throws HeadlessException : Create the button with name( label). Methods provided by Button Class © void setLabel(String str) : Sets Label of the button. © String getLabel( ) : Gets the Label of the button. As studied earlier in Event Handling button event is handled by actionPerformed(), stActionCommand( ), getActionCommand( ) methods. Simple Button Example import java.applet.Applet; import java.awt.Button; ti we public class TButton extends Applet( Public void init( ){ Button tButtonl = new Button(); ‘Button2.setLabel("TButton 1"); Button tButton2 = new Button("TButton 2"); add(tButton1); //add buttons using add method add(tButton2); } Core java (S.Y-B.Sc. (IT. ~ Sem.—1yy ie ree OUTPUT Cea le) Applet Feu Teuton 2 [Applet started, MUsing frame import java.awt.*; class Test extends Frame { Testa() { Button b=new Button("click me"); b.setBounds(30,100,80,30); add(b); setSize(300,300); setLayout(null); setVisible(true); 1 public static void main(String args{]) { TestA fnew TestA(); I t OUTPUT aunt wim Tt 7 - apesign 4 AWT program to print the factorial for an input value*/ import java.aw import java.awtevent.ActionEvent; import java.awtevent.ActionListener; import java.awt.event WindowListener; import java.awtevent: Window Adapter; import java.awt.event.WindowEvent; public class Pract25 extends Frame implements ActionListener { Label 11,12; TextField 1,12; Button b1,b2; public Pract25() { J/addWindowListener(this); t-new TextField(3); tQenew TextField(10); bi-new Button("Factorial"); b2-new Button("Clear"); I1=new Label("Enter Number 1=new Label("Result"); setLayout(new GridLayout(3,2)); add(tl); add(t1); add(12); add(t2); add(b1); add(b2); setSize(200,200); setVisible(true); bl.addActionListener(this); b2.add ActionListener(this); addWindowListener(new WindowAdapter()( public void windowClosing(WindowEvent we) ( System.exit(0); ) DM ¥.B.Se. 7.) ~ Sem, 164 en's’ Core joa public static void main(String! args) { new Pract25(); 1 public void actionPerformed(Actior { if(e.getSource()==b1) { int num fact,i;String result; fact=1; num-Integer.parselnt(tl.getText()); for(ie1;icenum;i++) { fact=fact*i; ! result=String-valueOf(fact); 12.setText(result); ) else { t1.setText(""); t2.setText(""); ) } ) OUTPUT 12.5.3 Check Boxes & Checkbox Group os ™ A check box is a control that is used when there are multiple options and multiple selections to turn an option on or off. It consists of a small box that can either contain @ check mark or not. indo Took oor 165 heck boxes are objects of the Checkbox class et Checkbox supports these constructors 1 : Create check box with blank label @ Checkbox( ) throws Headless th String, fe Checkbox(String str) throws HeadlessException : Create check box will label @ Checkbox(String, str, booleanon) throws HeadlessExxception : Create check box with String label with checked. or unchecked. @ Checkbox(String str, booleanon, —_ CheckboxGroupebGroup) HeadlessException : @ Checkbox(String str, CheckboxGroupcbGroup, _booleanon) _ throws HeadlessException : throws Both above constructors create a checkbox group with string, label. Checkbox class provides following methods : @ booleangetState( ) : Gives the state as Checked or unchecked © voidsetState(booleanon) : Sets the state as Checked or unchecked © String getLabel() : Reads the label of checkbox © voidsetLabel(String str) : Assigns the label to checkbox CheckboxGroup Itis possible to create a set of mutually exclusive check boxes in which one and only ene check box in the group can be checked at any one time. These check boxes are often dalled radio buttons. Check box groups are objects of type CheckboxGroup. Only the default constructor is defined, which creates an empty group. Methods © Checkbox getSelectedCheckbox( ) : Reads the selected radio button option from group © void setSelectedCheckbox(Checkbox which) : Selects radio button option of a group. Joint Example import java.applet.*; import java.awt."; r “apple i Public class TCBCBG extends Applet ( Checkbox morning, noon, evening; Public void init() { this.add(new Label("How will you pay for your pizza?")); CheckboxGroup cbg = new CheckboxGroup(); this.add(new Checkbox("Visa’, ebg, false)); this.add(new Checkbox("Cash", cbg, true)); // the default "BY-B Se. (1,)-Care Java (Sem -1V) Po 166 this.add(new | morning noon evening = new Checkbox("Evening'); 29's" ove (8 Bt (T)~ Sem = 1) abel("Select Time Slots for Delivery") *, null, true); new Checkbox("Mornin; new Checkbox("Afternoon"); this.add(morning); this.add(noon); this.add(evening); 12.5.4 Choice Controls ‘The Choice class provides drop down co! component takes up only enough space to show user clicks on it, the whole list of choices pops UP, Vy ue ‘Applet aj @ Cash afternoon I~ Evening How will you pay foryour pizza? Select Time Slots for Delivery Morning r JApplet started ion selection. Choice the currently selected item. When the and a new selection can be made. trol for the opti Choice class uses default constructor to create it Methods provided by Choice class are as follows = Note: void add(String name) : To add item in the list. String getSelecteditem( ) : Reading the selected item from the list. int getSelectedIndex( ) : Reading the selected item index number from the list. int getltemCount() : gives the number of items in the list. String getltem(int index) : Reads the item at given index. Example for Choice control is shown in Point 2.6” 12.55 Lists ‘The List class provides a compact, multiple-choice, scrolling selection list. We can select multiple options from the list. List provides these constructors : List( ) throws HeadlessException : Create a Normal list with only Single Selection Capability. List(int numRows) throws HeadlessException : Create a Normal list with only Single Selection Capability with specified number of rows. List(int numRows, Boolean multipleSelect) throws HeadlessException : Create a list with specified number of rows with unableing or disabling the mulitiple selection. | ure winds ToT ro0 mw Methods provided by the List class are as follows void add(String name) : To add item in the list, . @ void add(String name, int index) : To add item in the list at specified index. @ String getSelecteditem() : Reads the current selection from the list. @ int getSelectedIndex( ) : Gives the index nimber of current selection @ int getItemCount{ ) : Gives number of items present in the list. @ String getItem(int index) : Reads the item from the list at specified index simple List Example : import java.applet.Applet; import java.awtList; r v public class TList extends Applet{ public void init( ){ /[This list will have 5 visible rows List tList = new List(5); tList.add(’One"); tList.add("Two"); tList.add("Three"); tList.add("Four"); tList.add("Five"); tList.add("Six"); tList.add("Seven"); add(tList), _//adding a list } OUTPUT 1256 Scroll Bars When the contents of a window are 100 large to be displayed entirely within the Window, » seroll bar will appear. The scroll bar contains a slider that the user can click and drag to seroll through the window. It vertical bar on the right side of a window Fo 168 en's or a horizontal bar at the bottom of a window that is used to move th up and down or left and right. | The Scrollbar class defines following Constructors. © Scrollbar( ) throws HeadlessException. © Scrollbar(int style) throws HeadlessException. © Scrollbar(int style, int initialValue, int thumbSize, Core Java (5.Y B.Sc, (1) ~ Sem. ~ IV) e window contents int min, int max)throws HeadlessException. Methods of the Scrollbar class © void setValues(int initialValue, int thumbSize, int min, int max) int getValue( ) void setValue(int newValue) int getMinimum( ) int getMaximum( ) void setUnitincrement(int newIncr) void setBlockIncrement(int newIncr) Note : “Creating Scrollbar example you can see in the Border Layout Manager Example’ 12.5.7 TextField The TextField class implements a single-line text-entry area, control. TextFieldis a subclass of TextComponent. TextFielddefines the following constructors : © TextField() throws HeadlessException : Creates a default empty Text Field, © TextField(int numChars) throws HeadlessException : Creates Text Field with number of characters wide. © TextField(String stx) throws HeadlessException : Text Field with String © TextField(String str, int numChars) throws HeadlessException : Text Field with String and character width. Methods of TextField Class © String getText{ ) : To read the text from Text Field. voidsetText(String str) : To set the text to Text Field. String getSelectedText( ) : Reads only the selected text from the text field. void select(int startindex, int endIndex) : Reads the currently selected text. boolean isEditable( ) : Specify whether the text field is editable or not. © void setEditable(boolean canEdit) : Sets the text field editable. 12.5.8 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. usually called an edit Following are the constructors forTextArea : © TextArea( ) throws HeadlessException : Create Empty text area field. yy apn doe Toi ves @ TextArea(int numLines, int numChars) throws HeadlessExce] Empty text area field with number of displayable lines horizontally and characters vertically, 169 ption : Create no @ TextArea(String str) throws HeadlessException : Create text area field with specified string. @ TextArea(String str, int numLines, int numChars) throws HeadlessException sBars) throws @ TextArea(String str, int numLines, int numChars, int HeadlessException TextArea is a subclass of TextComponent. Therefore, it supports the getText( ), seiText( ), getSelectedText( ), select( ), isEditable( ), and setEditable( ) methods escribed in the Text Field section, qextArea adds the following methods : © void append(String str) : Appends the string specified by strto the end of the current text void insert(String str, int index): Inserts the string passed in strat the specified index. © voidreplaceRange(String str, int startindex, int endIndex) : Replaces the characters from startindex to endIndex-1, with the replacement text passed in str. Example for TextField and TextArea : import java.applet.*; import ava.awt.; import java.awtevent*; rt 7 public class TText extends Applet implements ActionListener { TextField write; TextArea copy; public TText() { * instantiation */ write = new TextField ("Write’, 20); copy = new TextArea ("Write above and Press Enter to copy Text 4,50); add (write); add (copy); copy.setBditable (false); write.addActionListener (this); | public void actionPerformed (ActionEvent e) ( copy.setText (write getText()); } } 170 OUTPUT Np PNAnER DY ano" ore jon (SY. B.S. (7) ~Sem. 19) [OPV M CCU! [Write above and Press Enter to copy Text QUESTIONS Explain GUI in Short. Brief information about AWT. Define Component, Container, Panel, Canvas, Window and Frame. How to create frame window in applet? Explain Label and Button Control With Example Write short note on CheckBox and CheckBoxGroup class. Explain Scrollbar With Example. Brief the use of Text and TextArea Classes. 2's nn LAYOUTS SYNOPSIS 13.1 Layout Manager 13.2 FlowLayout 13.3. BorderLayout 13.4 GridLayout 13.5 GridBagLayout 13.6 CardLayout Questions m oes Core eve SY BS (17) Sem.) 13.1 LAYOUT MANAGER Sometimes we want more control over how GUI components are placed on our programs. Layout managers are one way to do this. There are a few different layout managers we'll look at that let us specify how GUIs will look in different ways. Alternatives to layout managers include : © Using absolute positioning, i.e. specifying the exact position of each component, © Using tools that design GUIs and generate code for absolute positioning. 13.2 FLOWLAYOUT This is a default layout manager, which we've been using all along. Here, all GUL components are simply placed on the GUI from left to right in the order they're created, Components essentially act like characters in a word processing program and wrap to the next line when the right side of the GUT is reached. In our default formats, we haven't been naming the FlowLayout object, but we can do so as follows : private FlowLayout myLayout; For an example of how we'd proceed like this, our init( ) method for an applet would then look like this : public void init( ) { myLayout = new FlowLayout(); setLayout(myLayout); 1 One benefit of using named layout objects is the ability to change them based uy user actions or use different layouts for different panels within a program. Additionally, notice that all GUI components are aligned centered in a FlowLayoutby default. We « change this with the setAlignment( ) method. Valid alignments are. © FlowLayoutLEFT —~ © FlowLayout.CENTER_~ © FlowLayoutRIGHT.~ For example, we might use this line of code : layoutsetAlignment(FlowLayout. LEFT); Example: /*Program to demonstrate use of FlowLayout */ import java.applet.Applet; import java.awt.*; r wi public class TFlowLayout extends Applet a wow m3 poble void init() { setLayout(new FlowLayout(FlowLayout RIGHT)); //Aligning Right for (inti = 0; i< 4; i++) add(new Label("Tushar #" + i)); Tushar#0 Tushar#1 Tushar#2 Tushar #3 (33 BORDERLAYOUT | ‘The BorderLayout breaks the field up into five areas: north, south, east, west, and center, — ee —~ We can create a BorderLayout as follows : BorderLayout myLayout; layout = new BorderLayout(); setLayout(myLayout); Also, we could opt to specify gaps between components, e.g. myLayout = new BorderLayout(horizontalGap, verticalGap); | When we add components to a container with a BorderLayout, the add( ) method takes a second argument that tells in which area of the layout to place the component. If we omit this argument, the default is center. Here are the five options : © BorderLayoutNORTH BorderLayout SOUTH BorderLayout EAST BorderLayout WEST BorderLayout. CENTER For example, the following code adds a button to the north region : re add(button, BorderLayout NORTH); Example : Program to demonstrate use of BorderLayout */ import java.applet Applet; import java.awt."; plied code="TBorderLayout” width=500 height=50> a wen Core nya (S.¥.B Se, (T.)~ Sem. —1yy " public class TBorderLayout extends Applet | public void init() ( setl ayout (new BorderLayout()); Label b = new Label("This is SOUTH", Label. CENTER); b.setBackground(Color-yellow); Scrollbar sb1 = new Scrollbar(); Scrollbar sb2 = new Scrollbar(); add(b, BorderLayout SOUTH); add(sb1, BorderLayout.WEST); add(sb2, BorderLayout. EAST); This is SOUTH Applet started, 13.4 GRIDLAYOUT The GridLayout breaks the GUI up into rows and columns. We can declare a GridLayout as follows : sO 7 _ GridLayout myLayout; There are two constructors possible : myLayout = new GridLayout(Rows, Columns, horizontalGap, verticalGap); myLayout = new GridLayout(Rows, Columns); For example, the following code sets up a GridLayout with 4 rows and 4 columns : myLayout = new GridLayout(4, 4); setLayout(myLayout); When we add components to a container with a GridLayout, they're added to next open position in the current row. When a row is filled, components begin going to the next row. - Dont oes oe prample Program to demonstrate use of GridLayout */ import java.awt.*; import java.applet. Applet; r wi public class TGridBag extends Applet { protected void maketButton(tring name, GridBagLayoutmyGB, GridBagConstraints ¢) { - row 7 putton Button = new Button(name); myGB.setConstraints(tButton, ©); add(tButton); ' public void init( ) { GridBagLayoutmyGB = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); setFont(new Font("SansSerif’, Font-ITALIC, 15)); setLayout(myGB); fill = GridBagConstraints. BOTH; cweightx = 1.0; maketButton("Button1", myGB, ¢); maketButton("Button2", myGB, ¢); maketButton("Button3", myGB, c); cgridwidth = GridBagConstraints. REMAINDER; maketButton("Button4", myGB, ¢); cweightx = 0.0; Ihreset to the default maketButton("Buttons", myGB, ¢); //another row cgridwidth = GridBagConstraints. RELATIVE; //next-to-last in row maketButton("Button6", myGB, ¢); cgridwidth = GridBagConstraints. REMAINDER; //end row maketButton("Button?", myGB, c); cgridwidth = 1; /Ireset to the default cgridheight = 2; cweighty = maketButton("Button8", myGB, ©); cweighty = 0.0; Ifreset to the default cgridwidth = GridBagConstraints. REMAINDER; //end row J/reset to the default cgridheight = 1; maketButton("Button9", myGB, ); maketButton("Button10", myGB, c); setSize(300, 100); | Public static void main(String argsl!) Frame tFrame = new Frame("GridBag, Layout Example"); Y.B.Se. (LT) ~ Sem. 1) v8 wor Core java (8. iridBag(; TGridBagtix = new tEx.init(); tFrame.add(’Center’, tx); tFrame.pack() tFrame.setSize(tFrame.getPreferredSize()); tFrame.show(); Butfond Button8 Buttont0 Applet started. 113.6 CARDLAYOUT The CardLayout class is different among the other layout managers in that it stores several different layouts. Each layout can be thought of as being on a separate index card ina deck that can be shuffled so that any card is on top at a given time. This can be useful for user interfaces with optional components that can be dynamically enabled and disabled upon user input. We can prepare the other layouts and have them hidden, ready to be activated when needed. CardLayout provides these two constructors : CardLayout( ) CardLayout(inthorz, intvert) Methods defined by CardLayout : void first(Container deck) void last(Container deck) void next(Container deck) void previous(Container deck) void show(Container deck, StringcardName) rr Daye roe _ ” QUESTIONS J Write short note on FlowLayout management. Write short program to demonstrate use of FlowLayout management. Write short note on BorderLayout management. Write short program to demonstrate use of BorderLayout management. Write short note on GridLayout management. Write short program to demonstrate use of GridLayout management. Write short note on GridBagLayout management. Write short program to demonstrate use of GridBagLayout management. Write short note on CardLayout management. CP ART e pe rer

You might also like