Sei sulla pagina 1di 36

Event and GUI Programming

Event Handling in JAVA

User Performs an action, such as, moving the mouse, pressing a key, releasing the key and so on. All these operations generate an event. Events are triggered either by external user actions, such as mouse movements,button clicks or by internal program activities, such as timer. The component on which an event is fired or generated is called the source object or source component. For e.g a button is source object for a button-clicking action event. Various event classes are there, the root class of the event classes is java.util.EventObject

Event Class
ActionEvent

Description
When a button is pressed , a list item is double clicked or a menu is selected When a Scrollbar is used. When a component is resized,moved, hidden or made visible When component gains or loses focus Component added or removed from container When a checkbox or radio button is clicked When a window is activated,closed,opened or quit

AdjustmentEvent ComponentEvent

FocusEvent ContainerEvent ItemEvent WindowEvent

TextEvent
MouseEvent KeyEvent

When the value of a text field or text area is changed


When mouse is moved,clicked,dragged or released When input is received from the keyboard

Java uses a delegation based model for event handling. A source object fires an event An object interested in the event handles the event The object that handles the event is called listener. Two things are needed for an object to be a listener 1) a listener must be an instance of a listener interface 2) a listener must be registered with source component e.g Button btn = new Button(New); ActionListener listener1 = new ActionListener(); btn.addActionlistener(listener1); The listener interface is usually named XListener for XEvent . One exception is there - MouseMotionListener

Event class ActionEvent ItemEvent MouseEvent

Listener Interface ActionListener ItemListener MouseListener

Listener Methods actionPerformed(ActionEvent) itemStateChanged(ItemEvent) mousePressed(MouseEvent) mouseReleased(MouseEvent) mouseEntered(MouseEvent) mouseExited(MouseEvent) mouseClicked(MouseEvent) mouseDragged(MouseEvent) mouseMoved(MouseEvent) keyPressed(KeyEvent) keyReleased(KeyEvent) keyTyped(KeyEvent)

MouseMotionListener

KeyEvent

KeyListener

EventClass WindowEvent

Listener Interface WindowListener

Listener Methods windowClosing(WindowEvent) windowOpened(WindowEvent) windowIconified(WindowEvent) windowDeiconified(WindowEvent) windowClosed(WindowEvent) windowActivated(WindowEvent) windowDeactivated(WindowEvent) componentAdded(ContainerEvent) componentRemoved(ContainerEvent) focusGained(FocusEvent) focusLost(FocusEvent)

ContainerEvent

ContainerListener

FocusEvent

FocusListener

AdjustmentEvent AdjustmentListener adjustmentValueChanged(AdjustmentEvent)

Event Class ComponentEvent

Listener Interface ComponentListener

Listener Methods componentMoved(ComponentEvent) componentHidden(Componentevent) componentResized(ComponentEvent) componentShown(ComponentEvent)

Inner Class Listeners An inner class or nested class, is a class defined within scope of another class. public class Test { } public class A { } Inner Class public class Test { public class A { } }

A simple use of inner classes is to combine dependent classes into a primary class. This reduces the number of source files. It also makes class files easy to organize ,since all the class files are named with the primary class as the prefix. For e.g , rather than creating two source files, Test.java and A.java in previous example , we can combine class A into class Test and create just one source file Test.java The resulting class files are Test.class and Test$A.class

Anonymous Inner Classes An anonymous inner class is an inner class without a name. It combines declaring an inner class and creating an instance of the class in one step. Syntax:
new SuperClassName { } E.G public class anonymousinnerclass { Button btn = new Button(New); btn.addActionlistener(new ActionListener () { public void actionPerformed(ActionEvent e) { s.o.p(Process new); } } ); }

Adapter Classes Java provides a special features , called an adapter class, that can simplify the creation of event handlers in certain situations. This classes are useful when we want to receive and process only some of the events that are handled by a particular event listener interface. A listener adapter is named XAdapter for Xlistener. E.g MouseMotionAdapter class has two methods, mouseDragged() and mouseMoved()

If we are interested in only mouse drag events, then we could simply extend MouseMotionAdapter and implement mouseDragged().

Commonly used Listener Interfaces Implemented by Adapter Classes. Adapter Class Component Adapter ContainerAdapter FocusAdapter KeyAdapter MouseAdapter MouseMotionAdapter WindowAdapter Listener Interface ComponentListener ContainerListener FocusListener KeyListener MouseListener MouseMotionListener WindowListener

Applet and its Life Cycle


An applet is a Java Program that runs with the help of a Web Browser. All applets are subclasses of the class Applet. It belongs to the package java.applet To create an applet, the following two packages must be imported: java.applet java.awt Life Cycle Applets are created in well defined cycle. An applet defines its structure from four events that take place during the execution. For each event a method is automatically called. The methods are as follows:

init() The method called during initialisation is known as init() method. This method is used to create objects,initialise variables and load graphics. start() Once the initialisation process is complete, the applet is started. The start() method is called, when the applet is started. This method is used to restart the applet after it has stopped. stop() The stop() method comes in picture when the execution of an applet has to be paused. An applet should be stopped before it is destroyed. destroy() An applet is detroyed using the destroy() method.

In addition to this there is paint() method, which is used to display a line, text or an image on the screen. It takes an argument of the class Graphics This class is part of java.awt package only. drawstring() method is used to display the output. An applet is compiled using the syntax: java Applet1.java To execute an applet, create an HTML file. This HTML file uses the applet tag. <applet code = Applet1 width = 200 height = 200> </applet> Now execute using the following command: appletviewer abc.html

Another option is to include the applet tag as part of the code comment. The applet is compiled and then executed using the following command: appletviewer Applet1.java

Difference Between an Application and an Applet Applications run using the Java Interpreter, while applets un on any browser. Execution of applications begins with the main() method, while the execution of applets does not begin with the main() method. Applications use the System.out.println() to display the output, while applets use the drawstring() method to display the output.

Example
import java.awt.*; import java.applet.*; /* <applet code = Applet1 width = 200 height = 200> </applet> */ public class Applet1 extends Applet { int num; public void init() { num=11; } public void paint(Graphics g) { g.drawString(Hello to Applets. Session +num, 70, 80); } }

Applet Viewer : Applet1

Hello to Applets. Session 11

GUI Components
The concept of a Graphical User Interface is used to create a pictorial interface that is easy to work with. This is achieved by creating GUI components. A GUI component is a visual object with which user interacts through mouse or a keyboard. They are present in class Component in package java.awt

Label
A Label is used to display a string which cannot be edited. It is declared as follows: Label labelname; The constructor of a label : labelname = new Label(Enter Your Name); The label will be visible only if it is added to the container. This is done using add() method; Container.add(labelname);

TextField
A TextField is a single line area, in which text can be displayed or can be entered by the user. It is declared and initialised as: TextField tf = new TextField(Core Java); To prevent the user from editing the text,following method is used: tf.setEditable(false);

TextArea
This class provides an area where multiple text lines are visible and can be manipulated. It is declared and initialised as follows: TextArea ta = new TextArea(core java);

Button
A Button is a component that triggers a specific action when clicked. The text used to describe a button is known as label of the buton. It can be declared as follows: Button btn; To change the caption of a button btn.setLabel(Press me);

CheckBox
A Checkbox is a toggle box can be selected or deselected. There is always a line of text present next to the checkbox which specifies the significance of the box. It can be declared as follows: Checkbox cbl = new CheckBox(Core Java); add(cb1);

Radio Button
A radio button is a collection of checkboxes grouped together. To group the checkboxes together, the class CheckboxGroup is used. It can be declared as follows: CheckboGroup cbg; Checkboxes have to be added to the Checkboxgroup, so that radio buttons are created.

Checkbox ck1,ck2,ck3; To add these check boxes to the check box group: ck1.setCheckboxGroup(cbg); ck2.setCheckboxGroup(cbg); ck3.setCheckboxGroup(cbg);

The difference between checkboxes and radio buttons is that, checkboxes are used for multiple selections, whereas radio buttons are used only for single selections.

List
A List is a collection of items from which the user can select one or more than one items. To declare and initialise a list object: List mylist = new List(3, true); The first parameter indicates how many items will be displayed in the scrolling window and the second parameter indicates whether multiple items can be selected.

mylist.addItem(First); mylist.addItem(Second); To coun the number of items in alist, the syntax used is: mylist.countItem();

Combo Boxes
It is also known as choice list or drop-down list. It provides a list of items from which an item can be selected by the user. It can be created as follows: ComboBox cbobj = new ComboBox(); cbobj.addItem(Item 1); cbobj.addItem(Item 2);

ScrollBar
It creates a slider that can be used to set a numeric value. A ScrollBar object is created with following syntax: ScrollBar sbar; sbar = new ScrollBar(ScrollBar.HORIZONTAL,60,600,0,1200); The first parameter indicates the orientation HORIZONTAL or VERTICAL. The initial value is set by the second parameter. The third parameter contains the number of elements in the scroll bar The range of values for the scroll bar are 0 to 1200.

Sliders
It is same as scrollbar but has more properties and can appear in many forms. Slider s = new Slider(Slider.HORIZONTAL);

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. This can be implemented in java by following: MenuBar, Menu and MenuItem MenuBar contains one or more Menu objects. Each menu object contains a list of MenuItem Objects. MenuItem object represents something that can be selected by the user.
Example: MenuBar mbar = new Menu(); setMenuBar(mbar);

Menu file = new Menu(File); MenuItem item1 = new MenuItem(New..); file.add(item1); mbar.add(file);

Containers
Containers are components that hold other components such as button,textfield etc. The container components are: Applet Frame Panel Dialog We have already seen the applet.

Frame A Frame is an independent window. Frames are used with applications which requires GUI. When a frame is constructed, it does not have a size and is not visible. We have to set both. Frame f = new Frame(MyFrame); f.setSize(400,300); f.setVisible(true); //Components are added like this Button btn = new Button(OK); f.add(btn);

Panel
A Panel is an invisible container for components. A number of components can be placed by using panels. E.g
Suppose we want add ten buttons and a textfield in a frame. The buttons are placed in grid formation,but the textfield is placed on separate row. It is difficult to achieve the desired look by placing all the components in single container. So we can divide a window in panels.Panels act as subconatiners to group components. Add the buttons in one panel,and then add the panel into the frame.

Panel pan = new Panel(); Button btn1 = new Button(Open); Button btn2 = new Button(Exit); pan.add(btn1); pan.add(btn2);

Example import java.awt.*; import java.applet.*; /* <applet code = MyFrame width = 200 height = 200> </applet> */ public class MyFrame extends Applet { Frame myf; Panel pan; Button btnclose; TextField tf; public void init() { myf = new Frame(Title of frame); pan = new Panel(); tf = new TextField(Enter more text);

btnclose = new Button(Close); pan.add(tf); pan.add(btnclose); myf.add(pan); myf.setSize(200,200); myf.setVisible(true); } } o/p Title of frame

Enter more text Close

Dialog
The class Dialog is like the class Frame, except that dailog boxes are always child windows of a top level window. Dialog box dont have menu bars. Dialog boxes may be modal or modeless. When a modal dialog box is active, all input is directed to it until it is closed. This means that we cannot access other parts of the program until we have closed the dialog box. When a modeless dialog box is active, input focus can be directed to another window in the program. Thus other parts of the program remain active and accessible. Example Frame myframe = new Frame(My frame); String title = Title; boolean modal = true; Dialog dlg = new Dialog(myframe, title, modal);

Layout Managers
The layout manager provides a means for controlling the physical layout of GUI elements. A layout manager automatically positions GUI components within a container. The different types of layouts are as follows: Flow Layout Border Layout Grid Layout

Flow Layout Manager It is the default layout manager for applets and panels. The components are arranged from the upper left corner to the right bottom corner. When there are a number of components, they are arranged row wise and left to right. //contructor FlowLayout mylayout = new FlowLayout(); //constructor with alignment specified FlowLayout exlayout = new FlowLayout(FlowLayout.RIGHT);

The layout manager is set with method called setLayout().


setLayout(exLayout);

Border Layout Manager It is the default layout manager for window, Frame and Dialog. This layout arranges upto five components in a container. These components can be assigned to North,South,East,West and Center of the container. To add a component to the North region, the syntax is as follows:
Button b1 = new Button(North Button); setLayout(new BorderLayout()); add(b1,BorderLayout.NORTH);

The border layout can contain more than five components. To achieve this, we can use panels of various layouts to contain components and then place those panels in the border layout.
Panel pan = new Panel(); pan.add(btn1); pan.add(chk1); add(pan,BorderLayout.NORTH);

Grid Layout Manager This layout helps us to divide the conatiner into a grid. The components are placed in rows and columns. A grid is used when all the components are of same size. GridLayout g1 = new GridLayout(4,3) where 4 is the number of rows and 3 is the number of columns. Example
import java.applet.*; import java.awt.*; public class Grid extends Applet { public void init() { setLayout (new GridLayout(5, 3)); // 5 rows, 3 columns, no gaps for (int row = 0; row < 5; row ++) { add (new Label("Label " + row)); add (new Button("Button " + row)); add (new TextField("TextField " + row)); } } }

Potrebbero piacerti anche