AWT - Tutorials Point

Transcription

AWTAbout the TutorialJAVA provides a rich set of libraries to create Graphical User Interface (GUI) objects in anplatform independent way. Abstract Window Toolkit (AWT) is a set of APIs used by Javaprogrammers to create GUI objects. In this tutorial, we will learn how to use AWT to createGUI objects such as buttons, scroll bars, layout, menus, and more.AudienceThis tutorial is designed for all those software professionals who would like to learn JAVAGUI Programming in simple and easy steps.PrerequisitesBefore proceeding with this tutorial, you should have a basic understanding of Javaprogramming language and how to use it in practice.Copyright & Disclaimer Copyright 2015 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of Tutorials Point (I)Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republishany contents or a part of the contents of this e-book in any manner without written consentof the publisher.We strive to update the contents of our website and tutorials as timely and as precisely aspossible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.Ltd. provides no guarantee regarding the accuracy, timeliness, or completeness of ourwebsite or its contents including this tutorial. If you discover any errors on our website orin this tutorial, please notify us at contact@tutorialspoint.comi

AWTTable of ContentsAbout the Tutorial . iAudience . iPrerequisites . iCopyright & Disclaimer . iTable of Contents . ii1.AWT – OVERVIEW . 1Graphical User Interface. 1Basic Terminologies. 1Examples of GUI Based Applications . 2Advantages of GUI over CUI . 22.AWT – ENVIRONMENT SETUP . 4Setting up the Path for Windows 2000/XP . 4Setting up the Path for Windows 95/98/ME . 4Setting up the Path for Linux, UNIX, Solaris, FreeBSD . 4Popular Java Editors . 43.AWT – CONTROLS. 6AWT Component Class . 7AWT UI Elements . 20AWT Label Class . 21AWT Button Class . 25AWT CheckBox Class . 30AWT CheckBoxGroup Class . 35AWT List Class . 40AWT TextField Class . 46ii

AWTAWT TextArea Class . 51AWT Choice Class . 57AWT Canvas Class . 62AWT Image Class . 66AWT Scrollbar Class . 71AWT Dialog Class . 77AWT FileDialog Class . 834.AWT – EVENT HANDLING . 89What is an Event? . 89Types of Event . 89What is Event Handling? . 89Callback Methods . 90Event Handling Example . 905.AWT – EVENT CLASSES . 95EventObject Class . 95Class Declaration . 95Field . 95Class Constructors . 95Class Methods . 95Methods Inherited . 96AWT Event Classes . 96AWT AWTEvent Class . 97AWT ActionEvent Class . 99AWT InputEvent Class . 100AWT KeyEvent Class . 102AWT MouseEvent Class . 111iii

AWTAWT TextEvent Class . 114AWT WindowEvent Class . 115AWT AdjustmentEvent Class . 117AWT ComponentEvent Class . 118AWT ContainerEvent Class . 119AWT MouseMotionEvent Class . 121AWT PaintEvent Class. 1216.AWT – EVENT LISTENERS . 128EventListner Interface . 128Class Declaration . 128AWT Event Listener Interfaces . 128AWT ActionListener Interface . 129AWT ComponentListener Interface . 132AWT ItemListener Interface . 137AWT KeyListener Interface . 140AWT MouseListener Interface . 144AWT TextListener Interface . 148AWT WindowListener Interface . 152AWT AdjustmentListener Interface . 157AWT ContainerListener Interface . 160AWT MouseMotionListener Interface . 164AWT FocusListener Interface . 1687.AWT – EVENT ADAPTERS . 173AWT Adapters . 173AWT FocusAdapter Class . 173AWT KeyAdapter Class . 177iv

AWTAWT MouseAdapter Class . 181AWT MouseMotionAdapter Class . 185AWT WindowAdapter Class . 1898.AWT – LAYOUTS . 194Introduction . 194Layout Manager . 194AWT Layout Manager Interface . 195AWT LayoutManager2 Interface. 195AWT Layout Manager Classes. 196AWT BorderLayout Class . 197AWT CardLayout Class . 202AWT FlowLayout Class . 207AWT GridLayout Class . 212AWT GridBagLayout Class . 2179.AWT – CONTAINERS . 224AWT Container Class . 224AWT UI Elements . 228AWT Panel Class . 229Class Constructors . 229AWT Frame Class . 232AWT Window Class . 23910. AWT – MENU CLASSES . 248Menu Hiearchy . 248Menu Controls . 248AWT MenuComponent Class . 249AWT MenuBar Class . 250v

AWTAWT MenuItem Class . 256AWT Menu Class . 263AWT CheckboxMenuItem Class . 270AWT PopupMenu Class . 27611. AWT – GRAPHICS CLASSES. 281Graphics Controls . 281AWT Graphics Class . 282AWT Graphics2D Class. 287AWT Arc2D Class . 292AWT CubicCurve2D Class . 297AWT Ellipse2D Class . 302AWT Rectangle2D Class . 305AWT QuadCurve2D Class . 310AWT Line2D Class . 315AWT Font Class . 319AWT Color Class . 327AWT BasicStroke Class . 332vi

1. AWT – OVERVIEWAWTGraphical User InterfaceGraphical User Interface (GUI) offers user interaction via some graphical components. Forexample, our underlying Operating System also offers GUI via window, frame, Panel, Button,Textfield, TextArea, Listbox, Combobox, Label, Checkbox etc. These all are known ascomponents. Using these components, we can create an interactive user interface for anapplication.GUI provides result to end-users in response to its raised events. It is entirely based onevents. For example, clicking on a button, closing a window, opening a window, typingsomething in a text area etc. These activities are known as events. GUI makes it easier forthe end user to use an application. It also makes them interesting.Basic eDescriptionComponent is an object having a graphical representation that can bedisplayed on the screen and that can interact with the user. For example,buttons, checkboxes, list and scrollbars of a graphical user interface.Container object is a component that can contain other components.Components added to a container are tracked in a list. The order of the listwill define the components' front-to-back stacking order within thecontainer. If no index is specified when adding a component to a container,it will be added to the end of the list.Panel provides space in which an application can attach any othercomponents, including other panels.Window is a rectangular area, which is displayed on the screen. In adifferent window, we can execute different program and display differentdata. Window provide us with multitasking environment. A window musthave either a frame, dialog, or another window defined as its owner whenit's constructed.A Frame is a top-level window with a title and a border. The size of theframe includes any area designated for the border. Frame encapsulateswindow. It and has a title bar, menu bar, borders, and resizing corners.7

AWTCanvasCanvas component represents a blank rectangular area of the screen ontowhich the application can draw. Application can also trap input events fromthe use of the blank area of Canvas component.Examples of GUI Based ApplicationsFollowing are some of the examples for GUI based applications: Automated Teller Machine (ATM) Airline Ticketing System Information Kiosks at railway stations Mobile Applications Navigation SystemsAdvantages of GUI over CUI GUI provides graphical icons to interact while the CUI (Character User Interface) offersthe simple text-based interfaces. GUI makes the application more entertaining and interesting on the other hand CUIdoes not. GUI offers click and execute environment while in CUI every time, we have to enterthe command for a task. New user can easily interact with graphical user interface by the visual indicators, butit is difficult in Character user interface. GUI offers a lot of controls of file system and the operating system while in CUI, youhave to use commands, which is difficult to remember. Windows concept in GUI allows the user to view, manipulate, and control the multipleapplications at once while in CUI, user can control one task at a time. GUI provides multitasking environment so as the CUI also does, but CUI does notprovide same ease as the GUI do. Using GUI, it is easier to control and navigate the operating system, which becomesvery slow in command user interface. GUI can be easily customized but CUI cannot be.8

AWT2. AWT – ENVIRONMENT SETUPThis chapter guides you on how to download and set up Java on your computer. Please followthe steps given below to set up the environment.Java SE is freely available on the link Download Java. So you download a version based onyour operating system.Follow the instructions to download java and run the .exe to install Java on your computer.Once you installed Java on your computer, you would need to set up environment variablesto point to correct installation directories.Setting up the Path for Windows 2000/XPAssuming you have installed Java in c:\Program Files\java\jdk directory: Right-click on 'My Computer' and select 'Properties'. Click on the 'Environment variables' button under the 'Advanced' tab. Now alter the 'Path' variable so that it also contains the path to the Java executable.For example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then changeyour path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.Setting up the Path for Windows 95/98/MEAssuming you have installed Java in c:\Program Files\java\jdk directory: Edit the 'C:\autoexec.bat' file and add the following'SET PATH %PATH%;C:\Program Files\java\jdk\bin'lineattheend:Setting up the Path for Linux, UNIX, Solaris, FreeBSDEnvironment variable PATH should be set to point — where the java binaries have beeninstalled. Refer to your shell documentation, if you have trouble doing this.Example, if you use bash as your shell, then you would add the following line to the end ofyour '.bashrc: export PATH /path/to/java: PATH'Popular Java EditorsTo write your java programs, you will need a text editor. There are even more sophisticatedIDE available in the market. But for now, you can consider one of the following:9

AWT Notepad: On Windows system, you can use any simple text editor like Notepad(Recommended for this tutorial), TextPad. Netbeans: It is a Java IDE that is open source and free, it can be downloaded fromhttp://www.netbeans.org/index.html. Eclipse: It is also a java IDE developed by the eclipse open source community andcan be downloaded from http://www.eclipse.org/.10

3. AWT – CONTROLSAWTEvery user interface considers the following three main aspects: UI elements: These are the core visual elements, the user eventually sees andinteracts with. GWT provides a huge list of widely used and common elements varyingfrom basic to complex. We will discuss all these in this tutorial. Layouts: They define how UI elements should be organized on the screen and providea final look and feel to the GUI (Graphical User Interface). This part will be covered inLayout chapter. Behavior: These are events that occur when the user interacts with UI elements. Thispart will be covered in Event Handling chapter.Every AWT controls inherit properties from Component class.11

AWTSr.No.Control & Description1ComponentA Component is an abstract super class for GUI controls and it represents anobject with graphical representation.AWT Component ClassThe class Component is the abstract base class for the non-menu user-interfacecontrols of AWT. Component represents an object with graphical representation.Class DeclarationFollowing is the declaration for java.awt.Component class:public abstract class Componentextends Objectimplements ImageObserver, MenuContainer, SerializableFieldFollowing are the fields for java.awt.Component class: static float BOTTOM ALIGNMENT -- Ease-of-use constant for getAlignmentY. static float CENTER ALIGNMENT -- Ease-of-use constant for getAlignmentYand getAlignmentX. static float LEFT ALIGNMENT -- Ease-of-use constant for getAlignmentX. static float RIGHT ALIGNMENT -- Ease-of-use constant for getAlignmentX. static float TOP ALIGNMENT -- Ease-of-use constant for getAlignmentY().Class ConstructorsS.N.1Constructor & Descriptionprotected Component()This creates a new Component.Class MethodsS.N.1Method & Descriptionboolean action(Event evt, Object what)12

AWT23456789101112131415161718Deprecated. As of JDK version 1.1, should register this component asActionListener on component which fires action events.void add(PopupMenu popup)Adds the specified popup menu to the component.void addComponentListener(ComponentListener l)Adds the specified component listener to receive component events from thiscomponent.void addFocusListener(FocusListener l)Adds the specified focus listener to receive focus events from this componentwhen this component gains input focus.void addHierarchyBoundsListener(HierarchyBoundsListener l)Adds the specified hierarchy bounds listener to receive hierarchy boundsevents from this component when the hierarchy to which this containerbelongs changes.void addHierarchyListener(HierarchyListener l)Adds the specified hierarchy listener to receive hierarchy changed events fromthis component when the hierarchy to which this container belongs changes.void addInputMethodListener(InputMethodListener l)Adds the specified input method listener to receive input method events fromthis component.void addKeyListener(KeyListener l)Adds the specified key listener to receive key events from this component.void addMouseListener(MouseListener l)Adds the specified mouse listener to receive mouse events from thiscomponent.void addMouseMotionListener(MouseMotionListener l)Adds the specified mouse motion listener to receive mouse motion eventsfrom this component.void addMouseWheelListener(MouseWheelListener l)Adds the specified mouse wheel listener to receive mouse wheel events fromthis component.void addNotify()Makes this Component displayable by connecting it to a native screenresource.void addPropertyChangeListener(PropertyChangeListener listener)Adds a PropertyChangeListener to the listener list.void addProperty ChangeListener(String propertyName, PropertyChangeListener listener)Adds a PropertyChangeListener to the listener list for a specific property.void applyComponentOrientation(ComponentOrientation orientation)Sets the ComponentOrientation property of this component and allcomponents contained within it.boolean areFocusTraversalKeysSet(int id)Returns whether the Set of focus traversal keys for the given focus traversaloperation has been explicitly defined for this Component.int checkImage(Image image, ImageObserver observer)Returns the status of the construction of a screen representation of thespecified image.int checkImage(Image image,int width,int height,ImageObserver observer)13

AWTReturns the status of the construction of a screen representation of thespecified image.19boolean contains(int x,int y)Checks whether this component "contains" the specified point, where x and yare defined to be relative to the coordinate system of this component.boolean contains(Point p)2021222324Checks whether this component "contains" the specified point, where thepoints x and y coordinates are defined to be relative to the coordinate systemof this component.Image createImage(ImageProducer producer)Creates an image from the specified image producer.Image createImage(int width,int height)Creates an off-screen drawable image to be used for double buffering.VolatileImage createVolatileImage(int width,int height)Creates a volatile off-screen drawable image to be used for double buffering.VolatileImage createVolatileImage(int width,int height,ImageCapabilities caps)Creates a volatile off-screen drawable image, with the given capabilities.25262728293031323334void deliverEvent(Event e)Deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent e).void disable()Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).protected void disableEvents(long eventsToDisable)Disables the events defined by the specified event mask parameter frombeing delivered to this component.void dispatchEvent(AWTEvent e)Dispatches an event to this component or one of its sub components.void doLayout()Prompts the layout ma

About the Tutorial JAVA provides a rich set of libraries to create Graphical User Interface (GUI) objects in an platform independent way. Abstract Window Toolkit (AWT) is a set of APIs used by Java programmers to create GUI objects. In this tutorial, we will learn how to use AWT to create