11 Abstract Window Toolkit — Java Programming
11.1 Introduction
Java’s big trump card is its Abstract window toolkit (AWT). It is an object oriented graphical user Interface(GUI) framework that allows you to design modern, accessible, graphical application interface. But Java’s AWT lets you design and implement GUIs that run unmodified on PC’s running any OS.
11.2 AWT
AWT has the flexibility that we can easily interface that appears the same on all platforms. The concept of Swing is also introduced. As of now Swing has taken over. JavaFX is also getting popular
11.3 AWT Package
The AWT classes are contained in the java.awt package which is Java’s largest packages. It is hierarchical and is easy to understand and use.
11.3.1 AWT Components
java.awt contains classes for creating user interfaces and for painting graphics and images. Any object on user interface like text box, label or button are called components which cause an event when a user interacts. For example when a mouse is clicked or when a button is pressed. The AWTEvent class and its subclasses are used to handle such events. The Component class is the root of all AWT components.
11.3.2 AWT container
A container is a component that can contain components and other containers. A container can also have a layout manager that controls the visual placement of components in the container. The AWT package contains several layout manager classes and an interface for building our own layout manager.
11.4 Hierarchy For Package java.awt.event
11.4.1 Class Hierarchy
- java.lang.Object
- java.awt.event.ComponentAdapter(implements java.awt.event.ComponentListener)
- java.awt.event.ContainerAdapter(implements java.awt.event.ContainerListener)
- java.util.EventListenerProxy<T> (implements java.util.EventListener)
- java.awt.event.AWTEventListenerProxy(implements java.awt.event.AWTEventListener)
- java.util.EventObject(implements java.io.Serializable)
- java.awt.AWTEvent
- java.awt.event.ActionEvent
- java.awt.event.AdjustmentEvent
- java.awt.event.ComponentEvent
- java.awt.event.ContainerEvent
- java.awt.event.FocusEvent
- java.awt.event.InputEvent
- java.awt.event.KeyEvent
- java.awt.event.MouseEvent
- java.awt.event.MouseWheelEvent
- java.awt.event.PaintEvent
- java.awt.event.WindowEvent
- java.awt.event.HierarchyEvent
- java.awt.event.InputMethodEvent
- java.awt.event.InvocationEvent(implements java.awt.ActiveEvent)
- java.awt.event.ItemEvent
- java.awt.event.TextEvent
- java.awt.AWTEvent
- java.awt.event.FocusAdapter(implements java.awt.event.FocusListener)
- java.awt.event.HierarchyBoundsAdapter(implements java.awt.event.HierarchyBoundsListener)
- java.awt.event.KeyAdapter(implements java.awt.event.KeyListener)
- java.awt.event.MouseAdapter(implements java.awt.event.MouseListener, java.awt.event.MouseMotionListener, java.awt.event.MouseWheelListener)
- java.awt.event.MouseMotionAdapter(implements java.awt.event.MouseMotionListener)
- java.awt.event.WindowAdapter(implements java.awt.event.WindowFocusListener, java.awt.event.WindowListener, java.awt.event.WindowStateListener)
11.4.2 Description of classes in AWT
Here is the summary of classes used in AWT. [11.3]
| Class | Description |
|---|---|
| AlphaComposite |
The
AlphaComposite class implements basic alpha compositing rules for combining source and destination colors to achieve blending and transparency effects with graphics and images. |
| AWTEvent |
The root event class for all AWT events.
|
| AWTEventMulticaster |
AWTEventMulticaster implements efficient and thread-safe multi-cast event dispatching for the AWT events defined in thejava.awt.event package. |
| AWTKeyStroke |
An
AWTKeyStroke represents a key action on the keyboard, or equivalent input device. |
| AWTPermission |
This class is for AWT permissions.
|
| BasicStroke |
The
BasicStroke class defines a basic set of rendering attributes for the outlines of graphics primitives, which are rendered with aGraphics2D object that has its Stroke attribute set to thisBasicStroke . |
| BorderLayout |
A border layout lays out a container, arranging and resizing its components to fit in five regions: north, south, east, west, and center.
|
| BufferCapabilities |
Capabilities and properties of buffers.
|
| BufferCapabilities.FlipContents |
A type-safe enumeration of the possible back buffer contents after page-flipping
|
| Button |
This class creates a labeled button.
|
| Canvas |
A
Canvas component represents a blank rectangular area of the screen onto which the application can draw or from which the application can trap input events from the user. |
| CardLayout |
A
CardLayout object is a layout manager for a container. |
| Checkbox |
A check box is a graphical component that can be in either an “on” (
true ) or “off” (false ) state. |
| CheckboxGroup |
The
CheckboxGroup class is used to group together a set ofCheckbox buttons. |
| CheckboxMenuItem |
This class represents a check box that can be included in a menu.
|
| Choice |
The
Choice class presents a pop-up menu of choices. |
| Color |
The
Color class is used to encapsulate colors in the default sRGB color space or colors in arbitrary color spaces identified by aColorSpace . |
| Component |
Acomponentis an object having a graphical representation that can be displayed on the screen and that can interact with the user.
|
| ComponentOrientation |
The ComponentOrientation class encapsulates the language-sensitive orientation that is to be used to order the elements of a component or of text.
|
| Container |
A generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT components.
|
| ContainerOrderFocusTraversalPolicy |
A FocusTraversalPolicy that determines traversal order based on the order of child Components in a Container.
|
| Cursor |
A class to encapsulate the bitmap representation of the mouse cursor.
|
| DefaultFocusTraversalPolicy |
A FocusTraversalPolicy that determines traversal order based on the order of child Components in a Container.
|
| DefaultKeyboardFocusManager |
The default KeyboardFocusManager for AWT applications.
|
| Desktop |
The
Desktop class allows interact with various desktop capabilities. |
| Dialog |
A Dialog is a top-level window with a title and a border that is typically used to take some form of input from the user.
|
| Dimension |
The
Dimension class encapsulates the width and height of a component (in integer precision) in a single object. |
| DisplayMode |
The
DisplayMode class encapsulates the bit depth, height, width, and refresh rate of aGraphicsDevice . |
| Event | Deprecated.
It is recommended that
AWTEvent and its subclasses be used instead |
| EventQueue |
EventQueue is a platform-independent class that queues events, both from the underlying peer classes and from trusted application classes. |
| FileDialog |
The
FileDialog class displays a dialog window from which the user can select a file. |
| FlowLayout |
A flow layout arranges components in a directional flow, much like lines of text in a paragraph.
|
| FocusTraversalPolicy |
A FocusTraversalPolicy defines the order in which Components with a particular focus cycle root are traversed.
|
| Font |
The
Font class represents fonts, which are used to render text in a visible way. |
| FontMetrics |
The
FontMetrics class defines a font metrics object, which encapsulates information about the rendering of a particular font on a particular screen. |
| Frame |
A
Frame is a top-level window with a title and a border. |
| GradientPaint |
The
GradientPaint class provides a way to fill aShape with a linear color gradient pattern. |
| Graphics |
The
Graphics class is the abstract base class for all graphics contexts that allow an application to draw onto components that are realized on various devices, as well as onto off-screen images. |
| Graphics2D |
This
Graphics2D class extends theGraphics class to provide more sophisticated control over geometry, coordinate transformations, color management, and text layout. |
| GraphicsConfigTemplate |
The
GraphicsConfigTemplate class is used to obtain a validGraphicsConfiguration . |
| GraphicsConfiguration |
The
GraphicsConfiguration class describes the characteristics of a graphics destination such as a printer or monitor. |
| GraphicsDevice |
The
GraphicsDevice class describes the graphics devices that might be available in a particular graphics environment. |
| GraphicsEnvironment |
The
GraphicsEnvironment class describes the collection ofGraphicsDevice objects andFont objects available to a Java(tm) application on a particular platform. |
| GridBagConstraints |
The
GridBagConstraints class specifies constraints for components that are laid out using theGridBagLayout class. |
| GridBagLayout |
The
GridBagLayout class is a flexible layout manager that aligns components vertically, horizontally or along their baseline without requiring that the components be of the same size. |
| GridBagLayoutInfo |
The
GridBagLayoutInfo is an utility class forGridBagLayout layout manager. |
| GridLayout |
The
GridLayout class is a layout manager that lays out a container’s components in a rectangular grid. |
| Image |
The abstract class
Image is the superclass of all classes that represent graphical images. |
| ImageCapabilities |
Capabilities and properties of images.
|
| Insets |
An
Insets object is a representation of the borders of a container. |
| JobAttributes |
A set of attributes which control a print job.
|
| JobAttributes.DefaultSelectionType |
A type-safe enumeration of possible default selection states.
|
| JobAttributes.DestinationType |
A type-safe enumeration of possible job destinations.
|
| JobAttributes.DialogType |
A type-safe enumeration of possible dialogs to display to the user.
|
| JobAttributes.MultipleDocumentHandlingType |
A type-safe enumeration of possible multiple copy handling states.
|
| JobAttributes.SidesType |
A type-safe enumeration of possible multi-page impositions.
|
| KeyboardFocusManager |
The KeyboardFocusManager is responsible for managing the active and focused Windows, and the current focus owner.
|
| Label |
A
Label object is a component for placing text in a container. |
| LinearGradientPaint |
The
LinearGradientPaint class provides a way to fill aShape with a linear color gradient pattern. |
| List |
The
List component presents the user with a scrolling list of text items. |
| MediaTracker |
The
MediaTracker class is a utility class to track the status of a number of media objects. |
| Menu |
A
Menu object is a pull-down menu component that is deployed from a menu bar. |
| MenuBar |
The
MenuBar class encapsulates the platform’s concept of a menu bar bound to a frame. |
| MenuComponent |
The abstract class
MenuComponent is the superclass of all menu-related components. |
| MenuItem |
All items in a menu must belong to the class
MenuItem , or one of its subclasses. |
| MenuShortcut |
The
MenuShortcut class represents a keyboard accelerator for a MenuItem. |
| MouseInfo |
MouseInfo provides methods for getting information about the mouse, such as mouse pointer location and the number of mouse buttons. |
| MultipleGradientPaint |
This is the superclass for Paints which use a multiple color gradient to fill in their raster.
|
| PageAttributes |
A set of attributes which control the output of a printed page.
|
| PageAttributes.ColorType |
A type-safe enumeration of possible color states.
|
| PageAttributes.MediaType |
A type-safe enumeration of possible paper sizes.
|
| PageAttributes.OrientationRequestedType |
A type-safe enumeration of possible orientations.
|
| PageAttributes.OriginType |
A type-safe enumeration of possible origins.
|
| PageAttributes.PrintQualityType |
A type-safe enumeration of possible print qualities.
|
| Panel |
Panel is the simplest container class. |
| Point |
A point representing a location in
(x,y) coordinate space, specified in integer precision. |
| PointerInfo |
A class that describes the pointer position.
|
| Polygon |
The
Polygon class encapsulates a description of a closed, two-dimensional region within a coordinate space. |
| PopupMenu |
A class that implements a menu which can be dynamically popped up at a specified position within a component.
|
| PrintJob |
An abstract class which initiates and executes a print job.
|
| RadialGradientPaint |
The
RadialGradientPaint class provides a way to fill a shape with a circular radial color gradient pattern. |
| Rectangle |
A
Rectangle specifies an area in a coordinate space that is enclosed by theRectangle object’s upper-left point(x,y) in the coordinate space, its width, and its height. |
| RenderingHints |
The
RenderingHints class defines and manages collections of keys and associated values which allow an application to provide input into the choice of algorithms used by other classes which perform rendering and image manipulation services. |
| RenderingHints.Key |
Defines the base type of all keys used along with the
RenderingHints class to control various algorithm choices in the rendering and imaging pipelines. |
| Robot |
This class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed.
|
| Scrollbar |
The
Scrollbar class embodies a scroll bar, a familiar user-interface object. |
| ScrollPane |
A container class which implements automatic horizontal and/or vertical scrolling for a single child component.
|
| ScrollPaneAdjustable |
This class represents the state of a horizontal or vertical scrollbar of a
ScrollPane . |
| SplashScreen |
The splash screen can be displayed at application startup, before the Java Virtual Machine (JVM) starts.
|
| SystemColor |
A class to encapsulate symbolic colors representing the color of native GUI objects on a system.
|
| SystemTray |
The
SystemTray class represents the system tray for a desktop. |
| Taskbar |
The
Taskbar class allows a Java application to interact with the system task area (taskbar, Dock, etc.). |
| TextArea |
A
TextArea object is a multi-line region that displays text. |
| TextComponent |
The
TextComponent class is the superclass of any component that allows the editing of some text. |
| TextField |
A
TextField object is a text component that allows for the editing of a single line of text. |
| TexturePaint |
The
TexturePaint class provides a way to fill aShape with a texture that is specified as aBufferedImage . |
| Toolkit |
This class is the abstract superclass of all actual implementations of the Abstract Window Toolkit.
|
| TrayIcon |
A
TrayIcon object represents a tray icon that can be added to thesystem tray . |
| Window |
A
Window object is a top-level window with no borders and no menubar. |
11.4.3 Interface Hierarchy
- java.util.EventListener
- java.awt.event.ActionListener
- java.awt.event.AdjustmentListener
- java.awt.event.AWTEventListener
- java.awt.event.ComponentListener
- java.awt.event.ContainerListener
- java.awt.event.FocusListener
- java.awt.event.HierarchyBoundsListener
- java.awt.event.HierarchyListener
- java.awt.event.InputMethodListener
- java.awt.event.ItemListener
- java.awt.event.KeyListener
- java.awt.event.MouseListener
- java.awt.event.MouseMotionListener
- java.awt.event.MouseWheelListener
- java.awt.event.TextListener
- java.awt.event.WindowFocusListener
- java.awt.event.WindowListener
- java.awt.event.WindowStateListener
11.4.4 Interfaces Description
| Interface |
Description
|
|---|---|
| ActiveEvent |
An interface for events that know how to dispatch themselves.
|
| Adjustable |
The interface for objects which have an adjustable numeric value contained within a bounded range of values.
|
| Composite |
The
Composite interface, along withCompositeContext , defines the methods to compose a draw primitive with the underlying graphics area. |
| CompositeContext |
The
CompositeContext interface defines the encapsulated and optimized environment for a compositing operation. |
| ItemSelectable |
The interface for objects which contain a set of items for which zero or more can be selected.
|
| KeyEventDispatcher |
A KeyEventDispatcher cooperates with the current KeyboardFocusManager in the targeting and dispatching of all KeyEvents.
|
| KeyEventPostProcessor |
A KeyEventPostProcessor cooperates with the current KeyboardFocusManager in the final resolution of all unconsumed KeyEvents.
|
| LayoutManager |
Defines the interface for classes that know how to lay out
Container s. |
| LayoutManager2 |
Defines an interface for classes that know how to layout Containers based on a layout constraints object.
|
| MenuContainer |
The super class of all menu related containers.
|
| Paint |
This
Paint interface defines how color patterns can be generated forGraphics2D operations. |
| PaintContext |
The
PaintContext interface defines the encapsulated and optimized environment to generate color patterns in device space for fill or stroke operations on aGraphics2D . |
| PrintGraphics |
An abstract class which provides a print graphics context for a page.
|
| SecondaryLoop |
A helper interface to run the nested event loop.
|
| Shape |
The
Shape interface provides definitions for objects that represent some form of geometric shape. |
| Stroke |
The
Stroke interface allows aGraphics2D object to obtain aShape that is the decorated outline, or stylistic representation of the outline, of the specifiedShape . |
| Transparency |
The
Transparency interface defines the common transparency modes for implementing classes. |
11.4.5 Exceptions and Errors
| Exception | Description |
|---|---|
| AWTException |
Signals that an Abstract Window Toolkit exception has occurred.
|
| FontFormatException |
Thrown by method createFont in the
Font class to indicate that the specified font is bad. |
| HeadlessException |
Thrown when code that is dependent on a keyboard, display, or mouse is called in an environment that does not support a keyboard, display, or mouse.
|
| IllegalComponentStateException |
Signals that an AWT component is not in an appropriate state for the requested operation.
|
| Error | Description |
|---|---|
| AWTError |
Thrown when a serious Abstract Window Toolkit error has occurred.
|
Program 11.1 Program to demonstrate AWT and Frame
//loginAWT.java import java.awt.*; class loginAWT { loginAWT() { Frame f = new Frame(); // create Frame Label l1 = new Label("login name"); Label l2= new Label("Password"); TextField t1 = new TextField(); // create login TextField TextField t2= new TextField(); // Create password Textfield Button b = new Button("Go"); // create a Button // Set bounds for positioning l,b,t in f l1.setBounds(20, 80, 80, 30); l2.setBounds(20, 110,80,30); t1.setBounds(100, 80, 80, 30); t2.setBounds(100,110,80,30); b.setBounds(180, 100, 80, 30); // add components to frame f.add(b); f.add(l1); f.add(t1); f.add(l2); f.add(t2); // frame size and title f.setSize(400,300); f.setTitle("login page"); f.setLayout(null); f.setVisible(true); } // main method public static void main(String args[]) { // creating instance of Frame class loginAWT login = new loginAWT(); } }
11.5 The Delegation Event Model
This model is a modern approach for handling events which defines a standard and consistent mechanism to generate and process events. The concept involved in this model is quite simple: a source generates event and sends it to one or more listeners. In this scheme, listener simply waits until receives an event. Once received, the listener processes the event and then returns. In this model listeners.
The Delegation Event Model consists of four main components:
- the event source,
- the event object,
- the event listener, and
- the event handler.
The event source is the object that generates the event. The event object contains information about the event. The event listener is the object that is notified when the event occurs. The event handler is the object that handles the event.
In this model listeners must register with a source in order to receive an event notification.
11.6 Event
In delegation model, an event is an object that describers a state change in a source. Examples for events in user interfacing environments are pressing a button, entering a character via keyboard, selecting a menu item in a list and clicking the mouse. Some other examples of events are a counter exceeding the value, a software or hardware failure occurs or an operation is completed.
11.6.1 Event Sources
A source is an object that generates an event. Sources may generate more than one type of event. A source must register listeners in order for the listeners to receive notifications about a specific type of event. See figure 11.3.
The general form of registration of each type of event is:
public void addTypeListener(TypeListener el)
Here Type is the name of the event and el is a reference to the event listener. For example, The method that registers a mouse motion listener is called addMouseMotionListener().
11.6.2 Event Listeners
A listener is an object that is notified when an event occurs. It has two major requirements.
- It must have registered with one or more sources to receive notifications about specific type of events
- It must implement methods to receive and process these notifications.
The methods that receive and process events are defined in a set of interfaces found in java.awt.event.
11.6.3 Event Classes
The classes that represent events are at the core of Java’s event handling mechanism. At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the superclass for all events. Its one constructor is shown as below
EventObject(Object src)
Here, src is the object that generates this event.
EventObject contains two methods: getSource() and toString(). The getSource() method returns the source of the event. It is of the form shown below
Object getSource()
The toString() returns the string equivalent of the event.
The AWTEvent, defined within the java.awt package, is a subclass of EventObject. It is the superclass of all AWT-based events used by the delegation event model.
The package java.awt.event defines several types of events that are generated by various user interface elements.
|
Event Class |
Description |
|
ActionEvent |
Generated when a button is pressed, a list item is double-clicked, or a menu item is selected. |
|
AdjustmentEvent |
Generated when a scroll bar is manipulated. |
|
ComponentEvent |
Generated when a component is hidden, moved, resized, or becomes visible. |
|
ContainerEvent |
Generated when a component is added to or removed from a container |
|
FocusEvent |
Generated when a component gain or loses keyboard focus. |
|
InputEvent |
Abstract super class for all component input event classes. |
|
KeyEvent |
Generated when input is received from the keyboard |
|
MouseEvent |
Generated when the mouse is dragged, moved, clicked, presses, or releases, also generated when the mouse enters or exists a component |
|
TextEvent |
Generated when the value of a text area or text field is changed. |
|
WindowEvent |
Generated when a window is activated, closed, deactivated, de-iconified, Iconified, opened, or quit |
|
ItemEvent |
Generated when a check box or list item is clicked, also occurs when a choice selection is made or a checkable menu item is selected or deselected. |
11.6.4 Sources of Events
The sources for all the events stated above are some user interface components. Some of these components along with their description(i.e how they generate an event) is given in the below table.
|
Event Source |
Description |
|
Button |
Generates action events when the button is pressed. |
|
Check box |
Generates item events when the check box is selected or deselected. |
|
Choice |
Generates item events when the choice is changed |
|
List |
Generates action events when an item is double-clicked, generates item events when an item is selected or deselected |
|
Menu Item |
Generates action events when a menu item is selected. Generates item events when a checkable menu item is selected or deselected. |
|
Scrollbar |
Generates adjustments events when the scroll bar is manipulated |
|
Text components |
Generates text events when the user enters a character. |
|
Window |
Generates window events when a window is activated, closed, deactivated, deiconified, iconified, opened, or quit. |
11.6.5 Event Listener Interfaces
When an event is generated by the event sources (Stated in the above table) then the event processing is left to the listener registered by the source, the event listener is responsible for the processing and returning results to the source. For example when a button pressed or an item in the list is double clicked or a menu item is selected(all these events are the examples of the action events) then ActionListener is activated to take respective action for the source that generates event. Similarly for each event there are corresponding listeners that are explained in the below table.
|
Interface |
Description |
|
ActionListener |
Defines one method to receive action events |
|
AdjustmentListener |
Defines one method to receive adjustment events |
|
ComponentListener |
Define four methods to recognize when a Component is hidden, moved, resized, or shown. |
|
ContainerListener |
Defines two methods to recognize when a component added or loses keyboard focus |
|
ItemListener |
Defines one method to recognize when the state of an item changes |
|
KeyListener |
Defines three methods to recognize when a key is pressed, released, or typed. |
|
MouseListener |
Defines five methods to recognize when the mouse clicked, enters a component, exits a component, is pressed, or is released. |
|
MouseMotionListener |
Defines two methods to recognize when the mose dragged or moved |
|
TextListener |
Defines one method to recognize when a text changes |
|
WindowListener |
Defines seven methods to recognize when a window is activated, closed, deactivated, deiconified, iconified, opened, or quit. |
The AWT defines windows according to a class hierarchy that adds functionality and specificity with each level The two most common windows are those derived from panel, which is used by applets, and those derived from frame, which creates a standard window. Much of the functionality of these windows are derived from their parent classes. Thus the description of the AWT hierarchy of the classes is shown below.
All the elements like the button, text fields, scroll bars, etc. are called components. Every component is added to a container.
After setting all the layouts of the windows for an applet, we can add some AWT tools(components for the container) by using add function. Every container has its own layout manager(that is, layout style). Individual components are grouped together in containers. The classes that extend Container class are known as container. Examples are window,Frame, Dialog and Panel
| Method | Description |
|---|---|
| public void add(Component c) | Adds a component on this component. |
| public void setSize(int width,int height) | Sets the size (width and height) of the component. |
| public void setLayout(LayoutManager m) | Defines the layout manager for the component. |
| public void setVisible(boolean status) | Changes the visibility of the component, by default false. |
11.7 Discussion about the AWT classes
11.7.1 TextField
TextField is just a box that can hold text. These are also known as text boxes and edit controls. Textfields are declared as
TextField t1;
After creating t1 as TextField we can create a new text field for t1 by using a constructor as shown below
T1=new TextField(); or T1=new TextField(String);
String may be a caption or some text to be displayed in that text field.
Some of Java TextField class methods are given below.
|
TextField() |
Creates a text field initialized with string |
|
TextField(String) |
Creates a text field initialized with string given method. |
|
AddActionListener(Action Listener) |
Adds action listener to text field |
|
SetText(String) |
Sets the text field with the given string |
|
GetText() |
Gets the contents of the text field |
|
getColumns() |
Returns the number of columns in the text field |
|
setColmns() |
Sets number of columns in the text field |
11.7.2 Button
This is an important tool in user interface environment. Buttons are also known as control. Buttons because based on the event occurred on the Button the control may be changed. Buttons are declared as below
Button b;
Above declaration b as a button and is created before adding ot to applet and is done by using a constructor as shown below
b=newButton(); or b=newButton(String);
String is the label for the button.
Some of Java Button class methods are given below.
|
Button() |
Constructs a button with no label |
|
Button(String) |
Constructs a button with no string as label |
|
AddActionListener(ActionListener) |
Adds the action listener to the button. |
|
GetLabel() |
Returns the label as string given with constructor |
|
setLabel(String) |
Sets the label as string given with constructor |
|
GetActionCommand() |
Returns the names of the action event fired by a button. |
11.7.3 TextArea
Handling text area is similar to text field the only difference is that text are contains several lines of text where as we have only one line in text field. The methods for text area are almost similar to text fields. Text areas are declared as
TextArea t;
Above declaration only declares t as TextArea and is constructed by using the constructors shown below
T=new TextArea() or T=new TextArea(int, int)
Int, int represents the number of rows and columns of the text area.
Some of Java TextArea Class methods
|
Method |
Description |
|
TextArea() |
Constructs newTextArea. |
|
TextArea(int, int) |
Deprecated, replaced by TextArea(String, int, int) |
|
TextArea(String) |
Constructs new TextArea with the specified text. |
|
TextArea(String, int, int) |
Constructs new TextArea with given text and number of rows, columns, and scrollbar “visibility” |
|
Append(String) |
Appends given string to end of the TextArea. |
|
Insert(String, int) |
Inserts the given string at the given position |
|
getMinimumSize() |
Return minimum size dimensions of TextArea |
|
replaceRange(String, int, int) |
Relaces text from the indicated start to end position with the new text given. |
Some methods of TextField also applicable to TextArea.
11.7.4 Label
Label control is a control element whose function is to display a text and nothing more. Labels are declared as following
Label l;
Here 1 is declared as a label and is created by using constructors which are of form shown below.
l=new label(); or l=new label(String);
String is the text to be displayed as label.
Some of Java label class methods
|
Method |
Description |
|
Label() |
Constructs an empty label. |
|
Label(String) |
Constructors a label with given text. |
|
Label(String, int) |
Constructs a label with given text and alignment(Label. RIGHT, Label.CENTER, or Label.LEFT) |
|
getText() |
Return the caption of the label |
|
setText(String) |
Sets the caption of the label with the given string. |
The following program creates a frame with name “first AWT program” and then adds a label “hi from AWT”, then a text box is added which is initially empty, a button with text “click here” and when the button is clicked with mouse the text box is set to “Button clicked”.
Program 11.2 Program to demonstrate AWT listeners
//firstAWT.java //Click here for code import java.awt.*; import java.awt.event.*; public class firstAWT { public static void main(String args[]) { Frame f = new Frame("first AWT program"); f.setSize(300,300); f.setVisible(true); TextField t=new TextField(); t.setBounds(80,80,80,80); f.add(t); Button b=new Button("Click here"); b.setBounds(160,160,100,80); f.add(b); Label l=new Label("hi from AWT"); f.add(l); b.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { if(e.getSource()==b) t.setText("Button clicked"); } } ); } }
11.7.5 Check Boxes
It is a control that is used to turn an option on or off. It contains of small box that can either contains a check mark or not. There is a label associated with each check box that describers what option the box represents. You change the state of the check box by clicking on it.
Checkbox can be declared as follows
Checkbox c;
Here c is declared as a checkbox and is created by using the constructors as follows
C=new Checkbox() or c-new Checkbox(String, Boolean)
Some of Java Checkbox Class methods
|
Checkbox() |
Constructs a checkbox with null caption |
|
Checkbox(String) |
Constructs a check box with string as caption |
|
Checkbox(String, Boolean) |
Constructs a checkbox with the given label. |
|
Checkbox(String, Boolean, CheckboxGroup) |
Constructs a checkbox with the given label set to the given state, and in the given check box group. |
|
Checkbox(String, CheckboxGroup, Boolean) |
Deprecated. Replaced by checkbox(String, Boolean, CheckboxGroup) |
|
addItemListener(ItemListener) |
Adds the given item listener to receive item events from this checkbox |
|
Getlabel() |
Returns the label of the checkbox |
|
Setlabel(String) |
Sets the check box’s state. |
|
getState() |
Returns the state of the check |
|
setState(Boolean) |
Sets the state of the checkbox |
11.7.6 CheckboxGroup
Radio buttons are similar to check boxes, the only difference is that we can select only one button at time but not more that one as in check boxes. We can add radio buttons to a group by using CheckboxGroup object Suppose we want to create two radio buttons r1,r2. We first declare a checkbox group in that we add the two check boxes named r1,r2 as below
CheckboxGroup c; Checkbox r1,r2;
Above are declaration and the construction is as follows
C=new CheckboxGroup(); R1=new checkbox(“first”, false, c); R2=new Checkbox(“second:, false, c);
Some of Java CheckboxGroup class methods
|
Method |
Descritpion |
|
CheckboxGroup() |
Creates a CheckboxGroup. |
|
getCurrent() |
Gets the current selection |
|
getSelectedCheckbox() |
Gets the current check box selected |
|
setCurrent() |
Sets the current selection to the indicated checkbox |
|
setSelectedCheckbox() |
Sets the current choice to the specified checkbox |
11.7.7 Scroll Bars
Scroll bars are used to select continuous values between a specified minimum and maximum. Scroll bars may be oriented horizontally or vertically. A scroll bar is actually a composite of several individual parts Each end has an arrow that you can click to move the current value of the scroll bar one unit in the direction if the arrow.
Scrollbars are declared as follows
Scrollbar s;
Here s is declared as a scrollbar and is created by using one of the constructors of scrollbar class as below.
s=new scrollbar(); or s=new scrollbar(int);
int is the orientation of the scroll bar.
Some of java Scrollbar class methods
|
Scrollbar() |
Constructs a scrollbar(vertical) |
|
Scrollbar(int) |
Constructs a scrollbar with specified orientation: scrollbar.Horizontal or scrollbar.vertical |
|
Scrollbar(int, int, int, int) |
Constructs a scrollbar with given orientation, initial value, scroll thumb size, minimum and maximum values. |
|
AddAdjustmentListener(AdjectmentListener) |
Adds new adjustment listener to get adjectment events from this scrollbar |
|
getMaximum() |
Returns the maximum value of this scrollbar |
|
Getminimum() |
Returns the minimum value of scrollbar |
|
getValue() |
Returns the current value of the scrollbar |
|
getOrientation() |
Returns the orientation of the scrollbar |
|
getVIsible() |
Returns the visibility portion of the scrollbar. |
|
getUnitIncrement() |
Gets nit increment for the scrollbar |
|
getPageIncrement() |
Gets page by page increment for scrollbar |
Similarly we have setMaximum(int), setMinimum(int), setValue(int), setOrientation(int), setVisibleAmount(int), setUnitIncrement(int)…etc. to set the dimensions of the scroll bar.
Scroll pane is a plane which contains scroll bars around the edges of this container as needed. These scroll pane are declared as follows.
ScrollPane sp;
Here sp is declared as scroll pane and is constructed as below
sp=new scrollPane() or sp=new ScrollOane(int)
11.7.8 Choice Controls
The choice control is just the drop-down list box which is very familiar in windows environment. This choice class is used to create a pop-up list of items from which the user may choose. When inactive, a choice component takes up only enough space to show the currently selected item. When the user clicks n it, the whole list of choices pops up, and new selection can be made.
Choice lists are declared as follows
Choice c;
Here c is declared as choicebox and is created by sing one of the constructors of the choice list class as below.
c=new Choice();
Some of java choice list class methods
|
Choice() |
Constructs a new choice |
|
Add(string) |
Adds an item to this choice |
|
addItemListener(itemListener) |
Adds the given itemlistener to receive item events from this choice |
|
getItem(int) |
Returns the string at given index |
|
getItemCount() |
Returns the number of items in the choice |
|
getSelectedItem() |
Returns an array(length 1)containing the currently selected object. |
|
Insert(String, int) |
Inserts the item into this choice at the specified position. |
|
paramString() |
Returns the parameter string of this choice |
|
processEvent(AWTEvent) |
Processes events on this choice |
|
ProcessItemEvent(ItemEvent) |
Processes item events occurring on this choice by dispatching them to any registered ItemListener objects |
|
Remove(int) |
Removes an item from choice’s menu |
|
Remove(string) |
Remove first occurrence from the choice menu |
Program 11.3 Construct UI that contains a choice box and text box such that the item selected in choice box is to be displayed in the text box.
//constructUI.java //importing awt class import java.awt.*; import java.awt.event.*; public class choiceAWT implements ItemListener { TextField t; Choice c; // class constructor choiceAWT() { // creating a frame Frame f = new Frame(); Label l=new Label("SELECT CITY"); t=new TextField(); // creating a choice component c = new Choice(); // setting the bounds of choice menu c.setBounds(100, 100, 100, 75); t.setBounds(100,150,100,75); l.setBounds(100,50,100,75); // adding items to the choice menu c.add("Hyderabad"); c.add("Guntur"); c.add("Vizag"); c.add("Vijayawada"); c.add("Tirupathi"); // adding choice menu to frame f.add(c); f.add(t); f.add(l); // setting size, layout and visibility of frame f.setSize(500, 500); f.setLayout(null); f.setVisible(true); c.addItemListener(this); } public void itemStateChanged(ItemEvent e) { if(e.getItemSelectable()==c) t.setText(c.getSelectedItem()); } // main method public static void main(String args[]) { new choiceAWT(); } }
11.7.9 ScrollLists
A scrolling list presents choices that the user may select from using the up and down arrows that appear at right in the list control. The scroll list object can be declared as follows
List l;
Here l is a list and is created by using any one of the constructors of the List class which is of the form shown below
L= new List() or L=new List(int)
int is the number of visible lines in the list.
Some of Java list class methods
|
Method |
Description |
|
List() |
Creates a new scrolling list initialized with no visible lines |
|
List(int) |
Creates a new scrolling list initialized with visible number of lines |
|
List(int, Boolean) |
Creates a new scrolling list initialized with the given number of visible lines and a Boolean indication if multiple selections are allowed or not. |
|
Add(String) |
Adds the given item to the scrolling list at the given position |
|
Add(string,int) |
Adds the given item to the scrolling list at the given positions |
|
addActionListener(ActionListener) |
Adds the given action listener to receive action events from the list |
|
addItem(String) |
Deprecated. Replaced by add(String) |
|
addItem((String,int) |
Deprecated. Replaced by add(String int) |
|
addItemListener(ItemListener) |
Adds the given item listener to receive item events from this list |
|
Clear() |
Deprecated. Replaced by removeAll() |
|
Deselect(int) |
Deselects the item st the given index. |
|
getItem(int) |
Gets the item associated with the given index |
|
getItemCont() |
Returns the number of items in the list |
|
getRows() |
Returns the number of visible lines in the list |
|
Remove(String) |
Removes the first occurrence of the item from the list. |
|
Remove(int) |
Removes the item from the list. |
|
delItem() |
Deprecated. Replaced by remove(String) and remove(int) |
Program 11.4. Program to implement scroll list
//listAWT.java import java.awt.*; import java.awt.event.*; public class listAWT implements ItemListener { List l; TextField t; listAWT() { Frame f = new Frame(); Label lb=new Label("CLICK ON A BOOK"); t=new TextField(); l=new List(); l.setBounds(100, 150, 200, 75); t.setBounds(100,230,200,75); lb.setBounds(100,50,150,75); l.add("Java Programming "); l.add(" C Programming "); l.add("C++ Programming "); l.add("Windows Programming "); l.add("Shell Programming "); l.add(" Programming with VC++"); l.add(" Programming VB"); f.add(l); f.add(t); f.add(lb); f.setSize(500, 500); f.setLayout(null); f.setVisible(true); l.addItemListener(this); } public void itemStateChanged(ItemEvent e) { if(e.getItemSelectable()==l) t.setText(l.getSelectedItem()); } // main method public static void main(String args[]) { new listAWT(); } }
11.8 Windows
The AWT defines according to class hierarchy that adds functionality and specificity with each level. The two most common windows are those derived from panel, which is used by applets, and those derived from Frame, which creates a standard window.
A window object is declared as
Demoframe w1;
Some of the frame class methods:
|
Method |
Description |
|
Frame() |
Constructs a frame(stars as invisible) |
|
Frame(string) |
Constructs a frame with given title |
|
getCursorType() |
Gets cursor type |
|
getMenuBar() |
Gets menu bar frame |
|
Remove(MenuComponent) |
Removes given menu bar from object |
|
removeWindowListener(WindowListener) |
Removes given window listener. |
|
setMenuBar(menuBar) |
Sets menu bar for object) |
|
setTitle(String) |
Sets title for Frame to given title |
Program 11.5 Frame Layout demonstration
//demoFrame.java import java.awt.*; import java.awt.event.*; import java.awt.GridLayout.*; public class demoFrame implements ActionListener { TextField t; Button c; demoFrame() { Frame f=new Frame(); f.setLayout(new GridLayout(2,1)); t=new TextField(10); f.add(t); c=new Button("click here"); f.add(c); c.setBounds(100, 150, 200, 75); t.setBounds(100,230,200,75); f.setSize(500, 500); f.setLayout(null); f.setVisible(true); c.addActionListener(this); } public void actionPerformed(ActionEvent e) { if(e.getSource()==c) t.setText("clicked"); } // main method public static void main(String args[]) { new demoFrame(); } }
Program 11.6 Program to implement ActionListener
//Save both windowAWT.java and demoFrame2.java in different files. Compile them and then run windowAWT class file. //windowAWT.java import java.awt.*; import java.awt.event.*; public class windowAWT implements ActionListener { Button b1,b2; demoFrame w; windowAWT() { Frame f1=new Frame(); b1=new Button("show"); b1.setBounds(100, 150, 200, 75); f1.add(b1); b1.addActionListener(this); b1.addActionListener(this); f1.add(b1); b2=new Button("hide"); b2.setBounds(100,230,200,75); b2.addActionListener(this); f1.add(b2); w=new demoFrame2(); w.setSize(500,050); f1.setSize(500, 500); f1.setLayout(null); f1.setVisible(true); } public void actionPerformed(ActionEvent e) { if(e.getSource()==b1) w.setVisible(true); if(e.getSource()==b2) w.setVisible(false); } // main method public static void main(String args[]) { new windowAWT(); } }
**************************************** //demoFrame2.java import java.awt.*; import java.awt.event.*; import java.awt.GridLayout.*; public class demoFrame2 implements ActionListener { TextField t; Button c; Frame f; demoFrame2() { f=new Frame(); f.setLayout(new GridLayout(2,1)); t=new TextField(10); f.add(t); c=new Button("click here"); f.add(c); c.setBounds(100, 150, 200, 75); t.setBounds(100,230,200,75); //f.setSize(500, 500); f.setLayout(null); //f.setVisible(true); c.addActionListener(this); } public void setSize(int a, int b) { this.f.setSize(a,b); } public void setVisible(boolean visible) { this.f.setVisible(visible); } public void actionPerformed(ActionEvent e) { if(e.getSource()==c) t.setText("clicked"); } }
11.9 Menu bars
A menu bar displays a list of top level menu choices. Each choice is associated with a drop down menu.
Menu bar is declared as
MenuBar mbar= new MenuBar();
Menu is declared as
Menu mfile=Menu(“file”);
Some of the menu class methods are given below.
|
Method |
Description |
|
Menu() |
Constructs a new menu with an empty label |
|
Menu(String) |
Constructs a new menu with the given label. |
|
Add(MenuItem) |
Adds the given item to the menu |
|
Add(String) |
Adds an item to the menu |
|
getItem(int) |
Returns the item located at the given index of this menu |
|
GetItemCount() |
Returns the number of elements in this menu |
|
Insert(MenuItem, Int) |
Inserts the MenuItem to this menu at the given position |
|
Remove(Menucomponent) |
Delete the given item from this menu |
|
Removeall() |
Deletes all items from this menu. |
11.10 Graphics
The AWT supports a rich assortment of graphical methods. All graphics are drawn relative to window. The graphics class encapsulates a graphical context. The Graphics class defines a number of drawing functions. Each shape can be drawn edge-only or filled.
11.10.1 Drawing lines
Lines are drawn by means of the drawLine() method.
void drawLine(int startX, int startY, int endX, int endY);
11.10.2 Drawing Rectangle
Rectangle are drawn by using drawRect() and filled rectangles are drawn by sing fillRect() method
vdrawRondRect (int top, int left, int width, int height, int xDiam, int yDiam) void fillRoundRect(int top, int left, int width, int height, int xDiam, int yDiam)
11.10.3 Drawing Ellipses and Circles
To draw an ellipse we use drawOval() and to fill an ellipse we use fillOval() are used.
void drawOval(int top, int left, int width, int height) void fillOval(int top, int left, int width, int height)
11.10.4 Drawing Arcs
Arcs can be drawn with drawArc() and fillArc() methods.
void drawArc(int top, int left, int width, int height, int startangle, int sweepangel) void fillArc(int top, int left, int width, int height, int startangle, int sweepangle)
11.10.5 Drawing Polygons
We can draw polygons by using drawPolygon() and fillPolygon().
void drawPolygon(int x[], int y[], int numpoint) void fillPolygon(int x[], int y[], int numpoint)
In order to size a graphics object to fit in current window it is necessary to find the size of the current window. The size of window can be obtained by using getSize() method.
This method returns the dimensions of the current window encapsulated within a Dimension object.
11.10.6 Color Class
The color class defines several methods that help manipulates colors.
Using Hue, saturation, and Brightness: The hue-saturation-brightness(HSB) color model is an alternative to red-green-blue(RGB) for specifying particular colors. Figuratively, hue is a wheel of color. The hue is specified with a number between 0.0 and 1.0. Saturation is another scale ranging from 0.0 to 1.0, where 1 is bright white and 0 is black.
Color supplies two methods that convert between RGB and HSB.
Static int HSBtoRGB(float hue, float saturation, float brightness) Static float[] RGBtoHSB(int red, int green, int blue, float values[])
We can obtain the red, green, and blue components of a color by using gerRed(), getBlue() and getGreen().
To obtain a packed, RGB representation of a color we use getRGB()
int getRGB()
We can change color by calling the graphics method setColor() and we can obtain the current color by getColor().
void setcolor(color newColor)
Color getColor()
11.10.7 Font
The AWT supports multiple type fonts. The AWT provides flexibility by abstracting font-manipulation operations and allowing for dynamic selection of fonts. Fonts are encapsulated by Font class.
Some of java Font class methods
|
Method |
Description |
|
Static Font decode(String) |
Returns a font given its name |
|
Boolean equals(object Font) |
Returns true if the invoking object contains the same font as that specified by FontObj. Otherwise returns false. |
|
Static Font getFont(String) |
Returns the fone associated with system property specified by string. Nll is returned if string does not exist |
|
Static Font getFont(String) |
Returns the font associated with the system property specified by string. Nll is returned if string does not exist. |
|
String getFontName() |
Returns the face name of the invoking font. |
|
Int getSize() |
Returns the size, in points, of the the invoking font. |
|
Int getStyle() |
Returns the style values of the invoking font. |
|
Boolean isBold() |
Returns if the font includes the BOLD style value. Otherwise returns false. |
|
String toString() |
Returns the string equivalent of the invoking font. |
Boolean isItalic(), Boolean isPlain() does the same function similar to isBold() but in these cases test is made for italic and plain text in success.
11.11 Summary
In this chapter you have learned in detail about AWT package, the components, containers, panels, windows and Listeners.
Media Attributions
- 11.2 loginAWT
- 11.3 Event Delegation Model
- 11.4 AWT Hierarchy of classes
- 11.1 AWT Demo
- 11.5 choiceAWT
- 11.4 listAWT
- 11.5 demoFrame
- 11.6 windowAWT Action Listener