970 likes | 1.22k Views
8.0 AWT Components : Overview. Introduction: The AWT i.e. Abstract Windowing Toolkit Provides a collection of classes for developing GUI Used to create windows, draw and work with images, and components like buttons,etc. The java.awt package contains the AWT GUI classes. Objective:
E N D
8.0 AWT Components : Overview • Introduction: • The AWT i.e. Abstract Windowing Toolkit • Provides a collection of classes for developing GUI • Used to create windows, draw and work with images, and components like buttons,etc. • The java.awt package contains the AWT GUI classes. • Objective: After completing this Topic, you will be familiar with AWT Package and able to create GUI using AWT Components 1 . Introduction to AWT and AWT Components 2 . Visual Components 3 . The Container Components 4 . The Menu 5 . Utility classes
AWT and AWT Components • Java components are implemented by help of supperclasses the java.awt.Component and java.awt.MenuComponents. • AWT component categories : 1] Visual components • 2] Container components • 3] Menu components Component Menu Component Visual Component Container Component
AWT and AWT Components • Visual components and Container components are inherited from java.awt.Component and implements several methods listed below. • getSize() • setSize() • setBackground() • setForeground() • setFont() • setEnabled • setBounds() • setVisible() • Note : Menu components extends java.awt.MenuComponent therefore they do not inherit the same functionality as Visual and Container components
AWT and AWT Components Screen snapshots for setEnabled method Button button.setEnabled(true); figure 1 button.setEnabled(false); figure 2
Visual Components • AWT Visual Components • Button • Label • Checkbox • TextField • TextArea • Choice • List • FileDialog • Canvas • ScrollPane • Scrollbar
Visual Components This is the sample program to create components. 2 1 import java.awt.Button; import java.awt.Frame; class Sample extends Frame { public static void main(String args[]) { //Create an instance. Frame mainFrame =new Sample(); } Sample() { //Set the title of window setTitle("CTS: Visual component Demo"); setSize(300,140); //Set the size of the frame. setVisible(true); //Make window visible. /* Change only following lines */ Button button = new Button("Click me!"); button.setBounds(80,60,140,40); add(button); } }//End of Class Continue
Visual Components Button • The button class implements push button Button button = new Button("Click me!"); • Constructor : public Button() public Button(String label)
Visual Components Label • The label is only used to display any text, and not for user interaction Label label = new Label(“ This is Label "); • Constructor : public Label() public Label(String label) public Label(String label, int alignment)
Visual Components Checkbox • The Checkbox is a kind of button with two states. Two states are true (Checked) and false (Unchecked). Label label = new Label(“ This is Label "); • Constructor : public Checkbox() public Checkbox(String label) public Checkbox(String label, CheckboxGroup group, boolean state)
Visual Components TextField • The TextField is used to accept text from user TextField textfield = new TextField (“ Input here"); • Constructor : public TextField() public TextField(int cols) public TextField(String text) public TextField(String text, int cols)
Visual Components TextArea • The TextArea is used to accept text from user TextArea textarea = new TextArea (“ Input here"); • Constructor : public TextArea() public TextArea(int rows, int cols) public TextArea(String text) public TextArea(String text, int rows, int cols)
Visual Components Choice • The Choice is also called as pull-down list. Choice choice = new Choice (); choice.addItem(“Item 1”); //To add Items to Choice choice.addItem(“Item 2”); • Constructor : public Choice()
Visual Components List • The List is a collection of text items. List can be used for single selection or multi selection List list = new List(); list.add(“List Item 1”); list.add(“List Item 2”); • Constructor : public List() public List(int rows) public List(int rows, boolean isMultipleSelections)
Visual Components FileDialog • File open or file save dialog. • Appearance of this dialog box is platform dependent FileDialog filedialog = new FileDialog (this,” Select File to Load”, FileDialog.LOAD); • Constructor : public FileDialog(Frame parentWindow, String dlgTitle) public FileDialog(Frame parentWindow, String dlgTitle, int dlgMode)
Visual Components Canvas • Without any default appearance or behavior • We can use Canvas to create custom drawing Canvas canvas = new Canvas (); canvas.setBackground(Color. BLUE); canvas.setSize(200,200); • Constructor : public Canvas ()
Visual Components ScrollPane • Form of panel • Can contain child component having dimensions greater than the ScrollPane • Scroll pane provides horizontal or/and vertical scrollbars //Code snippet ScrollPane scrollpane = new ScrollPane (): TextArea bigText = new TextArea(" This is very very Long Text .. !!!"); bigText.setVisible(true); scrollpane.add(bigText); add(scrollpane); • Constructor : ScrollPane() ScrollPane(int scrollBarPolicy)
Visual Components Scrollbar • The Scrollbar component that adjusts scroll panes and lists which is available as a component in Scrollbar's own right. setLayout(null); Scrollbar sb = new Scrollbar(Scrollbar.HORIZONTAL, 10, 10, 0, 300); sb.setBounds(3,26,300,20); add(sb); • Constructor : public Scrollbar() public Scrollbar(int orientation) Range of scrollbar initial value of the scroll bar scroll bar thumb
Container Components • AWT Container Components • Applet • Frame • Panel • Dialog
Component Container Panel Window Applet Frame Dialog Container Components Hierarchy for Container components
Container Components Applet • Applets are Java programs that are integrated in Web pages. • Every applet is implemented by creating a subclass of the Applet class. • Import java.applet.*; • Java.applet package contains - 1 class : Applet - 3 interfaces : AppletContext, AppletStub, and AudioClip
Container Components Rules for Applet / Restriction on Applet : • Applet can not execute any program on local machine • Applet can not access any file on local machine • Applet can not open socket connection to any one other than from where it is down loaded • If any Applet opens any new window then that window gives warning and message box
Container Components Applet example : //FirstApplet.java import java.applet.*; import java .awt.Button; import java.awt.Graphics; public class FirstApplet extends Applet { Button b = new Button ("Click Me"); public FirstApplet() { b.setBounds(20,25,100,40); this.setLayout(null); this.add(b); } public void paint (Graphics g) { g.drawString(“Applet Example",14,14); } 1 2 public void init() { System.out.println("Applet Initialized "); } public void start() { System.out.println("Applet Started"); } public void stop() { System.out.println("Applet Stopped"); } public void destroy(){ System.out.println("Applet Destroyed"); } } //End Applet Class Continue
Applet Loaded Init Start Window Maximized Window Minimized /Closed Stop Destroy Window Closed Container Components Applet life cycle • Init • Start • Stop • Destroy
Container Components HTML Code to use applet in HTML file <html> <body> <applet code= "FirstApplet.class" height= "100" width = "140" > </applet> </body> </html>
Container Components Figure 1 Figure 2
Container Components Figure 1
Container Components Code snippet in java file String s = new String(); public void init(){ s="Parameter :" + getParameter("Param1"); System.out.print("Applet Initialized "); } public void paint (Graphics g){ g.drawString(s,14,14); } Constructor : public Button() Creates a button with no label. public Button(String label) Creates a button with the indicated label. Parameter passing to Applet : Code snippet in HTML file <html> <body> <applet code= "FirstApplet.class“ height= "100“ width = "140" > <param name= "Param1“ value= "Cognizant"> </param> </applet> </body> </html>
Container Components Figure 2
Container Components Other Applet Attribute Tags: < APPLET [CODEBASE =code_Base_URL] CODE =applet_File [ALT =alternate_Text] [NAME =applet_Instance_Name] WIDTH = in_Pixels HEIGHT = in_Pixels [ALIGN =alignment] [VSPACE = in_Pixels] [HSPACE = in_Pixels] > [< PARAM NAME =applet_Parameter1VALUE = value>] [< PARAM NAME =applet_Parameter2VALUE =value>] . . . . . . </APPLET>
Container Components • Frame • Create a standard window • import java.awt.Frame • Constructors : • Frame() • Frame(String frameTitle) • Methods : • setTitle(String), setVisible(boolean), • setSize(int, int), setSize(Dimension) • Dimension getSize().
Container Components Panel • Subclass of container • Panel is super class for applet • Intermediate level of space organization of GUI. • Does not contain Title bar , Menu bar and Border • add() method
Container Components Dialog • Pop-up window • User input • Modal or Modeless • Constructors : • Dialog(Frame parentWindow,boolean Mode) • Dialog(Frame parentWindow, String windowTitle, boolean Mode) • Example : • Save Dialog box • Load Dialog box etc.
The Menu Menus • Pull-down menus • Tear-off menu. • Pop-up menus • Classes used • Menu Class • MenuBar Class • MenuComponet Class • MenuItem Class Note : Menu can only be set to Frame
The Menu Menu bar Menu Items
The Menu // Menu demo code import java.awt.*; import java.awt.event.*; class Test extends Frame { MenuBar mb; public Test(){ mb=new MenuBar(); Menu menu=new Menu("File"); MenuItem mn=new MenuItem("New"); MenuItem mo=new MenuItem("Open"); menu.add(mn); menu.add(mo); mb.add(menu); this.setMenuBar(mb); } // Test Constructor 1 2 public static void main(String args[] ){ System.out.println("Starting Test..."); Test mainFrame = new Test(); mainFrame.setSize(200, 200); mainFrame.setTitle("Test"); mainFrame.setVisible(true); } }
The Menu Figure 1 Figure 2 Figure 3
The Menu • A PopupMenu class implements a menu which can be dynamically popped up at a specified position within a component. • public class PopupMenu extends Menu • As the inheritance hierarchy suggests, a PopupMenu can be used anywhere a Menu can be used. However, if you use a PopupMenu like a Menu (e.g., We add it to a MenuBar), then you can not call show on that PopupMenu. • We can show Popup Menu to specified location using show() method • void show(Component origin, int x, int y) Shows the popup menu at the x, y position relative to an origin component.
Utility classes • Vectors • Dimension • Insets • Point • Polygon • Rectangle • Shape • Color • Color • SystemColor
Utility classes • Resource • Cursor • Font • FontMetrics • Graphics • Image • PrintGraphics • PrintJob • Toolkit
Utility classes • Vectors • Dimension :The Dimension class encapsulates the width and height of a component in a single object. • e.g. void setSize(Dimension d) method of Component • Insets : An Insets object is a representation of the borders of a container. It specifies the space that a container must leave at each of its edges. The space can be a border, a blank space, or a title. • Point : A point represents an coordinate. • Polygon : A polygon consists of a list of, where each successive pair of coordinates defines a side of the polygon • Rectangle : A Rectangle specifies an rectangular area in a coordinate space • Shape : The Shape interface provides definitions for form of geometric shape.
Utility classes • Color • Color : This class encapsulate colors using the RGB format. • SystemColor : A class to encapsulate symbolic colors representing the color of native GUI objects on a system. • Resource • Cursor : A class to encapsulate the bitmap representation of the mouse cursor. • Font :The Font class represents fonts, which are used to render text on screen. • FontMetrics : The FontMetrics class defines a font metrics object, which encapsulates information about the rendering of a particular font on a screen.
Utility classes • Graphics : The Graphics class is the abstract base class for all graphics contexts that allow an application to draw onto components. • Image : The abstract class Image is the superclass of all classes that represent graphical images. • Toolkit : This class is the abstract superclass of all actual implementations of the Abstract Window Toolkit • Note : Example code snippets for Dimension, Point, Polygon, Rectangle, Color,Font, Graphics, Image, Toolkit are in Topic “Painting”
AWT Components : Summary • The AWT i.e. Abstract Windowing Toolkit provides classes for developing GUI • The java.awt package contains the AWT GUI classes. • AWT component : Visual components , Container components , Menu components. • FileDialog box : File Open dialog box , File Save dialog box. • Canvas is used to create custom drawing. • ScrollPane can contain child component having dimensions greater than the it. • AWT Container Components : Applet, Frame, Panel, Dialog. • appletrunner.exe can be used to execute applet while developing. • Applet can not open socket connection to any one other than from where it is down loaded. • The Graphics class is the abstract base class for all graphics contexts. • Now in next Topic “Events” we will learn about how to handle user interaction with AWT components
9.0 Events : Overview • Introduction • Platform-independent class • Encapsulates events from the platform's Graphical User Interface • Event handling using Listeners and Adapters • Java uses Event Delegation Model for handling events. • Objective After completing this Topic, you will be able to capture and handle AWT Component Events using Listeners/Adapters . In this Topic we will cover • Event Delegation Model • Event Hierarchy • Event Listeners • Event Adapters
Event Delegation Model Event Delegation Model : Event delegation model means Events which are generated by Event Source for Event Receiver are processed by Event Listener. Event Source Receiver Event Listener
Event Hierarchy Java.util.EventObject Java.awt.AWTEvent ActionEvent AdjustmentEvent ComponentEvent TextEvent ItemEvent InputEvent WindowEvent PaintEvent ContainerEvent FocusEvent MouseEvent KeyEvent
Event Listeners • Event Listener • Event Handler • Contains different methods to handle different event • Add method of syntax add<Listener Name>to add listener to component • e.g. addActionListener()
Event Listeners Table : Event Listener Interfaces and their methods Continued …
Event Listeners Table : Event Listener Interfaces and their methods
Event Listeners • Adding Listener to component : Method 1 • // Test.java • import java.awt.*; • import java.awt.event.*; • public class Test extends Frame{ • public static void main(String args[]) { • Frame mainFrame =new Test (); • myWinList myWL=new myWinList(); • mainFrame.setVisible(true); • mainFrame.setBounds(10,10,200,200); • mainFrame.addWindowListener(myWL); • } • }