Professional Documents
Culture Documents
SN Java Unit 4
SN Java Unit 4
Java AWT (Abstract Window Toolkit) is an API(Application Programming Interface) to develop GUI or window-based applications in java.
AWT CLASSES :
The java.awt package provides classes for AWT api such as TextField, Label,TextArea,RadioButton, CheckBox, Choice, List etc.
Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes that extends
Container class are known as container such as Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other components like button, textfield etc.
Education4Fun.com
Graphical User Interface
Graphical User Interface (GUI) offers user interaction via some graphical components. For example our underlying
Operating System also offers GUI via window,frame,Panel, Button, Textfield, TextArea, Listbox, Combobox, Label,
Checkbox etc.
GUI makes the application more entertaining and interesting on the other hand CUI does not.
GUI offers click and execute environment while in CUI every time we have to enter the command for a task.
The AWT supports a rich assortment of graphics methods.All graphics are drawn relative to window.This can be a main window of an applet,a
child window of an applet ,or stand alone application of window.The origin of each window is at the top-left corner and is 0,0.
A graphics context is encapsulated by the Graphics class and is obtained in two ways:
Example :
import java.applet.Applet;
import java.awt.*;
setBackground(Color.black);
Education4Fun.com
g.setColor(Color.green);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
OUTPUT:
EVENT HANDLING
EVENT :
Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as result of user
interaction with the graphical user interface components.
Types of Event
Foreground Events - Those events which require the direct interaction of user. For example, clicking on a button, moving the mouse,
entering a character through keyboard,selecting an item from list, scrolling the page etc.
Background Events - Those events that require the interaction of end user are known as background events. Operating system
interrupts, hardware or software failure, timer expires, an operation completion are the example of background events.
Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism have the code
which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events.
Education4Fun.com
TWO EVENT HANDLING MECHANISMS:
The working of an event-driven program is governed by its underlying event-handling model. Till now two models have been introduced in Java
for receiving and processing events.They are :
The Java 1.0 Event model for event processing was based on the concept of containment. In this approach, when a user-initiated event is
generated it is first sent to the component in which the event has occurred. But in case the event is not handled at this component, it is
automatically propagated to the container of that component. This process is continued until the event is processed or it reaches the root of the
containment hierarchy.
The advanced versions of Java ruled out the limitations of Java 1.0 event model. This model defines the standard mechanism to generate and
handle the events. The Delegation Event Model has the following key participants namely Source and Listener.
A source generates an event and sends it to one or more listeners. On receiving the event, listener processes the event and returns it.
• Event source: An event source is an object that generates a particular kind of event. An event is generated when the internal state of
the event source is changed. A source may generate more than one type of event. Every source must register a list of listeners that are interested
to receive the notifications regarding the type of event. Event source provides methods to add or remove listeners.
Education4Fun.com
• Event listener: An event listener is an object which receives notification when an es about specific types of events. The role of
event listener is to receive these notifications and process them.
For example, as shown in Figure, when the mouse is clicked on Button, an event is generated. If the Button has a registered listener
to handle the event, this event is sent to Button, processed and the output is returned to the user. However, if it has no registered
Example program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
String msg="";
addKeyListener(this);
showStatus("KeyPressed");
Education4Fun.com
showStatus("KeyRealesed");
msg = msg+k.getKeyChar();
repaint();
EVENT CLASSES:
The Event classes represent the event. Java provides us various Event classes
ActionEvent generated when button is pressed, menu-item is selected, list-item is double clicked ActionListener
MouseEvent generated when mouse is dragged, moved,clicked,pressed or released and also MouseListener
when it enters or exit a component
WindowEvent generated when window is activated, deactivated, deiconified, iconified, opened or WindowListener
closed
ComponentEvent generated when component is hidden, moved, resized or set visible ComponentEventListener
Education4Fun.com
SOURCES OF EVENTS:
EventListener Interfaces
An event listener registers with an event source to receive notifications about the events of a particular type.
Various event listener interfaces defined in the java.awt.event package are given below :
Interface Description
Defines the actionPerformed() method
ActionListener
to receive and process action events.
Defines five methods to receive mouse
events, such as when a mouse is
MouseListener
clicked, pressed, released, enters, or
exits a component
Defines two methods to receive
MouseMotionListener events, such as when a mouse is
dragged or moved.
Defines the adjustmentValueChanged()
AdjustmentListner method to receive and process the
adjustment events.
Defines the textValueChanged()
TextListener method to receive and process an event when the text
value changes.
Defines seven window methods to
WindowListener
receive events.
Defines the itemStateChanged()
ItemListener method when an item has been
selected or deselected by the user.
Education4Fun.com
AWT CONTROL FUNDAMENTALS :
1 Label
2 Button
3 Check Box
5 List
The List component presents the user with a scrolling list of text
items.
6 Text Field
7 Text Area
8 Choice
Education4Fun.com
A Choice control is used to show pop up menu of choices. Selected
choice is shown on the top of the menu.
9 Canvas
10 Image
11 Scroll Bar
12 Dialog
13 File Dialog
In order to include a control in a window, we must add it to the window. So, 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.Mostly used form is :
Component add(Component compObj)
Here, compObj is an instance of the control that we want to add.
Sometimes we will want to remove a control from a window when the control is no longer needed. For doing 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 that we want to remove. We can remove all controls by calling removeAll( ).
Responding to Controls
Except for labels, which are passive controls, all controls generate events when they are accessed by the user. For example, when the user clicks
on a push button, an event is sent that identifies the push button. In general, our program simply implements the appropriate interface and then
registers an event listener for each control that we need to monitor.
Education4Fun.com
JAVA AWT LABEL
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:
1 Label()
2 Label(String text)
Output:
Education4Fun.com
Java AWT Button
The button class is used to create a labeled button that has platform independent implementation. The application result in some
action when the button is pushed.
Output:
Education4Fun.com
Java AWT Checkbox Example
1. import java.awt.*;
2. public class CheckboxExample
3. {
4. CheckboxExample(){
5. Frame f= new Frame("Checkbox Example");
6. Checkbox checkbox1 = new Checkbox("C++");
7. checkbox1.setBounds(100,100, 50,50);
8. Checkbox checkbox2 = new Checkbox("Java", true);
9. checkbox2.setBounds(100,150, 50,50);
10. f.add(checkbox1);
11. f.add(checkbox2);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. }
16. public static void main(String args[])
17. {
18. new CheckboxExample();
19. }
20. }
Output:
Education4Fun.com
15. f.setVisible(true);
16. }
17. public static void main(String args[])
18. {
19. new CheckboxGroupExample();
20. }
21. }
Output:
Output:
Education4Fun.com
Java AWT List
The object of List class represents a list of text items. By the help of list, user can choose either one item or multiple items. It
inherits Component class.
Output:
Education4Fun.com
AWT Scrollbar class declaration
1. public class Scrollbar extends Component implements Adjustable, Accessible
Output:
Education4Fun.com
Java AWT TextArea
The object of a TextArea class is a multi line region that displays text. It allows the editing of multiple line text. It inherits
TextComponent class.
Output:
Education4Fun.com
The object of Menu class is a pull down menu component which is displayed on the menu bar. It inherits the MenuItem class.
Output:
Education4Fun.com
Java AWT Dialog
The Dialog control represents a top level window with a border and a title used to take some form of input from the user. It
inherits the Window class.
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons but Dialog doesn't have.
Output:
Education4Fun.com
Class declaration
Following is the declaration for java.awt.FileDialog class:
SampleFrame(String title)
super(title);
class FileDialogDemo
f.setVisible(true);
f.setSize(100, 100);
fd.setVisible(true);
OUTPUT:
Education4Fun.com
AWT Layouts
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is implemented
by all the classes of layout managers. There are following classes that represents the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Following is the list of commonly used controls while designed GUI using
AWT.
1 BorderLayout
The borderlayout arranges the components to fit in the five regions: east, west, north, south
and center.
2 CardLayout
The CardLayout object treats each component in the container as a card. Only one card is
visible at a time.
3 FlowLayout
The FlowLayout is the default layout.It layouts the components in a directional flow.
4 GridLayout
5 GridBagLayout
This is the most flexible layout manager class.The object of GridBagLayout aligns the
component vertically,horizontally or along their baseline without requiring the components of
same size.
EXAMPLE:
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border {
Education4Fun.com
5. JFrame f;
6. Border(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("NORTH");;
10. JButton b2=new JButton("SOUTH");;
11. JButton b3=new JButton("EAST");;
12. JButton b4=new JButton("WEST");;
13. JButton b5=new JButton("CENTER");;
14.
15. f.add(b1,BorderLayout.NORTH);
16. f.add(b2,BorderLayout.SOUTH);
17. f.add(b3,BorderLayout.EAST);
18. f.add(b4,BorderLayout.WEST);
19. f.add(b5,BorderLayout.CENTER);
20.
21. f.setSize(300,300);
22. f.setVisible(true);
23. }
24. public static void main(String[] args) {
25. new Border();
26. }
27. }
OUTPUT:
Java also allows us to handle events by subclassing AWT components. In order to extend an AWT component, we must call the enableEvents( )
method of Component. Its general form is shown here:
The eventMask argument is a bit mask that defines the events to be delivered to this component. The AWTEvent class defines int constants for
making this mask. Several are shown here:
ACTION_EVENT_MASK
KEY_EVENT_MASK
ADJUSTMENT_EVENT_MASK
MOUSE_EVENT_MASK
COMPONENT_EVENT_MASK
MOUSE_MOTION_EVENT_MASK
CONTAINER_EVENT_MASK
MOUSE_WHEEL_EVENT_MASK
FOCUS_EVENT_MASK
TEXT_EVENT_MASK
INPUT_METHOD_EVENT_MASK
WINDOW_EVENT_MASK
ITEM_EVENT_MASK
Education4Fun.com
We must also override the appropriate method from one of our superclasses in order to process the event. Methods listed below most commonly
used and the classes that provide them.
Output:
Education4Fun.com
16. setVisible(true);
17. }
18. public void actionPerformed(ActionEvent e) {
19. try{
20. String host=tf.getText();
21. String ip=java.net.InetAddress.getByName(host).getHostAddress();
22. l.setText("IP of "+host+" is: "+ip);
23. }catch(Exception ex){System.out.println(ex);}
24. }
25. public static void main(String[] args) {
26. new LabelExample();
27. }
28. }
Output:
Education4Fun.com
Education4Fun.com