Download - Chapter_8_9_10_Java GUI .ppt
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
1/89
Java
Knowledge Level:
Basic / Intermediate
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
2/89
2Copyright 2004, Cognizant Academy, All Rights Reserved
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 Components2 . Visual Components
3 . The Container Components
4 . The Menu
5 . Utility classes
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
3/89
3Copyright 2004, Cognizant Academy, All Rights Reserved
AWT and AWT Components
Java components are implemented by help of supperclasses thejava.awt.Component and java.awt.MenuComponents.
AWT component categories : 1] Visual components
2] Container components
3] Menu components
Component
Visual Component Container Component Menu Component
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
4/89
4Copyright 2004, Cognizant Academy, All Rights Reserved
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
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
5/89
5Copyright 2004, Cognizant Academy, All Rights Reserved
AWT and AWT Components
Screen snapshots for setEnabled method Button
button.setEnabled(true);
figure 1
button.setEnabled(false);
figure 2
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
6/89
6Copyright 2004, Cognizant Academy, All Rights Reserved
Visual Components
AWT Visual Components Button
Label
Checkbox
TextField TextArea
Choice
List
FileDialog
Canvas
ScrollPane
Scrollbar
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
7/897Copyright 2004, Cognizant Academy, All Rights Reserved
Visual Components
This is the sample program to create components.
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
1 2
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
8/898Copyright 2004, Cognizant Academy, All Rights Reserved
Button The button class implements push button
Button button = new Button("Click me!");
Constructor :
public Button()
public Button(String label)
Visual Components
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
9/899Copyright 2004, Cognizant Academy, All Rights Reserved
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
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
10/8910Copyright 2004, Cognizant Academy, All Rights Reserved
Checkbox The Checkbox is a kind of button with two states. Two states aretrue (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
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
11/8911Copyright 2004, Cognizant Academy, All Rights Reserved
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
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
12/8912Copyright 2004, Cognizant Academy, All Rights Reserved
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
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
13/8913Copyright 2004, Cognizant Academy, All Rights Reserved
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
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
14/8914Copyright 2004, Cognizant Academy, All Rights Reserved
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
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
15/8915Copyright 2004, Cognizant Academy, All Rights Reserved
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
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
16/8916Copyright 2004, Cognizant Academy, All Rights Reserved
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
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
17/8917Copyright 2004, Cognizant Academy, All Rights Reserved
ScrollPane Form of panel Can contain child component having dimensions greater than the
ScrollPane
Scroll pane provides horizontal or/and vertical scrollbars
//Code snippetScrollPane 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
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
18/8918Copyright 2004, Cognizant Academy, All Rights Reserved
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)
initial value of the scroll bar
scroll bar thumb
Range of scrollbar
Visual Components
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
19/89
19Copyright 2004, Cognizant Academy, All Rights Reserved
Container Components
AWT Container Components Applet
Frame
Panel
Dialog
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
20/89
20Copyright 2004, Cognizant Academy, All Rights Reserved
Container Components
Hierarchy for Container components
Container
Component
Dialog
WindowPanel
FrameApplet
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
21/89
21Copyright 2004, Cognizant Academy, All Rights Reserved
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
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
22/89
22Copyright 2004, Cognizant Academy, All Rights Reserved
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
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
23/89
23Copyright 2004, Cognizant Academy, All Rights Reserved
Applet example ://FirstApplet.javaimport 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);
}
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
1 2
Continue
Container Components
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
24/89
24Copyright 2004, Cognizant Academy, All Rights Reserved
Applet life cycle Init Start
Stop
Destroy
Init
Stop Destroy
StartApplet Loaded
Window Closed
Window
Minimized
/Closed
Window
Maximized
Container Components
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
25/89
25Copyright 2004, Cognizant Academy, All Rights Reserved
HTML Code to use applet in HTML file
Container Components
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
26/89
26Copyright 2004, Cognizant Academy, All Rights Reserved
Figure 1 Figure 2
Container Components
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
27/89
27Copyright 2004, Cognizant Academy, All Rights Reserved
Figure 1
Container Components
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
28/89
28Copyright 2004, Cognizant Academy, All Rights Reserved
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 withno label.
public Button(String label) Creates abutton with the indicated label.
Code snippet in HTML file
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
29/89
29Copyright 2004, Cognizant Academy, All Rights Reserved
Figure 2
Container Components
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
30/89
30Copyright 2004, Cognizant Academy, All Rights Reserved
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>]
. . . . . .
Container Components
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
31/89
31Copyright 2004, Cognizant Academy, All Rights Reserved
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
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
32/89
32Copyright 2004, Cognizant Academy, All Rights Reserved
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
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
33/89
33Copyright 2004, Cognizant Academy, All Rights Reserved
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.
Container Components
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
34/89
34Copyright 2004, Cognizant Academy, All Rights Reserved
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
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
35/89
35Copyright 2004, Cognizant Academy, All Rights Reserved
The Menu
Menu bar
Menu Items
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
36/89
36Copyright 2004, Cognizant Academy, All Rights Reserved
// 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
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);
}
}
1 2
The Menu
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
37/89
37Copyright 2004, Cognizant Academy, All Rights Reserved
Figure 1 Figure 2
Figure 3
The Menu
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
38/89
38Copyright 2004, Cognizant Academy, All Rights Reserved
A PopupMenu class implements a menu which can be dynamicallypopped up at a specified position within a component.
public class PopupMenu extends Menu
As the inheritance hierarchy suggests, a PopupMenu can be usedanywhere 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.
The Menu
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
39/89
39Copyright 2004, Cognizant Academy, All Rights Reserved
Utility classes
VectorsDimensionInsets
Point
Polygon
Rectangle
Shape
ColorColor
SystemColor
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
40/89
40Copyright 2004, Cognizant Academy, All Rights Reserved
Utility classes
ResourceCursorFont
FontMetrics
Graphics
Image
PrintGraphics
PrintJob
Toolkit
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
41/89
41Copyright 2004, Cognizant Academy, All Rights Reserved
Vectors Dimension :The Dimension class encapsulates the width and height of acomponent 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 spacecan 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
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
42/89
42Copyright 2004, Cognizant Academy, All Rights Reserved
Color Color : This class encapsulate colors using the RGB format.
SystemColor :A class to encapsulate symbolic colors representing thecolor of native GUI objects on a system.
Resource
Cursor :A class to encapsulate the bitmap representation of the mousecursor.
Font :The Font class represents fonts, which are used to render text onscreen.
FontMetrics : The FontMetrics class defines a font metrics object, whichencapsulates information about the rendering of a particular font on a screen.
Utility classes
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
43/89
43Copyright 2004, Cognizant Academy, All Rights Reserved
Graphics : The Graphics class is the abstract base class for all graphicscontexts that allow an application to draw onto components.
Image : The abstract class Image is the superclass of all classes thatrepresent graphical images.
Toolkit : This class is the abstract superclass of all actual implementations ofthe Abstract Window Toolkit
Note : Example code snippets for Dimension, Point, Polygon, Rectangle,
Color,Font, Graphics, Image, Toolkit are in Topic Painting
Utility classes
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
44/89
44Copyright 2004, Cognizant Academy, All Rights Reserved
AWT Components : Summary
The AWT i.e. Abstract Windowing Toolkit provides classes for
developing GUIThe 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 fromwhere 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
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
45/89
45Copyright 2004, Cognizant Academy, All Rights Reserved
Which are the categories for AWT Components ?
Give three methods of AWT Component which are inherited from
Component ?
What is difference between setBounds() and setSize() ?
What are the types of FileDialog ?
Where we use Canvas ?
What is use of ScrollPane?
Which are AWT Container Components ?
What is use of appletrunner.exe ?
Where applet can open socket connection ?
Where the Graphics class is used ?
: Quiz
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
46/89
46Copyright 2004, Cognizant Academy, All Rights Reserved
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
47/89
47Copyright 2004, Cognizant Academy, All Rights Reserved
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
1. Event Delegation Model2. Event Hierarchy
3. Event Listeners
4. Event Adapters
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
48/89
48Copyright 2004, Cognizant Academy, All Rights Reserved
Event Delegation Model
Event Delegation Model : Event delegation model means Eventswhich are generated by Event Source for Event Receiver are
processed by Event Listener.
Source Receiver
Listener
Event
Event
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
49/89
49Copyright 2004, Cognizant Academy, All Rights Reserved
Event Hierarchy
Java.util.EventObject
Java.awt.AWTEvent
ItemEventComponentEventActionEvent AdjustmentEvent
MouseEvent KeyEvent
TextEvent
PaintEventInputEventContainerEvent FocusEvent WindowEvent
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
50/89
50Copyright 2004, Cognizant Academy, All Rights Reserved
Event Listeners
Event Listener
Event Handler
Contains different methods to handle different event
Add method of syntax addto add listener to
component
e.g. addActionListener()
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
51/89
51Copyright 2004, Cognizant Academy, All Rights Reserved
Event Listeners
Table : Event Listener Interfaces and their methods
Continued
Interface Interface Methods Add Method Components
WindowListener windowActivated ( WindowEvent )
windowClosed ( WindowEvent )
windowClosing ( WindowEvent )
windowDeactivated ( WindowEvent )
windowDeiconified ( WindowEvent )
windowIconified ( WindowEv
addWindiwListener( ) Frame ,
Act ionListener actionPerformed ( ActionEvent ) addActionListener( ) Button , List,
MenuItem, TextField
AdjustmentEvent adjustmentValueChanged ( AdjustmentEvent ) addAdjustmentListener( ) Scrollbar
ComponentListener componentMoved ( ComponentEvent )
componentHidden ( ComponentEvent )
componentResized ( ComponentEvent )
componentShown ( ComponentEvent )
addComponentListener( ) Canvas
ContainerListener componentAdded ( ContainerEvent )
componentRemoved ( ContainerEvent )
addContainerListener( ) Frame , Panel
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
52/89
52Copyright 2004, Cognizant Academy, All Rights Reserved
Table : Event Listener Interfaces and their methods
FocusListener focusGained( FocusEvent )
focusLost( FocusEvent )
addFocusListener( ) Frame , Button,
Canvas
ItemListener itemStateChanged ( ItemEvent ) addItemListener( ) Checkbox, Choice, List
KeyListener keyPressed ( KeyEvent )
keyReleased ( KeyEvent )
keyTyped ( KeyEvent )
addKeyListener( ) Button , Canvas, Panel
MouseListener mouseClicked ( MouseEvent )
mouseEntered ( MouseEvent )
mouseExited ( MouseEvent )
mousePressed ( MouseEvent )
mouseReleased ( MouseEvent )
addMouseListener( ) Button , Canvas, Panel
MouseMotionListener mouseDragged (MouseEvent )
mouseMoved ( MouseEvent )
addMouseMotionListener( ) Button , Canvas, Panel
TextListener textValueChanged ( TextEvent ) addTextListener( ) TextComponent
Interface Interface Methods Add Method Components
Event Listeners
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
53/89
53Copyright 2004, Cognizant Academy, All Rights Reserved
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);
}
}
Event Listeners
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
54/89
54Copyright 2004, Cognizant Academy, All Rights Reserved
// myWinList class implements WindowListner
class myWinList implements WindowListener{
public void windowActivated ( WindowEvent we) {}
public void windowClosed ( WindowEvent we) {}
public void windowClosing ( WindowEvent we) {System.exit(0);}public void windowDeactivated ( WindowEvent we){}
public void windowDeiconified ( WindowEvent we){}
public void windowIconified ( WindowEvent we) {}
public void windowOpened ( WindowEvent we) {}
}
Event Listeners
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
55/89
55Copyright 2004, Cognizant Academy, All Rights Reserved
Adding Listener to component : Method 2
// Test.java
import java.awt.*;
import java.awt.event.*;
public class Test extends Frame implements WindowListener{public static void main(String args[]) {
Frame mainFrame =new Test ();
myWinList myWL=new myWinList();
mainFrame.setVisible(true);
mainFrame.setBounds(10,10,200,200);
}Test(){
addWindowListener(this);
}
Event Listeners
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
56/89
56Copyright 2004, Cognizant Academy, All Rights Reserved
public void windowActivated ( WindowEvent we) {}
public void windowClosed ( WindowEvent we) {}
public void windowClosing ( WindowEvent we) {System.exit(0);}
public void windowDeactivated ( WindowEvent we){}
public void windowDeiconified ( WindowEvent we){}
public void windowIconified ( WindowEvent we) {}public void windowOpened ( WindowEvent we) {}
} // End Test
Event Listeners
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
57/89
57Copyright 2004, Cognizant Academy, All Rights Reserved
Example : How to Use ActionListener for Buttonimport java.awt.*;
import java.awt.event.*;
public class Test extends Frame {
public static void main(String args[]) {
Frame mainFrame =new Test ();
myAction myA = new myAction();Button b1=new Button("Button 1");
mainFrame.setVisible(true);
mainFrame.setBounds(10,10,200,200);
mainFrame.setLayout(null);
b1.setBounds(40,100,80,40);
b1.addActionListener(myA);
mainFrame.add(b1);
} //main
} //Class Test
Event Listeners
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
58/89
58Copyright 2004, Cognizant Academy, All Rights Reserved
class myAction implements ActionListener {
public void actionPerformed ( ActionEvent ae){
System.out.println(ae.getActionCommand());
}
} //Class myAction
Output after pressing button b1:
Event Listeners
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
59/89
59Copyright 2004, Cognizant Academy, All Rights Reserved
Event Adapters
Event Adapters :Empty implementation of Listener
interface
Example :import java.awt.*;
import java.awt.event.*;
public class Test extends Frame {
public static void main(String args[]) {Frame mainFrame =new Test ();
myWinAd myWA = new myWinAd ();
mainFrame.setVisible(true);
mainFrame.setBounds(10,10,200,200);
mainFrame.addWindowListener(myWA);
}
}//Class Test End
class myWinAd extends WindowAdapter {
public void windowClosing ( WindowEvent we){ System.exit(0); }
} //Class Adapter End
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
60/89
60Copyright 2004, Cognizant Academy, All Rights Reserved
Event Adapters
Adapter Class Listener Interface
WindowAdapter WindowListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListenerFocusAdapter FocusListener
Adapter classes and corresponding interfaces
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
61/89
61Copyright 2004, Cognizant Academy, All Rights Reserved
Events : Summary
Event is a platform-independent class Event handling is done by using Listeners and Adapters
Event delegation model entities : Event, Source, Receiver and Listener
Event listener Contains different methods to handle different event
Using add method of component we can add listener Event Adapters : Empty implementation of Listener interface
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
62/89
62Copyright 2004, Cognizant Academy, All Rights Reserved
: Quiz
Which are the entities in Event-Delegation model ? What is the use of event listeners ?
Which method of component is used to attach event listener to
component ?
What getActionCommand() method returns ? What are event adapters ?
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
63/89
63Copyright 2004, Cognizant Academy, All Rights Reserved
10.0 Layout Managers : Overview
Introduction
Layout Managers defines the interface to set Layout for containers
Performs layout management for the components within the
container
ObjectiveAfter completing this Topic, you will be able to create GUI with
specified appearance robust by handling runtime exceptions.
In this Topic we will cover
1. Types of Layout Managers
2. GrigBag Layout Manager
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
64/89
64Copyright 2004, Cognizant Academy, All Rights Reserved
Layout Manager Overview
Layout Manager
Defines the interface for classes that know how to lay out
Containers.
Recommend that we use layout managers
We can perform layout without them.
By setting a container's layout property to null, we make the
container use no layout manager (absolute positioning).
In absolute positioning, we must specify the size and position of
every component within that container.
Drawback of absolute positioning :It doesn't adjust well when the
top-level container is resized
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
65/89
65Copyright 2004, Cognizant Academy, All Rights Reserved
Types of Layout Managers
Types of Layout Managers
FlowLayout Manager
GridLayout Manager
BorderLayout Manager CardLayout Manager
GridBagLayout Manager
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
66/89
66Copyright 2004, Cognizant Academy, All Rights Reserved
FlowLayout Manager
Default manager type for panels and applets
Arranges components in horizontal row (left to right, starting new rows, if
necessary).
The FlowLayout class has three constructors:
public FlowLayout()
public FlowLayout(int alignment)
public FlowLayout(int alignment, int horizontalGap, int verticalGap)
Types of Layout Managers
f
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
67/89
67Copyright 2004, Cognizant Academy, All Rights Reserved
FlowLayout Manager Example
import java.awt.*;
public class Test extends Frame {
public static void main(String args[]) {
Frame mainFrame =new Test ();
myAction myA = new myAction();
mainFrame.setVisible(true);
mainFrame.setBounds(10,10,350,100);
mainFrame.setLayout(new FlowLayout()); // Important Line
mainFrame.add(new Button("Button 1"));
mainFrame.add(new Button("Button 2"));mainFrame.add(new Button("Button 3"));
mainFrame.add(new Button("Button 4"));
}
}
Types of Layout Managers
T f L M
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
68/89
68Copyright 2004, Cognizant Academy, All Rights Reserved
FlowLayout Manager Example Output
Types of Layout Managers
If we change size of windows then Output
Figure 1
Figure 2
Figure 3
T f L t M
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
69/89
69Copyright 2004, Cognizant Academy, All Rights Reserved
Types of Layout Managers
Figure 1
Figure 2
FlowLayout ManagerIf we change line commented as //Important LinemainFrame.setLayout(new FlowLayout()); mainFrame.setLayout(new FlowLayout(0));
T f L t M
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
70/89
70Copyright 2004, Cognizant Academy, All Rights Reserved
Types of Layout Managers
GridLayout Manager
Places components in a grid of cells
Each component takes all the available space within its cell
Resize the GridLayout window, changes the cell size
The GridLayout class has two constructors
public GridLayout(int rows, int columns)
public GridLayout(int rows, int columns, int horizontalGap, int verticalGap) )
T f L t M
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
71/89
71Copyright 2004, Cognizant Academy, All Rights Reserved
Types of Layout Managers
GridLayout Manager Example :
import java.awt.*;
public class Test extends Frame {
public static void main(String args[]) {
Frame mainFrame =new Test ();
myAction myA = new myAction();
mainFrame.setVisible(true);
mainFrame.setBounds(10,10,400,100);
mainFrame.setLayout(new GridLayout(0,2)); // Important Line
mainFrame.add(new Button("Button 1"));
mainFrame.add(new Button("Button 2"));
mainFrame.add(new Button("Button 3"));
mainFrame.add(new Button("Button 4"));
}
}
T f L t M
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
72/89
72Copyright 2004, Cognizant Academy, All Rights Reserved
GridLayout Manager: Example Output
Types of Layout Managers
If we change size of windows thenOutput
Figure 1
Figure 2
Figure 3
T f L t M
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
73/89
73Copyright 2004, Cognizant Academy, All Rights Reserved
GridLayout Manager : If we change line commented as //Important Line
mainFrame.setLayout(new GridLayout(0,2)); mainFrame.setLayout(new GridLayout(0,2,10,10));
Types of Layout Managers
Figure 1
Figure 2
And If we change line commented as //Important LinemainFrame.setLayout(new GridLayout(0,2)); mainFrame.setLayout(new GridLayout(0,2, 0,10));
T f L t M
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
74/89
74Copyright 2004, Cognizant Academy, All Rights Reserved
Types of Layout Managers
BorderLayout Manager
A BorderLayout has five areas : PAGE_START, PAGE_END,
LINE_START, LINE_END, and CENTER.
Instead of using PAGE_START, LINE_START, PAGE_END, LIEN_END ,
we can use NORTH, SOUTH, EAST, and WEST.
By default component will get added to the center
By default BorderLayout does not put gap between the components
Constructors :
public BorderLayout()
public BorderLayout(int horizontalgap, int verticalgap)
T f L t M
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
75/89
75Copyright 2004, Cognizant Academy, All Rights Reserved
BorderLayout ManagerExample :
import java.awt.*;
public class Test extends Frame {
public static void main(String args[]) {
// All frame creation and display code will come here
mainFrame.setLayout(new BorderLayout());mainFrame.add(new Button("Button(PAGE_START)"), BorderLayout.PAGE_START);
Button button = new Button("Button(CENTER)");
button.setSize(new Dimension(200, 100));
mainFrame.add(button, BorderLayout.CENTER);
mainFrame.add(new Button("Button(LINE_START)"), BorderLayout.LINE_START);
mainFrame.add(new Button("LongButton(PAGE_END)"), BorderLayout.PAGE_END);
mainFrame.add(new Button("5(LINE_END)"), BorderLayout.LINE_END);
}
}
Types of Layout Managers
T f L t M
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
76/89
76Copyright 2004, Cognizant Academy, All Rights Reserved
BorderLayout ManagerExample Output
Types of Layout Managers
If we change size of windows then Output
Figure 1
Figure 2
Figure 3
Types of Layout Managers
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
77/89
77Copyright 2004, Cognizant Academy, All Rights Reserved
Types of Layout Managers
Figure 1
Figure 2
BorderLayout Manager : If we change line commented as//Important Line
mainFrame.setLayout(new BorderLayout()); mainFrame.setLayout(new BorderLayout(10,10));
BorderLayout Manager : If we change line commented as //Important LinemainFrame.setLayout(new BorderLayout()); mainFrame.setLayout(new BorderLayout(0,10));
Types of Layout Managers
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
78/89
78Copyright 2004, Cognizant Academy, All Rights Reserved
Types of Layout Managers
CardLayout Manager
CardLayout treats each component in the container as a card.
Only one card is visible at a time, and the container acts as a stack of
cards.
The first component added to a CardLayout object is the visible
component when the container is first displayed. The CardLayout API :
void first(Container)
void next(Container)
void previous(Container)
void last(Container)
void show(Container, String)
Constructors :
public CardLayout()
public CardLayout(int horizontalgap, int verticalgap)
Types of Layout Managers
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
79/89
79Copyright 2004, Cognizant Academy, All Rights Reserved
CardLayout Manager
Example :import java.awt.*;
import java.awt.event.*;
public class Card extends Panel {
private Panel cardPanel = new Panel ();
private CardLayout cardLayout= new CardLayout();
private Panel controlPanel = new Panel();
private Button b1 = new Button ("Panel 1");
private Button b2 = new Button ("Panel 2");
// Constructor here
public static void main(String args[]){
Frame f= new Frame("Example");Card card = new Card (); // Check the Constructor on next slide
f.add(card);
f.pack();
f.setVisible(true);
} //Main
} //Class
Types of Layout Managers
Types of Layout Managers
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
80/89
80Copyright 2004, Cognizant Academy, All Rights Reserved
public Card(){
Panel p1 = new Panel();
Panel p2 = new Panel();
p1.add(new TextField("This is Panel 1"));
p2.add(new Button("This is Panel 2"));
cardPanel.setLayout(cardLayout);
cardPanel.add(p1,"1");
cardPanel.add(p2,"2");
add(cardPanel,BorderLayout.CENTER);
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
cardLayout.first(cardPanel);
}});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
cardLayout.last(cardPanel);
}});
Panel cp_1 = new Panel();
Panel cp_2 = new Panel();
cp1.add(b1);
cp1.add(b2);
controlPanel.add(cp1);
controlPanel.add(cp2);
add(controlPanel,BorderLayout.SOUTH);
} //Constructor
Continue
1 2
Types of Layout Managers
Types of Layout Managers
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
81/89
81Copyright 2004, Cognizant Academy, All Rights Reserved
CardLayout Manager Example Output
Types of Layout Managers
Figure 1
Figure 2
Figure 3
GridBagLayout Manager
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
82/89
82Copyright 2004, Cognizant Academy, All Rights Reserved
GridBagLayout Manager
GridBagLayout Manager
GridBagLayout is the most sophisticated, flexible layout manager
This layout manager aligns components by placing them within a
grid of cells Allows some components to span more than one cell.
GridBagConstraints class used to hold all layout position
information
Constructor :public GridBagLayout()
GridBagLayout Manager
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
83/89
83Copyright 2004, Cognizant Academy, All Rights Reserved
GridBagLayout Manager
GridBagConstraints
public GridBagConstraints(int gridx, int gridy, int gridwidth,
int gridheight, double weightx,
double weighty, int anchor, int fill,
Insets insets, int ipadx, int ipady)
Parameters:gridx - The initial gridx value.gridy - The initial gridy value.
gridwidth - The initial gridwidth value.
gridheight - The initial gridheight value.
weightx - The initial weightx value.
weighty - The initial weighty value.anchor - The initial anchor value.
fill - The initial fill value.
insets - The initial insets value.
ipadx - The initial ipadx value.
ipady - The initial ipady value.
GridBagLayout Manager
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
84/89
84Copyright 2004, Cognizant Academy, All Rights Reserved
GridBagLayout Manager
import java.awt.*;
import java.awt.event.*;
public class GB extends Panel {
private Panel p1=new Panel();
private Panel p2=new Panel();
public GB() {
p1.setLayout(new GridLayout(2,1));
p1.add(new Button("Panel1UP"));
p1.add(new Button("Panel1Down"));
p2.setLayout(new GridLayout(2,1));
p2.add(new Button("Panel2UP"));
p2.add(new Button("Panel2Down"));
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx=0;
c.gridy=0;
add(new Button("TopLeft"),c);
c.gridx=1;add(new Button("TopCentre"),c);
c.gridx=2;
add(new Button("TopRight"),c);
c.gridx=1;
c.gridy=1;
add(p1,c);
c.gridx=2;
add(p2,c);
}
public static void main(String
args[]) {Frame f=new Frame("CTS");
f.add(new GB());
f.pack();
f.setVisible(true);
}
}
1 2
Continue
GridBagLayout Manager
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
85/89
85Copyright 2004, Cognizant Academy, All Rights Reserved
GridBagLayout Manager
Figure 1: Output of previous code - Figure 2: When resized, Output is -
Figure 3: Resized window when
weightx and weighty are set to 1.0 -
Col 0 Col 1 Col 2
Row 0
Row 1
GridBagLayout Manager
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
86/89
86Copyright 2004, Cognizant Academy, All Rights Reserved
GridBagLayout Manager
Controlling the cell size for a component How to specify if a component occupies multiple cells ?
The gridwidth and gridheight parameters
Example
In the previous example if we modify the code to make panel1 occupy firstand second columns, the output will look as -
The code is like this
c.gridx=0;
c.gridy=1;
c.gridwidth=2;add(p1,c);
c.gridx=2;
c.gridwidth=1;
add(p2,c);
Col 0 Col 1 Col 2
Row 0
Row 1
S L t M
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
87/89
87Copyright 2004, Cognizant Academy, All Rights Reserved
Summary : Layout Managers
Layout Managers defines the interface for classes that know how to layout
Containers. Types of LayoutManager : FlowLayout Manager, GridLayout Manager,
BorderLayout Manager, CardLayout Manager, GridBagLayout Manager.
FlowLayout Manager is default manager type for panels and applets.
FlowLayout Manager arranges components in horizontal row .
GridLayout Manager places components in a grid of cells. In GridLayout Manager each component takes all the available space within
its cell.
BorderLayout has 5 areas: PAGE_START, PAGE_END, LINE_START,
LINE_END, and CENTER.
In BorderLayout By default component will get added to the center.
CardLayout treats each component in the container as a card.
While using CardLayout Only one card is visible at a time.
A GridBagConstraints object is associated with every component that contains
detail information regarding the position of the component.
Q i
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
88/89
88Copyright 2004, Cognizant Academy, All Rights Reserved
: Quiz
What is absolute positioning ?
Write any 3 Layout Managers ?
Which is default layout manager type for panels and applets.
Which layout manager by default arranges components horizontally ?
Where by default component will get added In BorderLayout ?
How many cards at a time are visible while using CardLayout ?
Which parameters of GridBagConstraints are used to control cell size
for components?
-
7/27/2019 Chapter_8_9_10_Java GUI .ppt
89/89