a brief introduction to java AWT and graphics programming and also covers topics included with layouts and components.
Size: 616.58 KB
Language: en
Added: Feb 27, 2017
Slides: 76 pages
Slide Content
BY M.S.MANOJ P.MASHILAMANI U.SHANMUGARAJAN
Abstract Window Toolkit (AWT) is an API to develop GUI or window – based applications in java. A graphical user interface is built of graphical elements called components. Typical components include such items as buttons, scrollbars, and text fields. Java AWT Components are platform dependent that is components are displayed according to the view of operating system. The Container class is a subclass of Component. Container class used to display non-container class. In java GUI can be design using some predefined classes. All these classes are defined in java.awt package. INTRODUCTION
java.awt class The AWT provides nine basic non-container component and three container classes.
Container class 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. Frame - The Frame is the container that contain title bar and can have menu bars. It can have other components like button, text field etc. Panel - The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button, text field and etc. Canvas - It represents a rectangular area where application can draw something or can receive inputs created by user. Before adding the components that make up a user interface, the programmer must create a container.
Creating the Frame Create a subclass of Frame override any of the standard window methods,such as init(),start(),stop(),and paint(). implement the windowClosing () method of the windowlistener interface . Calling setVisible (false)when the window is closed. Once you have defined a Frame subclass,you can create an object of that class.But it will note be initially visible When created,the window is given a default height and width You can set the size of the window explicitly by calling the following method void setSize ( int height,int width); void setSize (dimension d); dimension d=new dimension(400,400);
Frame Methods setTitle (String) - used to set display user defined message on title bar. setBackground (color) - used to set background color. setForeground (color) - used to set Foreground or text color. setSize (dimension) - set the width and height for frame setVisible ( boolean ) - set frame is visible or not. setLayout () - used to set any layout to the frame . add(component) - add component to the frame.
Frame example import java.awt.*; import java.awt.event .*; import java.applet .*; class SampleFrame extends Frame { SampleFrame (String title) { super(title); MyWindowAdapter adapter = new MyWindowAdapter (this); addWindowListener (adapter); } public void paint(Graphics g) { g.drawString ("This is in frame window", 40, 40); } } class MyWindowAdapter extends WindowAdapter { SampleFrame sf ; public MyWindowAdapter ( SampleFrame sf ) { this.sf = sf ; }
Frame example (cont.,) public void windowClosing ( WindowEvent we) { sfsetVisible (false); } } public class testFrame extends Applet { Frame f; public void init() { f = new SampleFrame ("A Frame Window"); f.setSize (500, 500); f.setVisible (true); } public void start() { f.setVisible (true); } public void stop() { f.setVisible (false); } }
OUTPUT
Event : An event is an Object that describes a state change in a Source. Some of the activities that causes event to be generated are : * Pressing a Button. * Entering a character through Key Board. * Selecting an item form a list etc. Event Source : A source is an object that generates an event. Some general Event sources are, Buttons Checkbox List Text Items EVENT HANDLING
Here is a general form for adding a listener to an event source : public void addTypeListener ( TypeEvent e) Here, type is the name of the event. e is the reference of the event listener Event Listener A Listener is an object that is notified when an event occurs. For example mouseMotionListener interface define two events: When mouse is dragged. When mouse is moved. For implementing event listener we have to import the following statement: import java.awt.event .*; EVENT HANDLING (Cont)
Components defined in the AWT generate AWTEvents Identify which events you wish to listen for (some components generate more than one type of event) Identify the Listener class which Listens for that event Once we have identified the Listener interface, implement the Listener interface Our listener class must register with the component to received events Call the addXXXListener method where XXX is the Event type. HOW TO USE EVENTS
The following is a list of events in the java.awt.event package : ActionEvent - Action has occurred ( eg . Button pressed ) AdjustmentEvent - "Adjustable" Component changed ComponentEvent - Component Changed ContainerEvent - Container changed (add or remove) FocusEvent - Focus Changed ItemEvent - Item Selected or Deselected KeyEvent - Keyboard event MouseEvent - Mouse event TextEvent - Text Changed events WindowEvent - Window related Events AWT EVENT
The Following events have Listeners associated with them : ActionEvent - ActionListener AdjustmentEvent - AdjustmentListener ComponentEvent - ComponentListener ContainerEvent - ContainerListener FocusEvent - FocusListener ItemEvent - ItemListener KeyEvent - KeyListener MouseEvent - MouseListener - MouseMotionListener TextEvent - TextListener WindowEvent - WindowListener LISTENER INTERFACE
The ActionEvent is generated when button is clicked or the item of a list is double clicked. To write an Action Listener,follow the steps given below: First declare an event handler class and specify that the class either implements an ActionListener interface or extends a class that implements an ActionListener interface. For example public class MyClass implements ActionListener { //abstract methods of ActionListener inteface } ActionEvent
ActionEvent Listener (cont) Register an instance of the event handler class as a listener on one or more components. For example: someComponent.addActionListener ( instanceOfMyClass ) Include code that implements the methods in listener interface. public void actionPerformed ( ActionEvent e) { if( e.getSouce ()== someComponent ) { //code that reacts to the action } }
On entering the character from any source generates the key event.This interface has 3 methods. These are public void keyTyped ( KeyEvent ae ) { //active on typing a code….. } public void keyPressed ( KeyEvent ae ) { //active on pressing a key…… } public void keyReleased ( KeyEvent ae ) { //active on realesing a key….. } KeyEvent
import java.awt.*; import java.awt.event .*; import java.applet .*; public class Key extends Applet implements KeyListener { int X=20, Y=30; String msg =" KeyEvents --->"; public void init() { addKeyListener (this); setBackground ( Color.green ); setForeground ( Color.blue ); } public void keyPressed ( KeyEvent k) { showStatus (" KeyDown "); int key= k.getKeyCode (); Key Event example
switch (key) { case KeyEvent.VK_UP : //constant for non- numpad up arrow key showStatus ("Move to Up"); break ; case KeyEvent.VK_DOWN : //constant for non- numpad down arrow key showStatus ("Move to Down"); break ; case KeyEvent.VK_LEFT : //constant for non- numpad left arrow key showStatus ("Move to Left"); break ; case KeyEvent.VK_RIGHT : //constant for non- numpad right arrow key showStatus ("Move to Right"); break ; } repaint(); } Key Event example
public void keyReleased ( KeyEvent k) { showStatus ("Key Up"); } public void keyTyped ( KeyEvent k) { OUTPUT msg += k.getKeyChar (); repaint(); } public void paint(Graphics g){ g.drawString ( msg,X,Y ); } } Key Event example
This event indicates a mouse action occurred in a component. This class has 5 interface method as follows : public void mousePressed ( MouseEvent e) {….} Called just after the user presses a mouse button while the cursor is over the listened-to component. public void mouseReleased ( MouseEvent e) {...} Called just after the user releases a mouse button after a mouse press over the listened-to component public void mouseClicked ( MouseEvent e) {…} Called just after the user clicks the listened-to component. public void mouseEntered ( MouseEvent e) {…….} Called just after the cursor enters the bounds of the listened-to component. public void mouseExited ( MouseEvent e) {……..} Called just after the cursor exits the bounds of the listened-to component. Mouse Event
The interface MouseMotionEvent indicates a mouse action occurred in a component. This low level event is generated by a component object when mouse is dragged or moved. This class provides 2 interface methods: mouseDragged Method: executed when mouse is dragged over the listened-to component.. mouseMoved Method: executed when mouse is moved over the listened-to component … MouseMotionEvent
This class provide two interface methods: focusGained : Called just after the listened-to component gets the focus. focusLost : Called just after the listened-to component Loses the focus. FocusEvent
import java.awt.*; import java.awt.event .*; public class FocusListenertest extends Frame implements FocusListener { //initialization occur… public FocusListenertest () { Label l; add(b1=new Button ("First"),"South"); add(b2=new Button ("Second"),"North"); add(l); b1.addFocusListener(this); b2.addFocusListener(this); setSize (200,200); Example
} public void focusGained ( FocusEvent fe ) { if( fe.getSource ()==b1) { l.setText ("focus gained of first & Lost of second"); } public void focusLost ( FocusEvent fe ) { if( fe.getSource ()==b1) { l.setText ("focus Lost of First & Gained of Second "); } Example
OUTPUT
OUTPUT
This class provide 8 interface methods: windowOpened : Called just after the listened-to window has been shown for the first time. windowClosing : Called in response to a user request for the listened-to window to be closed.To actually close the window ,the listener should invoke the windowsdispose or setVisible ( fasle ) method. windowClosed : Called just after the listened-to window has closed. windowIconified : Called just after the listened-to window is iconified . windowDeicoified : Called just after the listened-to window is deiconified . WindowEvent Listener
windowActivated and windowDeactivated : Called just after the listened-to window is activated or deactivated, respectively. These methods are not sent to windows that are not frames or dialogs. we use windowGainedFocus andwindowLostFocus methods to determine when a window gains or loses the focus. Window Event Class
This class provide one interface method: itemStateChanged : Called just after a state change in the listened-to component. ItemEvent Class
Graphics Programming The AWT supports a rich assortment of graphics methods.All graphics are drawn relative to a window. Coordinates are specified in pixels.
Coordinate Systems Each pixel can be identified using a two-dimensional coordinate system When referring to a pixel in a Java program, we use a coordinate system with the origin in the top-left corner Y X (0, 0) ( 100, 40) 100 40
Drawing Shapes A shape can be filled or unfilled, depending on which method is invoked The method parameters specify coordinates and sizes Shapes with curves, like an oval, are usually drawn by specifying the shape’s bounding rectangle An arc can be thought of as a section of an oval
Drawing a Line X Y 10 20 150 45 g.drawLine ( int startX,int startY,int endX,int endY ); g.drawLine (10, 20, 150, 45);
Drawing a Rectangle X Y g.drawRect ( int top,int left,int width,int height); g.drawRect (50, 20, 100, 40); 50 20 100 40
Drawing an Oval X Y g.drawOval ( int top,int left,int width,int height); g.drawOval (175, 20, 50, 80); 175 20 50 80 bounding rectangle
Drawing an arc X Y g.drawArc ( int x,int y,int width,int height,int sa,int aa ); g.drawArc (175, 20, 50, 80,0,90); 175 20 50 80 bounding rectangle
The Color Class Colors in java are in java.awt.Color class Class Constructor Color( int r, int g , int b) Creates an RGB color with specified red,green and blue values in the range 0 to 255 RGB Value 0, 0, 0 0, 0, 255 0, 255, 255 255, 200, 0 255, 255, 255 255, 255, 0 Object Color.black Color.blue Color.cyan Color.orange Color.white Color.yellow
The Color Class methods Method name Meaning getBlue () getGreen () getRed () gets the blue component gets the green component gets the red component getColor (String) Gets the specified color property getColor ( int ) Gets the specified color property of the color value getRGB () Gets the RGB value representing the color in the default RGB color model
Fonts The AWT supports multiple type fonts.fonts have family name,a logical font name, and a face name. Fonts are encapsulated by the Font class. Font(String name,int fontStyle,int size); Variable Meaning String name Name of the font Float point size Size of the font in points Int size Size of the font in points Int style Font style
The FONt Class Method Description static Font decode(String str ) Returns a font given its name. boolean equals(Object FontObj ) Returns true if the FontObj equals to current Font otherwise it returns false. String getFontName () Returns the face name of current font String getName () Returns the logical name of the font. int getSize () Returns the size Int getStyle () returns the style values boolean isBold () Returns true it the font includes the BOLD style value, otherwise false. boolean isItalic Returns true it the font includes the ITALIC style value, otherwise false. boolean isPlain Returns true it the font includes the PLAIN style value, otherwise false. String toSring () Returns the string equivalent of the invoking font.
Creating the Font To use new font, we must first construct a Font object that describes that font. Font(String fontName,int fontStyle,int size) fontName ~ name of the font fontStyle ~ Font.PLAIN , Font.BOLD , Font.ITALIC . To combine use pipeline( | ). Set the font to current program by calling the method Void setFont (Font fontObj );
Color and Font example import java.awt.*; import java.applet .*; public class FontDemo extends Applet { Font f1; Color c1,c2; public void init(){ c1=new Color(100,120,100); c2=new Color(140,0,0); f1=new Font(“Arial”,Font.BOLD|Font.ITALIC,40); setBackground (c1); setForeground (c2); setFont (f1); }
output public void paint(Graphics g) { g.drawString (“Hello World”,60,40); } } Color and Font example
AWT Controls AWT Supports the following types of controls. Label List Button Scroll bar Check box Text box Check box Group Text area Choice list To add controls you must create an window and add by following method. Component .add( ComponentObj ); To remove call the following method void remove( ComponentObj );
Label A label displays a single line of read only text ,the label cannot changed by the end user anyway. Creating the Label The following constructor used to create the Label Label(); Label(String text); Label(String text,int alignment); the value of alignment must be one of these three constants : Label.LEFT , Label.RIGHT , Label.CENTER .
Label Set the text of the label by calling void setText (String str ); Obtain the current label text by calling String getText () Set the Alignment of the label by calling Void setAlignment ( int align) Obtain the current label Alignment by calling int getAlignment ()
This class represents a push-button which displays some specified text. When a button is pressed, it notifies its Listeners. (More about Listeners in the next chapter). To be a Listener for a button, an object must implement the ActionListener Interface. Panel aPanel = new Panel(); Button okButton = new Button("Ok"); Button cancelButton = new Button("Cancel"); aPanel.add ( okButton )); aPanel.add ( cancelButton )); okButton.addActionListener (this); cancelButton.addActionListener (this); Buttons
This class is a Component which displays a list of Strings. The list is scrollable, if necessary. Sometimes called Listbox in other languages. Lists can be set up to allow single or multiple selections. The list will return an array indicating which Strings are selected List aList = new List(); aList.add ("Calgary"); aList.add ("Edmonton"); aList.add ("Regina"); aList.add ("Vancouver"); aList.setMultipleMode (true); List
This class represents a GUI checkbox with a textual label. The Checkbox maintains a boolean state indicating whether it is checked or not. If a Checkbox is added to a CheckBoxGroup , it will behave like a radio button. Checkbox creamCheckbox = new CheckBox ("Cream"); Checkbox sugarCheckbox = new CheckBox ("Sugar"); [ ] if ( creamCheckbox.getState ()) { coffee.addCream (); } Checkbox
This class represents a dropdown list of Strings. Similar to a list in terms of functionality, but displayed differently. Only one item from the list can be selected at one time and the currently selected element is displayed. Choice aChoice = new Choice(); aChoice.add ("Calgary"); aChoice.add ("Edmonton"); aChoice.add ("Alert Bay"); [ ] String selectedDestination = aChoice.getSelectedItem (); Choice
This class displays a single line of optionally editable text. This class inherits several methods from TextComponent . This is one of the most commonly used Components in the AWT TextField emailTextField = new TextField (); TextField passwordTextField = new TextField (); passwordTextField.setEchoChar ("*"); […] String userEmail = emailTextField.getText (); String userpassword = passwordTextField.getText (); Text Field
This class displays multiple lines of optionally editable text. This class inherits several methods from TextComponent . TextArea also provides the methods: appendText (), insertText () and replaceText () // 5 rows, 80 columns TextArea fullAddressTextArea = new TextArea (5, 80); [ ] String userFullAddress = fullAddressTextArea.getText (); Text Area
Since the Component class defines the setSize () and setLocation () methods, all Components can be sized and positioned with those methods. Problem: the parameters provided to those methods are defined in terms of pixels. Pixel sizes may be different (depending on the platform) so the use of those methods tends to produce GUIs which will not display properly on all platforms. Solution: Layout Managers. Layout managers are assigned to Containers. When a Component is added to a Container, its Layout Manager is consulted in order to determine the size and placement of the Component. NOTE: If you use a Layout Manager, you can no longer change the size and location of a Component through the setSize and setLocation methods. Layout Managers
There are several different LayoutManagers , each of which sizes and positions its Components based on an algorithm: FlowLayout BorderLayout GridLayout For Windows and Frames, the default LayoutManager is BorderLayout . For Panels, the default LayoutManager is FlowLayout . Layout Managers (cont)
The algorithm used by the FlowLayout is to lay out Components like words on a page: Left to right, top to bottom. It fits as many Components into a given row before moving to the next row. Panel aPanel = new Panel(); aPanel.add (new Button("Ok")); aPanel.add (new Button("Add")); aPanel.add (new Button("Delete")); aPanel.add (new Button("Cancel")); Flow Layout
The BorderLayout Manager breaks the Container up into 5 regions (North, South, East, West, and Center ). When Components are added, their region is also specified: Frame aFrame = new Frame(); aFrame.add ("North", new Button("Ok")); aFrame.add ("South", new Button("Add")); aFrame.add ("East", new Button("Delete")); aFrame.add ("West", new Button("Cancel")); aFrame.add (" Center ", new Button("Recalculate")); Border Layout
The regions of the BorderLayout are defined as follows: Center North South West East Border Layout (cont)
The GridLayout class divides the region into a grid of equally sized rows and columns. Components are added left-to-right, top-to-bottom. The number of rows and columns is specified in the constructor for the LayoutManager . Panel aPanel = new Panel(); GridLayout theLayout = new GridLayout (2,2); aPanel.setLayout ( theLayout ); aPanel.add (new Button("Ok")); aPanel.add (new Button("Add")); aPanel.add (new Button("Delete")); aPanel.add (new Button("Cancel")); Grid Layout
Menu Bar and Menu A menu bar displays a list of top-level menu choices Each choice is associated with a drop-down menu This concept is implemented in Java by the following classes MenuBar Menu MenuItem
Menu Bar and Menu (cont ) In general, a menu bar contains one or more Menu objects Each Menu object contains a list of MenuItem objects Each MenuItem object represents something that can be selected by the user
Menubar and menu (cont) Following are the constructors for Menu: Menu( ) Menu(String optionName ) Menu(String optionName , boolean removable) Here, optionName specifies the name of the menu selection If removable is true, the pop-up menu can be removed and allowed to float free Otherwise, it will remain attached to the menu bar
Menubar and menu (cont) MenuItem defines these constructors MenuItem ( ) MenuItem (String itemName ) MenuItem (String itemName , MenuShortcut keyAccel ) Here, itemName is the name shown in the menu keyAccel is the menu shortcut for this item
Sample Program // Illustrate menus. import java.awt.*; import java.awt.event .*; import java.applet .*; /* <applet code=" MenuDemo " width=250 height=250 > </applet> */ // Create a subclass of Frame class MenuFrame extends Frame { String msg = ""; CheckboxMenuItem debug, test; MenuFrame (String title) { super(title); // create menu bar and add it to frame MenuBar mbar = new MenuBar (); setMenuBar (mbar);
Program (cont.) // create the menu items Menu file = new Menu("File"); MenuItem item1, item2, item3, item4, item5; file.add (item1 = new MenuItem ("New...")); file.add (item2 = new MenuItem ("Open...")); file.add (item3 = new MenuItem ("Close")); file.add (item4 = new MenuItem ("-")); file.add (item5 = new MenuItem ("Quit...")); mbar.add (file); Menu edit = new Menu("Edit"); MenuItem item6, item7, item8, item9; edit.add (item6 = new MenuItem ("Cut")); edit.add (item7 = new MenuItem ("Copy")); edit.add (item8 = new MenuItem ("Paste")); edit.add (item9 = new MenuItem ("-"));
Program (cont.) Menu sub = new Menu("Special"); MenuItem item10, item11, item12; sub.add (item10 = new MenuItem ("First")); sub.add (item11 = new MenuItem ("Second")); sub.add (item12 = new MenuItem ("Third")); edit.add (sub); // these are checkable menu items debug = new CheckboxMenuItem ("Debug"); edit.add (debug); test = new CheckboxMenuItem ("Testing"); edit.add (test); mbar.add (edit); // create an object to handle action and item events MyMenuHandler handler = new MyMenuHandler (this);
Program (cont.) // register it to receive those events item1.addActionListener(handler); item2.addActionListener(handler); item3.addActionListener(handler); item4.addActionListener(handler); item5.addActionListener(handler); item6.addActionListener(handler); item7.addActionListener(handler); item8.addActionListener(handler); item9.addActionListener(handler); item10.addActionListener(handler); item11.addActionListener(handler); item12.addActionListener(handler); debug.addItemListener (handler); test.addItemListener (handler);
Program (cont.) // create an object to handle window events MyWindowAdapter adapter = new MyWindowAdapter (this); // register it to receive those events addWindowListener (adapter); } public void paint(Graphics g) { g.drawString ( msg , 10, 200); if( debug.getState ()) g.drawString ("Debug is on.", 10, 220); else g.drawString ("Debug is off.", 10, 220); if( test.getState ()) g.drawString ("Testing is on.", 10, 240); else g.drawString ("Testing is off.", 10, 240); } }
Program (cont.) class MyWindowAdapter extends WindowAdapter { MenuFrame menuFrame ; public MyWindowAdapter ( MenuFrame menuFrame ) { this.menuFrame = menuFrame ; } public void windowClosing ( WindowEvent we) { menuFrame.setVisible (false); } } class MyMenuHandler implements ActionListener , ItemListener { MenuFrame menuFrame ; public MyMenuHandler ( MenuFrame menuFrame ) { this.menuFrame = menuFrame ; }
Program (cont.) // Handle item events public void itemStateChanged ( ItemEvent ie ) { menuFrame.repaint (); } } // Create frame window. public class MenuDemo extends Applet { Frame f; public void init() { f = new MenuFrame ("Menu Demo"); int width = Integer.parseInt ( getParameter ("width")); int height = Integer.parseInt ( getParameter ("height")); setSize (new Dimension(width, height)); f.setSize (width, height); f.setVisible (true); }
public void start() { f.setVisible (true); } public void stop() { f.setVisible (false); } } Sample output is shown here Fig. 74.1 Output of MenuDemo Program (cont.)