SlideShare a Scribd company logo
1 of 99
UNIT-5
 Advantages of GUI over CUI
 The AWT class hierarchy- Component, Frame
 Event handling: Delegation Event model
 Closing a frame, mouse and keyboard events
 Adapter classes
 User interface components:
 Labels, button, scrollbars
 Text components, check box, check box groups, choices
 Lists panels – ScrollPane, MenuBar, graphics
 Layout manager – layout manager types
 Concepts of Applets, differences between applets and
Applications
 Life cycle of an applet
 Types of applets, creating applets, passing parameters to applets
Advantages of GUI over CUI
Presents a user-friendly mechanism for interacting with an
application.
Built from GUI components.
It need more resources
Speed is less compare to the CUI
In a Command Line Interface, the commands are entered from
the keyboard. It is not user-friendly.
Difficult to remember commands.
It need less resources
Speed is more compare to the GUI
Most modern programs use a GUI.
 Graphical: Not just text or characters but windows, menus,
buttons, ..
 User: Person using the program
 Interface: Way to interact with the program
Graphical Elements include:
Window List
Choice Label
Menu Scrollbar
Button TextComponent etc.,
button menus title bar menu bar combo box
scroll
bars
Internet Explorer Window with GUI components
Abstract Window Toolkit (AWT)
 The AWT contains several classes and methods that allow you to
create and manage windows.
 The two most common windows are
those derived from Panel, which is used by applets, and
those derived from Frame, which creates a standard window.
 The main purpose of the AWT is to support applet windows.
 It can also be used to create stand-alone GUI applications.
AWT class hierarchy
MenuBar
Component
Container
Window Panel
Frame
Label
Button
TextComponent
TextField
TextArea
Choice
CheckBox
CheckBoxGroup
Scrollbar
MenuComponent
List
MenuItem
Menu
Dialog
Canvas
ScrollPane
Applet
Component: (java.awt)
 Component is an abstract class that encapsulates all of the attributes of a visual
component.
 It is a super class of all user interface classes.
 A component is something that can be displayed on a two-dimensional screen
and with which the user can interact.
 Attributes of a component include a size, a location, foreground and background
colors, whether or not visible etc.,
Methods defined in class Component are:
 setLocation(int, int), getLocation() ---To set and get component location
 setSize(int, int), getSize() ---To set and get component size
 setVisible() ---To show or hide the component
 setForeground(Color), getForeground() ---To set and get foreground colors
 setBackground(Color), getBackground() ---To set and get background colors
Container: (java.awt)
 Container class is a subclass of Component class.
 This is a type of component that can nest other components within it.
Ex:- Window, Frame, and panel are examples of containers.
 A Container is responsible for laying out (that is, positioning) any components
that it contains.
Methods defined in a class Container are:
 setLayout(LayoutManager) ---To set layout manager for display.
 add( Component ) ---To add component to the display.
 remove( Component ) ---To remove component from display.
Panel: (java.awt)
 The Panel class is a concrete subclass of Container class.
 A panel is a window that does not contain a title bar, or border.
 It provides space in which an application can attach any other component,
including other panels.
 It is the superclass for Applet.
 Other components can be added to a Panel object by its add() method.
 The default layout manager for a panel is the FlowLayout layout manager.
Window: (java.awt)
 The Window class creates a top-level window.
 A top-level window is not contained within any other object; it sits
directly on the desktop.
 Generally, we won’t create Window objects directly. Instead, we use a
subclass of Window called Frame.
Frame: (java.awt)
 It is a type of Window with a title bar, menu bar , borders, and resizing
corners.
Methods defined in a Frame class are:
 setTitle(String), getTitle() ---To set or get title
 setMenuBar(MenuBar) ---To set menu bar for window
Layout Manager:
 A manager is used to position and place components in a Container.
Event Handling
 It defines standard and consistent mechanisms to generate and process events.
 In this model, a source generates an event and sends it to one or more
listeners.
 The listener simply waits until it receives an event. Once received, the listener
processes the event and then returns.
 Listeners are created by implementing one or more of the interfaces defined
by the java.awt.event package.
 When an event occurs, the event source invokes the appropriate method
defined by the listener and provides an event object as its argument.
 In the delegation event model, listeners must register with a source in order
to receive an event notification.
The Delegation Event Model
The Delegation Event Model
Event source Event listener
Event Object
(Event handling
methods)
Action Events on Buttons
Button ActionListener
ActionEvent
(actionPerformed(…))
Example 1:
class MyActionListener implements ActionListener {
//Registration Method
source.addActionListener(this);
public void actionPerformed(ActionEvent ae){
// Handler_ code
}
}
Example 2:
class MyMouseListener implements MouseListener{
//Registration Method
addMouseListener(this);
public void mouseClicked(MouseEvent me){
// Handler_ code
}
public void mouseEntered(MouseEvent me){
// Handler_ code
}
public void mouseExited(MouseEvent me){
// Handler_ code
}
public void mousePressed(MouseEvent me){
// Handler_ code
}
public void mouseReleased(MouseEvent me){
// Handler_ code }
}
}
Events
Events are supported by the java.awt.event package.
An event is an object that describes a state change in a source.
Events can be generated as a consequence of a person interacting
with elements in a graphical user interface.
Events may also occur that are not directly caused by interactions
with a user interface.
For example, an event may be generated
when a timer expires,
 a counter exceeds a value,
a software or hardware failure occurs.
 A source is an object that generates an event. This occurs when the internal
state of that object changes in some way.
 Sources may generate more than one type of event.
 A source must register listeners in order for the listeners to receive
notifications about a specific type of event.
 Each type of event has its own registration method.
Here is the general form:
public void addTypeListener(TypeListener el)
Here, Type is the name of the event and el is a reference to the event listener.
For example, the method that registers a keyboard event listener is called
addKeyListener( ).
Event Sources
Event Listeners
 A listener is an object that is notified when an event occurs.
 It has two major requirements.
First, it must have been registered with one or more sources to receive
notifications about specific types of events.
Second, it must implement methods to receive and process these
notifications.
 For example, the MouseMotionListener interface defines two methods to
receive notifications when the mouse is dragged or moved.
 Any object may receive and process one or both of these events if it provides
an implementation of this interface.
Event Classes
 EventObject is a superclass of all events which is defined in java.util package.
 AWTEvent is a superclass of all AWT events that are handled by the delegation
event model which is defined in java.awt package.
The following are the main event classes in java.awt.event package.
Event Class Description
ActionEvent Generated when a button is pressed, a list item is double-clicked,
or a menu item is selected.
MouseEvent Generated when the mouse is dragged, moved, clicked, pressed,
or released; also generated when the mouse enters or exits
a component.
KeyEvent Generated when the key is pressed , key is released, or key is
typed.
Event Class Description
TextEvent Generated when the value of a text area or text field is
changed.
MouseWheelEvent Generated when the mouse wheel is moved.
WindowEvent Generated when a window is activated, deactivated,
deiconified, iconified, opened, closing, closed.
ItemEvent Generated when a check box or list item is clicked; also
occurs when a choice selection is made or a checkable
menu item is selected or deselected.
FocusEvent Generated when a component gains or loses keyboard
focus.
AdjustmentEvent Generated when a scroll bar is manipulated.
ContainerEvent Generated when a component is added to or removed
from a container.
The ActionEvent Class
 You can obtain the command name for the invoking ActionEvent object by
using the
String getActionCommand() method.
 The getWhen( ) returns the time at which the event took place.
The KeyEvent Class
 int getKeyChar( ) which returns the character that was entered, and int getKeyCode( )
which returns the key code.
 It defines many integer constants:
VK_ENTER VK_ESCAPE VK_CANCEL VK_UP
VK_DOWN VK_LEFT VK_RIGHT VK_PAGE_DOWN
VK_PAGE_UP VK_SHIFT VK_ALT VK_CONTROL
The MouseEvent Class
 int getX( ) int getY( )
 The int getClickCount( ) method obtains the number of mouse clicks for this event.
The ItemEvent Class
 The int getStateChange() method returns the state change (i.e., SELECTED or
DESELECTED) for the event.
 The Object getItem( ) method can be used to obtain a reference to the item that
generated an event.
Sources of Events
 The following table lists some of the user interface components that can generate
the events.
Event Source Description
Button Generates action events when the button is pressed.
Choice Generates item events when the choice is changed.
List Generates action events when an item is double-
clicked; generates item events when an item is
selected or deselected.
Window Generates window events when a window is activated,
closed, deactivated, deiconified, iconified, opened, or
quit.
Event Source Description
Menu Item Generates action events when a menu item is
selected; generates item events when a checkable
menu item is selected or deselected.
Scrollbar Generates adjustment events when the scroll bar is
manipulated.
Text components Generates text events when the user enters a character.
Checkbox Generates item events when the check box is
selected or deselected.
Listener Interfaces
Interface Description
ActionListener Defines one method to receive action events.
AdjustmentListener Defines one method to receive adjustment events.
ComponentListener Defines four methods to recognize when a component is
hidden, moved, resized, or shown.
ContainerListener Defines two methods to recognize when a component is
added to or removed from a container.
FocusListener Defines two methods to recognize when a component
gains or loses keyboard focus.
ItemListener Defines one method to recognize when the state of an
item changes.
KeyListener Defines three methods to recognize when a key is pressed,
released, or typed.
Contd…
Interface Description
MouseListener Defines five methods to recognize when the
mouse is clicked, enters a component, exits a
component, is pressed, or is released.
MouseMotionListener Defines two methods to recognize when the
mouse is dragged or moved.
MouseWheelListener Defines one method to recognize when the
mouse wheel is moved.
TextListener Defines one method to recognize when a text
value changes.
WindowFocusListener Defines two methods to recognize when a
window gains or loses input focus.
WindowListener Defines seven methods to recognize when a
window is activated, closed, deactivated,
deiconified, iconified, opened, or quit.
Listener Interfaces and associated Event Classes
ActionEvent ActionListener
MouseEvent MouseListener
MouseMotionListener
KeyEvent KeyListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
ItemEvent ItemListener
TextEvent TextListener
WindowEvent WindowListener
The ActionListener Interface
This interface defines the actionPerformed() method that is invoked when an
action event occurs. Its general form is shown here:
void actionPerformed(ActionEvent ae)
The AdjustmentListener Interface
void adjustmentValueChanged(AdjustmentEvent ae)
The ComponentListener Interface
This interface defines four methods that are invoked when a component is
resized, moved, shown, or hidden.
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
The ItemListener Interface
void itemStateChanged(ItemEvent ie)
The ContainerListener Interface
When a component is added or removed to and from a container the following
methods are invoked.
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)
The KeyListener Interface
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
The MouseListener Interface
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
The MouseMotionListener Interface
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
The WindowListener Interface
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
The MouseWheelListener Interface
void mouseWheelMoved(MouseWheelEvent mwe)
The TextListener Interface
void textChanged(TextEvent te)
Adapter Classes
 Java provides a special feature, called an adapter class, that can simplify the
creation of event handlers in certain situations.
 An adapter class provides an empty implementation of all methods in an
event listener interface.
 Adapter classes are useful when you want to receive and process only some of
the events that are handled by a particular event listener interface.
 You can define a new class to act as an event listener by extending one of the
adapter classes and implementing only those events in which you are interested.
Table 20-4 lists the commonly used adapter classes in java.awt.event and
corresponding interfaces.
Adapter Class Listener Interface
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
Inner Class
 An inner class is a class defined within other class, or within an
expression.
//Inner class demo.
import java.applet.*;
import java.awt.event.*;
/*<applet code="InnerClassDemo" width=200 height=100></applet>*/
public class InnerClassDemo extends Applet{
public void init() {
addMouseListener(new MyMouseAdapter());
}
class MyMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}
}
}
Anonymous Inner Class
 An anonymous inner class is one that is not assigned a name.
//Anonymous inner class demo.
import java.applet.*;
import java.awt.event.*;
/*<applet code="AnonymousInnerClassDemo" width=200
height=100></applet>*/
public class AnonymousInnerClassDemo extends Applet{
public void init() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}
});
}
}
Frame
 Frame is a window that is not contained inside another window.
 Frame is the basis to contain other user interface components in Java
graphical applications.
 The Frame class can be used to create windows. Frame’s constructors:
Frame( )
Frame(String title)
 After a frame window has been created, it will not be visible until you
call setVisible( true).
Frame Location
 By default, a frame is displayed in the upper- left corner of the screen.
 To display a frame at a specified location, use the setLocation(x,y) method in
the Frame class.
screenHeight
screenWidth
frameHeight
frameWidth
(x, y)
Frame
Screen
(0,0)
//Method 1
import java.awt.*;
public class MyFrame{
public static void main( String args[]){
Frame f = new Frame("MyFrame");
f.setSize(300,200);
f.setVisible(true);
}
}
//Method 2
import java.awt.*;
public class MyFrame extends Frame{
MyFrame(){
super(“title of Frame”);
setSize(300,200);
setVisible(true);
}
}
class ExFrame{
public static void main( String args[]){
new MyFrame();
}
}
//Method 3
import java.awt.*;
public class MyFrame extends Frame{
MyFrame(){
super(“title of Frame”);
setSize(300,200);
setVisible(true);
}
public static void main( String args[]){
new MyFrame();
}
}
User interface components
Label Button Scrollbar
TextField TextArea List
Checkbox CheckboxGroup Choice
MenuBar Menu MenuItem
…
Label
Labels are passive controls that do not support any interaction with the
user.
Constructors
Label()
Label( String text )
Label( String text , int alignment )
Alignment Constants
Label.LEFT , Label.RIGHT , Label.CENTER
Methods
void setText(String text)
String getText()
void setAlignment(int alignment)
int getAlignment()
import java.awt.*;
public class ExLabel extends Frame
{
public ExLabel()
{
super("Label test");
Label label1 = new Label(“Enter User Name");
add( label1 );
setSize(300,200);
setVisible(true);
}
public static void main( String args[] )
{
new ExLabel();
}
}
//Label Example
Button
Constructors
Button()
Button(String title )
Methods
getLabel()
setLabel()
import java.awt.*; import java.awt.event.*; import java.applet.*;
/* <applet code="ButtonDemo" width=250 height=150> </applet>*/
public class ButtonDemo extends Applet implements ActionListener {
String msg = "“; Button yes, no, maybe;
public void init() {
yes = new Button("Yes"); no = new Button("No");
maybe = new Button("Undecided");
add(yes); add(no); add(maybe);
yes.addActionListener(this); no.addActionListener(this);
maybe.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
if(str.equals("Yes")) {
msg = "You pressed Yes.";
}
else if(str.equals("No")) {
msg = "You pressed No.";
}
else {
msg = "You pressed Undecided.";
}
repaint();
}
public void paint(Graphics g) {
g.drawString(msg, 6, 100);
} } }
Checkbox
Constructors
Checkbox()
Checkbox(String text)
Checkbox(String text , boolean state)
Checkbox(String text , CheckboxGroup group , boolean state)
Methods
String getLabel()
void setLabel()
boolean getState()
void setState()
CheckboxGroup, Choice and List
Three types of interface components are used to allow the user to select
one item from a large number of possibilities.
 First is a group of connected check boxes with the property that
only one can be selected at a time.( also called radio buttons ).
 Second is Choice.
 A third is a List. A List is similar to a choice, but several items
will be displayed at a time.
Constructors
CheckboxGroup()
Checkbox(String text , CheckboxGroup group , boolean state)
Methods
Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox which)
CheckboxGroup / Radio buttons
Choice
Constructors
Choice()
Methods
void add(String) – To add items to the list
String getItem(int)
String getSelectedItem()
void select(int index)
void select(String name)
List
Constructors
List()
List(int rows)
List(int rows, boolean multipleMode)
Methods
void add(String) //To add item to the end of the list
void add(String, int index) //To add item at an specified index
int getItemCount() //To get the count of items in the list
String getItem(int) //To get the specified item from the list
void remove(int) //To remove the item form the list
String getSelectedItem() //To get selected item from the list
TextField
Constructors
TextField()
void setText(String)
TextField(int columns)
TextField(String text)
TextField(String text, int columns)
Methods
void setText(String)
String getText()
void setEchoChar(char) //To enter text that is not displayed
void setEditable(bolean) //if false, text cann’t be modified
//TextField Example
import java.awt.*; import java.awt.event.*; import java.applet.*;
/*<applet code="TextFieldDemo" width=380 height=150></applet>*/
public class TextFieldDemo extends Applet implements ActionListener {
TextField name, pass;
public void init() {
Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
name = new TextField(1);
pass = new TextField(8);
pass.setEchoChar('?');
add(namep); add(name); add(passp); add(pass);
// register to receive action events
name.addActionListener(this);
pass.addActionListener(this);
}
// User pressed Enter.
public void actionPerformed(ActionEvent ae) {
repaint();
}
public void paint(Graphics g) {
g.drawString("Name: " + name.getText(), 6, 60);
g.drawString("Selected text in name: "+ name.getSelectedText(), 6, 80);
g.drawString("Password: " + pass.getText(), 6, 100);
}
}
Constructors
TextArea()
TextArea(String text)
TextArea(int rows, int numChars)
TextArea(String text , int rows, int numChars)
TextArea(String str, int numLines, int numChars, int sBars)
sBars must be one of these values:
SCROLLBARS_BOTH SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
Methods
void append(String)
void setText(String)
String getText()
void setEditable(boolean)
void insert(String str, int index)
TextArea
// Demonstrate TextArea.
import java.awt.*; import java.applet.*;
/*<applet code="TextAreaDemo" width=300 height=250></applet>*/
public class TextAreaDemo extends Applet {
public void init() {
String val = "There are two ways of constructing " +
"a software design.n" +
"One way is to make it so simplen" +
"that there are obviously no deficiencies.n" +
"And the other way is to make it so complicatedn" +
"that there are no obvious deficiencies.nn" +
" -C.A.R. Hoarenn" +
"There's an old story about the person who wishedn" +
"his computer were as easy to use as his telephone.n" +
"That wish has come true,n" +
"since I no longer know how to use my telephone.nn" +
" -Bjarne Stroustrup, AT&T, (inventor of C++)";
TextArea text = new TextArea(val, 10, 30);
add(text);
}
}
Scrollbar
Scroll bars are used to select continuous values between a specified
minimum and maximum.
The maximum and minimum values can be specified.
The line increment can be specified( the amount scroll bar will move
when it is touched in the line ends).
The page increment can be specified ( the amount scroll bar will move
when it is touched in the background area between the thumb and the
end).
Constructors
Scrollbar()
Scrollbar(int style)
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
Constants
 Scrollbar.VERTICAL
 Scrollbar.HORIZONTAL
Methods
getValue()
setValue(int newValue);
void setUnitIncrement(int newIncr)
void setBlockIncrement(int newIncr)
int getMinimum( )
int getMaximum( )
Minimum : default 0. Maximum : default 100
Default line increment is 1 Default page increment is 10.
import java.awt.*; import java.awt.event.*; import java.applet.*;
/*<applet code="SBDemo" width=300 height=200></applet>*/
public class SBDemo extends Applet implements AdjustmentListener, MouseMotionListener {
String msg = ""; Scrollbar vertSB, horzSB; int width = 300, height = 200;
public void init() {
vertSB = new Scrollbar(Scrollbar.VERTICAL,0, 1, 0,height);
horzSB = new Scrollbar(Scrollbar.HORIZONTAL,0, 1, 0, width);
add(vertSB); add(horzSB);
vertSB.addAdjustmentListener(this); horzSB.addAdjustmentListener(this);
addMouseMotionListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent ae) {
repaint();
}
public void mouseDragged(MouseEvent me) {
int x = me.getX(); int y = me.getY();
vertSB.setValue(y); horzSB.setValue(x);
repaint();
}
public void mouseMoved(MouseEvent me) {}
public void paint(Graphics g) {
msg = "Vertical: " + vertSB.getValue();
msg += ", Horizontal: " + horzSB.getValue();
g.drawString(msg, 6, 160);
}
}
1. To create a menu bar, first create an instance of MenuBar class.
This class only defines the default constructor. A menu bar contains one or
more Menu objects.
Constructor: MenuBar( )
Methods: setMenuBar(menubarInstance)
menubarInstance.add(menuInstance)
2. Next, create instances of Menu class.
Constructors: Menu( )
Menu(String menuName)
Methods: menuInstance.add(menuitemInstance)
3. Add menu items using MenuItem class.
Constructors:
MenuItem( )
MenuItem(String itemName)
MenuItem(String itemName, MenuShortcut keyAccel)
MenuBar , Menu and MenuItem
 You can disable or enable a menu item by using the setEnabled( ) method.
 You can determine an item’s status by calling isEnabled( ).
 You can change the name of a menu item by calling setLabel( ).
 You can retrieve the current name by using getLabel( ).
import java.awt.*;
public class ExMenubar extends Frame implements ActionListener{
public ExMenubar(){
super("Menubar test");
MenuBar mbar = new MenuBar();
setMenuBar(mbar);
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);
setSize(300,400);
setVisible(true);
//item1.addItem
}
public static void main(String args[]){
new ExMenubar(); }
}
 A dialog box is a special window used to alert user or take input from user.
 They are similar to frame windows, except that dialog boxes are always
child windows of a top-level window.
 Also, dialog boxes don’t have menu bars. In other respects, dialog boxes
function like frame windows.
 You can add controls to them, for example, in the same way that you add
controls to a frame window.)
 Dialog boxes may be modal or modeless.
 When a modal dialog box is active, you cannot access other parts of your
program until the dialog box is closed.
 When a modeless dialog box is active, you can access other parts of your
program.
Dialog Boxes
Constructors
 Dialog(Frame parentWindow, boolean mode)
 Dialog(Frame parentWindow, String title, boolean mode)
 Here, parentWindow is the owner of the dialog box.
 If mode is true, the dialog box is modal. Otherwise, it is modeless.
import java.awt.*;
public class ExDialog extends Frame{
public ExDialog() {
Dialog d = new Dialog(this ,"Dialog", false);
d.add("Center", new Label("Dialog Box"));
d.add("South“, new Button("OK"));
d.pack();
d.setVisible(true);
}
public static void main(String args[]){
new ExDialog();
}
}
Canvas
A Canvas is a two-dimensional area used to draw some shapes on it using the
Graphics.
Constructors
Canvas()
Methods
setSize(int width, int height)
setBackground(Color )
import java.awt.*;
public class ExCanvas extends Frame{
public ExCanvas(){
setLayout(new FlowLayout());
Canvas can1 = new Canvas();
can1.setSize(200,100);
can1.setBackground(Color.red);
add( can1 );
setSize(200,300);
setVisible(true);
}
public static void main(String args[]){
new ExCanvas();
}
}
Panel
This is simplest invisible container that holds GUI components.
It is recommended that you place the user interface components in panels and
place the panels in a frame.
You can also place panels in a panel.
FlowLayout is the default layout for panel.
Panel()
Panel(LayoutManager layout)
import java.awt.*;
public class ExPanel extends Frame{
public ExPanel(){
setLayout(new FlowLayout());
Panel pan1 = new Panel();
pan1.setSize(200,100);
pan1.setBackground(Color.red);
pan1.setLocation(50,50);
add( pan1 );
Button button1 = new Button(“ok");
Button button2 = new Button(“cancel");
pan1.add( button1 );
pan1.add( button2 );
}
public static void main(String args[]){
new ExPanel();
}
}
ScrollPane
It is similar to a panel.
It can hold only one Component.
 If size of the component held is larger than the size of the ScrollPane,
Scroll bars will be automatically generated.
 It does not have a LayoutManager
Constructors
ScrollPane()
import java.awt.*;
public class ExScrollPane extends Frame{
public ExScrollPane(){
ScrollPane sPane1 = new ScrollPane();
sPane1.setSize(200,100);
sPane1.setBackground(Color.red);
sPane1.setLocation(50,50);
Panel pan1 = new Panel();
TextArea text1 = new TextArea(300,500);
pan1.add( text1 );
sPane1.add( pan1 );
add( sPane1 );
setSize(200,300);
setVisible(true);
}
public static void main(String args[]){
new ExScrollPane();
}
}
Graphics
 Graphics object draws pixels on the screen that represent text and other
graphical shapes such as lines, ovals, rectangles, polygons etc.
 The graphics class is an abstract class(i.e. Graphics objects can not be
instantiated.)
 A graphics context is encapsulated by the Graphics class and is obtained
in two ways:
 It is passed to an applet when one of its various methods, such as
paint( ) or update( ), is called.
 It is returned by the getGraphics() method of Component.
public void paint(Graphics g)
 The paint(Graphics g) method is common to all components and containers.
 It is needed if you do any drawing or painting other than just using standard
GUI components.
 Never call paint(Graphics g), call repaint( )
How does the paint(Graphics g) method get called?
 It is called automatically by Java whenever the component or
container is loaded, resized, minimized, maximized.
 You can cause the paint method to be called at any time by calling the
component’s repaint() method.
class myFrame extends Frame{
……..
……..
public void paint(Graphics g){
g.drawOval(x1,y1,width,height);
……
}
}
The repaint() method will do two things:
1. It calls update(Graphics g), which writes over the old drawing in background
color (thus erasing it).
2. It then calls paint(Graphics g) to do the drawing.
Java coordinate system ( 0,0)
x
y
(x,y)
Graphics methods for drawing shapes
g.drawString (str, x, y); //Puts string at x,y
g.drawLine( x1, y1, x2, y2 ) //Line from x1, y1 to x2, y2
g.drawRect( x1, y1, width, height)
//Draws rectangle with upper left corner x1, y1
g.fillRect(x1, y1, width, height) //Draws a solid rectangle.
g.drawRoundRect( x, y, width, height,arcWidth, arcHeight )
//Draws rectangle with rounded corners.
g.fillRoundRect( x, y, width, height,arcWidth, arcHeight )
//Draws a solid rectangle with rounded corners.
arc width
width
height
(x, y)
arc height
(x, y)
height
width
drawRoundRect
parameters
drawOval parameters
g.drawOval(x1, y1, width, height)
//Draws an oval with specified width and height. The bounding
rectangle’s top left corner is at the coordinate (x,y).The oval
touches all four sides all four sides of the bounding rectangle.
g.fillOval(x1, y1, width, height) //Draws a filled oval.
g.setColor(Color.RED)
//Sets color, it is remain active until new color is set.
g.drawArc(x1, y1, width, height, startAngle,arcAngle)
//Draws an arc relative to the bounding rectangle’s top-left
coordinates with the specified width and height. The arc
segment is drawn starting at startAngle and sweeps arcAngle
degrees.
180 180
270 270
90 90
0
0
Positive angle Negative angle
Drawing Polygons and Polylines
 Polygon - multisided shape
 Polyline - series of connected points
 Methods of class Polygon
drawPolygon( xPoints[], yPoints[], points )
//Draws a polygon, with x and y points specified in arrays. Last
argument specifies number of points
//Closed polygon, even if last point different from first.
drawPolyline ( xPoints[], yPoints[],points )
//Draws a polyline
Font
 Fonts are encapsulated by the Font class.
 To select a new font, you must first construct a Font object that
describes that font.
Font(String fontName, int fontStyle, int pointSize)
//Here, fontName specifies the name of the desired font.
 All Java environments will support the following fonts:
Dialog, DialogInput, Sans Serif, Serif, Monospaced and Symbol.
 The style of the font is specified by fontStyle. It may consist of one or
more of these three constants:
Font.PLAIN Font.BOLD Font.ITALIC
void setFont(Font fontObj)
//To set the specified Font .
//It is defined in Component class.
//Here, fontObj is the object that contains the desired font.
Font getFont() //To obtain information about the currently
selected font which is defined in Graphics class
Methods in Font Class:
String getName() //To get the name of the Font
String getFamily(); //To get family name of the Font
int getSize(); //To get the size of the Font
int getStyle(); //To get the style of the Font
Layout Managers
 Arranges and lays out the GUI components on a container.
 Every container has a default Layout Manager:
 Panel FlowLayout
 Window (Frame) BorderLayout
 Types:
Flow Layout Border Layout Grid Layout
Card Layout Gridbag Layout
 To set layout manager:
myContainer.setLayout( new LayoutManger() );
Flow Layout
 The Flow Layout manager arranges the components left-to-right, top-
to-bottom in the order they were inserted into the container.
 When the container is not wide enough to display all the components,
the remaining components are placed in the next row, etc.
 By default each row is centered.
 The line alignment can be:
 FlowLayout.LEFT
 FlowLayout.CENTER
 FlowLayout.RIGHT
Flow Layout Example
English French Greek
Japanese German
Spanish Portuguese
Arabic Chinese Russian
Flow Layout Constructors
 FlowLayout()
//A centered alignment and a default 5-unit horizontal and vertical gap.
 FlowLayout(align)
align – alignment used by the manager. A default 5-unit horizontal and
vertical gap.
 FlowLayout(align, hgap, vgap)
//align – alignment used by the manager
//hgap – horizontal gaps between components
//vgap – vertical gaps between components
Border Layout
 The Border Layout manager arranges components into five regions: North,
South, East, West, and Center.
 Components in the North and South are set to their natural heights and
horizontally stretched to fill the entire width of the container.
 Components in the East and West are set to their natural widths and
stretched vertically to fill the entire width of the container.
 The Center component fills the space left in the center of the container.
 If one or more of the components, except the Center component, are
missing then the rest of the existing components are stretched to fill the
remaining space in the container.
 The positional constraints are:
BorderLayout.NORTH BorderLayout.SOUTH
BorderLayout.EAST BorderLayout.WEST
BorderLayout.CENTER
BorderLayout Manager
North
South
Center East
West
To set BorderLayout:
add( new Button(“ok”), BorderLayout.NORTH);
Border Layout Constructors
 BorderLayout()
//No vertical or horizontal gaps.
 BorderLayout(hgap, vgap)
//hgap – horizontal gaps between components
//vgap – vertical gaps between components
Grid Layout
 Container is divided into a grid where components are placed in
rows and columns.
 Every component has the same width and height.
 Example
Grid Layout Constructors
 GridLayout()
//A single row and no vertical or horizontal gaps.
 GridLayout(r, c)
//r – number of rows in the layout
//c – number of columns in the layout
//No vertical or horizontal gaps.
 GridLayout(r, c, hgap, vgap)
//r – number of rows in the layout
//c – number of columns in the layout
//hgap – horizontal gaps between components
//vgap – vertical gaps between components
CardLayout
 CardLayout places components (usually panels) on top of each other
in a stack like a deck of cards.
 You can see only one card at a time.
 By default, the first card is visible.
 We can put a cards on top using another control by using the methods
next(), previous(), first(), last(), and show().
Methods:
public void first(Container parent);
public void next(Container parent);
public void previous(Container parent);
public void last(Container parent);
public void show(Container parent, String name);
First Card
add(component, name)
New Card
Constructor: CardLayout()
import java.awt.*; import java.awt.event.*;
public class CardLayoutDemo extends Frame implements ActionListener, MouseListener
{
Checkbox winXP, winVista, solaris, mac;
Button Win, Other;
Panel osCards;
CardLayout cardLO;
public CardLayoutDemo(){
setLayout(new BorderLayout());
cardLO = new CardLayout();
Panel tabs=new Panel();
Win = new Button("Windows");
Other = new Button("Other");
tabs.add(Win);
tabs.add(Other);
add(tabs,BorderLayout.NORTH);
osCards = new Panel();
osCards.setLayout(cardLO); // set panel layout to card layout
Panel winPan = new Panel();
winXP = new Checkbox("Windows XP", null, true);
winVista = new Checkbox("Windows Vista");
// add Windows check boxes to a panel
winPan.setBackground(Color.CYAN);
winPan.add(winXP);
winPan.add(winVista);
// Add other OS check boxes to a panel
Panel otherPan = new Panel();
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
otherPan.setBackground(Color.RED);
otherPan.add(solaris);
otherPan.add(mac);
// add panels to card deck panel
osCards.add(winPan, "Windows");
osCards.add(otherPan, "Other");
// add cards to main applet panel
add(osCards,BorderLayout.CENTER);
// register to receive action events
Win.addActionListener(this);
Other.addActionListener(this);
// register mouse events
addMouseListener(this);
setSize(250,250);
setVisible(true);
}
public Insets getInsets(){
return new Insets(30,30,30,30);
}
public void mousePressed(MouseEvent me) {
cardLO.next(osCards);
}
public void mouseClicked(MouseEvent me) { }
public void mouseEntered(MouseEvent me) { }
public void mouseExited(MouseEvent me) { }
public void mouseReleased(MouseEvent me) { }
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == Win) {
cardLO.first(osCards); //cardLO.show(osCards, "Windows");
}
else {
cardLO.last(osCards); //cardLO.show(osCards, "Other");
}
}
public static void main(String arg[]){
new CardLayoutDemo();
}
}
GridBagLayout Layout Manager
 Flexible GridBagLayout
 Components can vary in size
 Components can occupy multiple rows and columns
 Components can be added in any order
 There are two classes that are used:
GridBagLayout: Provides the overall layout manager.
GridBagConstraints: Defines the properties of each component in
the grid such as placement, dimension and alignment
Specifying a GridBagLayout
 To use a gridbag layout, you must declare the GridBagLayout and
GridBagConstaraints object and attach the layout to your applet.
Example:
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
setLayout(gridbag);
Setting Constraints for Components
 For each component that you add to the gridbag layout, you must first
set an instance of the GridBagContraints class.
 Let us look at an example:
constraints.gridx = 0 // put component in first cell.
constraints.gridy = 0
gridbag.setConstraints(button1, constraints);
//set the constraints to button1.
add(button1); //add to the Frame
Precisely Placing Components
Row
Column
0 1 2
0
1
2
3
The following are the constraints to control the component:
gridx, gridy, gridwidth, gridheight, weightx, weighty, ipadx, ipady , fill
constraints.gridx=0; //To set the column (Default is RELATIVE).
constraints.gridy=0; //To set the row (Default is RELATIVE).
constraints.gridwidth = 2; //Joins two cells horizontally
constraints.gridheight = 2; //Joins two cells vertically
//Default value is 1.
GridBagConstraints Data Members
constraints.weightx=2; //Determines horizontal spacing between cells.
constraints.weighty=3; // Determines vertical spacing between cells.
//Default value is 0.
constraints.ipadx=2;
//Specifies extra horizontal space that surrounds a component within a cell.
constraints.ipady=0;
//Specifies extra vertical space that surrounds a component within a cell.
//Default is 0.
fill //Resizing rules for a component smaller than its display area;
//HORIZONTAL makes component as wide as the display area;
//VERTICAL as tall; BOTH expands it vertically and horizontally.
//NONE (default) is default.
Examples:
constraints.fill = GridBagConstraints.BOTH; //Fill cell height & width
constraints.fill = GridBagConstraints.HORIZONTAL; //Fill cell width

More Related Content

Similar to engineeringdsgtnotesofunitfivesnists.ppt

Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01Ankit Dubey
 
Unit-3 event handling
Unit-3 event handlingUnit-3 event handling
Unit-3 event handlingAmol Gaikwad
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptxGood657694
 
Event Handling in JAVA
Event Handling in JAVAEvent Handling in JAVA
Event Handling in JAVASrajan Shukla
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in JavaAyesha Kanwal
 
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 Dr Jammi Ashok - Introduction to Java Material (OOPs) Dr Jammi Ashok - Introduction to Java Material (OOPs)
Dr Jammi Ashok - Introduction to Java Material (OOPs)jammiashok123
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892renuka gavli
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in javaAdil Mehmoood
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 appletsraksharao
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01JONDHLEPOLY
 
Java gui event
Java gui eventJava gui event
Java gui eventSoftNutx
 
ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxudithaisur
 
event handling new.ppt
event handling new.pptevent handling new.ppt
event handling new.pptusama537223
 
Advance java for bscit
Advance java for bscitAdvance java for bscit
Advance java for bscitYogeshDhamke2
 

Similar to engineeringdsgtnotesofunitfivesnists.ppt (20)

Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01
 
Unit-3 event handling
Unit-3 event handlingUnit-3 event handling
Unit-3 event handling
 
Lecture8 oopj
Lecture8 oopjLecture8 oopj
Lecture8 oopj
 
Jp notes
Jp notesJp notes
Jp notes
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
 
GUI components in Java
GUI components in JavaGUI components in Java
GUI components in Java
 
Event Handling in JAVA
Event Handling in JAVAEvent Handling in JAVA
Event Handling in JAVA
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in Java
 
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 Dr Jammi Ashok - Introduction to Java Material (OOPs) Dr Jammi Ashok - Introduction to Java Material (OOPs)
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01
 
JAVA (UNIT 5)
JAVA (UNIT 5)JAVA (UNIT 5)
JAVA (UNIT 5)
 
Java gui event
Java gui eventJava gui event
Java gui event
 
What is Event
What is EventWhat is Event
What is Event
 
ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptx
 
event handling new.ppt
event handling new.pptevent handling new.ppt
event handling new.ppt
 
Advance java for bscit
Advance java for bscitAdvance java for bscit
Advance java for bscit
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 

Recently uploaded

Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxvipinkmenon1
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 

Recently uploaded (20)

★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptx
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 

engineeringdsgtnotesofunitfivesnists.ppt

  • 2.  Advantages of GUI over CUI  The AWT class hierarchy- Component, Frame  Event handling: Delegation Event model  Closing a frame, mouse and keyboard events  Adapter classes  User interface components:  Labels, button, scrollbars  Text components, check box, check box groups, choices  Lists panels – ScrollPane, MenuBar, graphics  Layout manager – layout manager types  Concepts of Applets, differences between applets and Applications  Life cycle of an applet  Types of applets, creating applets, passing parameters to applets
  • 3. Advantages of GUI over CUI Presents a user-friendly mechanism for interacting with an application. Built from GUI components. It need more resources Speed is less compare to the CUI In a Command Line Interface, the commands are entered from the keyboard. It is not user-friendly. Difficult to remember commands. It need less resources Speed is more compare to the GUI
  • 4. Most modern programs use a GUI.  Graphical: Not just text or characters but windows, menus, buttons, ..  User: Person using the program  Interface: Way to interact with the program Graphical Elements include: Window List Choice Label Menu Scrollbar Button TextComponent etc.,
  • 5. button menus title bar menu bar combo box scroll bars Internet Explorer Window with GUI components
  • 6. Abstract Window Toolkit (AWT)  The AWT contains several classes and methods that allow you to create and manage windows.  The two most common windows are those derived from Panel, which is used by applets, and those derived from Frame, which creates a standard window.  The main purpose of the AWT is to support applet windows.  It can also be used to create stand-alone GUI applications.
  • 7. AWT class hierarchy MenuBar Component Container Window Panel Frame Label Button TextComponent TextField TextArea Choice CheckBox CheckBoxGroup Scrollbar MenuComponent List MenuItem Menu Dialog Canvas ScrollPane Applet
  • 8. Component: (java.awt)  Component is an abstract class that encapsulates all of the attributes of a visual component.  It is a super class of all user interface classes.  A component is something that can be displayed on a two-dimensional screen and with which the user can interact.  Attributes of a component include a size, a location, foreground and background colors, whether or not visible etc., Methods defined in class Component are:  setLocation(int, int), getLocation() ---To set and get component location  setSize(int, int), getSize() ---To set and get component size  setVisible() ---To show or hide the component  setForeground(Color), getForeground() ---To set and get foreground colors  setBackground(Color), getBackground() ---To set and get background colors
  • 9. Container: (java.awt)  Container class is a subclass of Component class.  This is a type of component that can nest other components within it. Ex:- Window, Frame, and panel are examples of containers.  A Container is responsible for laying out (that is, positioning) any components that it contains. Methods defined in a class Container are:  setLayout(LayoutManager) ---To set layout manager for display.  add( Component ) ---To add component to the display.  remove( Component ) ---To remove component from display.
  • 10. Panel: (java.awt)  The Panel class is a concrete subclass of Container class.  A panel is a window that does not contain a title bar, or border.  It provides space in which an application can attach any other component, including other panels.  It is the superclass for Applet.  Other components can be added to a Panel object by its add() method.  The default layout manager for a panel is the FlowLayout layout manager.
  • 11. Window: (java.awt)  The Window class creates a top-level window.  A top-level window is not contained within any other object; it sits directly on the desktop.  Generally, we won’t create Window objects directly. Instead, we use a subclass of Window called Frame. Frame: (java.awt)  It is a type of Window with a title bar, menu bar , borders, and resizing corners. Methods defined in a Frame class are:  setTitle(String), getTitle() ---To set or get title  setMenuBar(MenuBar) ---To set menu bar for window Layout Manager:  A manager is used to position and place components in a Container.
  • 13.  It defines standard and consistent mechanisms to generate and process events.  In this model, a source generates an event and sends it to one or more listeners.  The listener simply waits until it receives an event. Once received, the listener processes the event and then returns.  Listeners are created by implementing one or more of the interfaces defined by the java.awt.event package.  When an event occurs, the event source invokes the appropriate method defined by the listener and provides an event object as its argument.  In the delegation event model, listeners must register with a source in order to receive an event notification. The Delegation Event Model
  • 14. The Delegation Event Model Event source Event listener Event Object (Event handling methods) Action Events on Buttons Button ActionListener ActionEvent (actionPerformed(…))
  • 15. Example 1: class MyActionListener implements ActionListener { //Registration Method source.addActionListener(this); public void actionPerformed(ActionEvent ae){ // Handler_ code } }
  • 16. Example 2: class MyMouseListener implements MouseListener{ //Registration Method addMouseListener(this); public void mouseClicked(MouseEvent me){ // Handler_ code } public void mouseEntered(MouseEvent me){ // Handler_ code } public void mouseExited(MouseEvent me){ // Handler_ code } public void mousePressed(MouseEvent me){ // Handler_ code } public void mouseReleased(MouseEvent me){ // Handler_ code } } }
  • 17. Events Events are supported by the java.awt.event package. An event is an object that describes a state change in a source. Events can be generated as a consequence of a person interacting with elements in a graphical user interface. Events may also occur that are not directly caused by interactions with a user interface. For example, an event may be generated when a timer expires,  a counter exceeds a value, a software or hardware failure occurs.
  • 18.  A source is an object that generates an event. This occurs when the internal state of that object changes in some way.  Sources may generate more than one type of event.  A source must register listeners in order for the listeners to receive notifications about a specific type of event.  Each type of event has its own registration method. Here is the general form: public void addTypeListener(TypeListener el) Here, Type is the name of the event and el is a reference to the event listener. For example, the method that registers a keyboard event listener is called addKeyListener( ). Event Sources
  • 19. Event Listeners  A listener is an object that is notified when an event occurs.  It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications.  For example, the MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved.  Any object may receive and process one or both of these events if it provides an implementation of this interface.
  • 20. Event Classes  EventObject is a superclass of all events which is defined in java.util package.  AWTEvent is a superclass of all AWT events that are handled by the delegation event model which is defined in java.awt package. The following are the main event classes in java.awt.event package. Event Class Description ActionEvent Generated when a button is pressed, a list item is double-clicked, or a menu item is selected. MouseEvent Generated when the mouse is dragged, moved, clicked, pressed, or released; also generated when the mouse enters or exits a component. KeyEvent Generated when the key is pressed , key is released, or key is typed.
  • 21. Event Class Description TextEvent Generated when the value of a text area or text field is changed. MouseWheelEvent Generated when the mouse wheel is moved. WindowEvent Generated when a window is activated, deactivated, deiconified, iconified, opened, closing, closed. ItemEvent Generated when a check box or list item is clicked; also occurs when a choice selection is made or a checkable menu item is selected or deselected. FocusEvent Generated when a component gains or loses keyboard focus. AdjustmentEvent Generated when a scroll bar is manipulated. ContainerEvent Generated when a component is added to or removed from a container.
  • 22. The ActionEvent Class  You can obtain the command name for the invoking ActionEvent object by using the String getActionCommand() method.  The getWhen( ) returns the time at which the event took place. The KeyEvent Class  int getKeyChar( ) which returns the character that was entered, and int getKeyCode( ) which returns the key code.  It defines many integer constants: VK_ENTER VK_ESCAPE VK_CANCEL VK_UP VK_DOWN VK_LEFT VK_RIGHT VK_PAGE_DOWN VK_PAGE_UP VK_SHIFT VK_ALT VK_CONTROL The MouseEvent Class  int getX( ) int getY( )  The int getClickCount( ) method obtains the number of mouse clicks for this event. The ItemEvent Class  The int getStateChange() method returns the state change (i.e., SELECTED or DESELECTED) for the event.  The Object getItem( ) method can be used to obtain a reference to the item that generated an event.
  • 23. Sources of Events  The following table lists some of the user interface components that can generate the events. Event Source Description Button Generates action events when the button is pressed. Choice Generates item events when the choice is changed. List Generates action events when an item is double- clicked; generates item events when an item is selected or deselected. Window Generates window events when a window is activated, closed, deactivated, deiconified, iconified, opened, or quit.
  • 24. Event Source Description Menu Item Generates action events when a menu item is selected; generates item events when a checkable menu item is selected or deselected. Scrollbar Generates adjustment events when the scroll bar is manipulated. Text components Generates text events when the user enters a character. Checkbox Generates item events when the check box is selected or deselected.
  • 25. Listener Interfaces Interface Description ActionListener Defines one method to receive action events. AdjustmentListener Defines one method to receive adjustment events. ComponentListener Defines four methods to recognize when a component is hidden, moved, resized, or shown. ContainerListener Defines two methods to recognize when a component is added to or removed from a container. FocusListener Defines two methods to recognize when a component gains or loses keyboard focus. ItemListener Defines one method to recognize when the state of an item changes. KeyListener Defines three methods to recognize when a key is pressed, released, or typed.
  • 26. Contd… Interface Description MouseListener Defines five methods to recognize when the mouse is clicked, enters a component, exits a component, is pressed, or is released. MouseMotionListener Defines two methods to recognize when the mouse is dragged or moved. MouseWheelListener Defines one method to recognize when the mouse wheel is moved. TextListener Defines one method to recognize when a text value changes. WindowFocusListener Defines two methods to recognize when a window gains or loses input focus. WindowListener Defines seven methods to recognize when a window is activated, closed, deactivated, deiconified, iconified, opened, or quit.
  • 27. Listener Interfaces and associated Event Classes ActionEvent ActionListener MouseEvent MouseListener MouseMotionListener KeyEvent KeyListener TextEvent TextListener AdjustmentEvent AdjustmentListener ContainerEvent ContainerListener FocusEvent FocusListener ItemEvent ItemListener TextEvent TextListener WindowEvent WindowListener
  • 28. The ActionListener Interface This interface defines the actionPerformed() method that is invoked when an action event occurs. Its general form is shown here: void actionPerformed(ActionEvent ae) The AdjustmentListener Interface void adjustmentValueChanged(AdjustmentEvent ae) The ComponentListener Interface This interface defines four methods that are invoked when a component is resized, moved, shown, or hidden. void componentResized(ComponentEvent ce) void componentMoved(ComponentEvent ce) void componentShown(ComponentEvent ce) void componentHidden(ComponentEvent ce) The ItemListener Interface void itemStateChanged(ItemEvent ie)
  • 29. The ContainerListener Interface When a component is added or removed to and from a container the following methods are invoked. void componentAdded(ContainerEvent ce) void componentRemoved(ContainerEvent ce) The KeyListener Interface void keyPressed(KeyEvent ke) void keyReleased(KeyEvent ke) void keyTyped(KeyEvent ke) The MouseListener Interface void mouseClicked(MouseEvent me) void mouseEntered(MouseEvent me) void mouseExited(MouseEvent me) void mousePressed(MouseEvent me) void mouseReleased(MouseEvent me)
  • 30. The MouseMotionListener Interface void mouseDragged(MouseEvent me) void mouseMoved(MouseEvent me) The WindowListener Interface void windowActivated(WindowEvent we) void windowClosed(WindowEvent we) void windowClosing(WindowEvent we) void windowDeactivated(WindowEvent we) void windowDeiconified(WindowEvent we) void windowIconified(WindowEvent we) void windowOpened(WindowEvent we) The MouseWheelListener Interface void mouseWheelMoved(MouseWheelEvent mwe) The TextListener Interface void textChanged(TextEvent te)
  • 31. Adapter Classes  Java provides a special feature, called an adapter class, that can simplify the creation of event handlers in certain situations.  An adapter class provides an empty implementation of all methods in an event listener interface.  Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface.  You can define a new class to act as an event listener by extending one of the adapter classes and implementing only those events in which you are interested.
  • 32. Table 20-4 lists the commonly used adapter classes in java.awt.event and corresponding interfaces. Adapter Class Listener Interface KeyAdapter KeyListener MouseAdapter MouseListener MouseMotionAdapter MouseMotionListener WindowAdapter WindowListener ComponentAdapter ComponentListener ContainerAdapter ContainerListener FocusAdapter FocusListener
  • 33. Inner Class  An inner class is a class defined within other class, or within an expression. //Inner class demo. import java.applet.*; import java.awt.event.*; /*<applet code="InnerClassDemo" width=200 height=100></applet>*/ public class InnerClassDemo extends Applet{ public void init() { addMouseListener(new MyMouseAdapter()); } class MyMouseAdapter extends MouseAdapter { public void mousePressed(MouseEvent me) { showStatus("Mouse Pressed"); } } }
  • 34. Anonymous Inner Class  An anonymous inner class is one that is not assigned a name. //Anonymous inner class demo. import java.applet.*; import java.awt.event.*; /*<applet code="AnonymousInnerClassDemo" width=200 height=100></applet>*/ public class AnonymousInnerClassDemo extends Applet{ public void init() { addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { showStatus("Mouse Pressed"); } }); } }
  • 35. Frame  Frame is a window that is not contained inside another window.  Frame is the basis to contain other user interface components in Java graphical applications.  The Frame class can be used to create windows. Frame’s constructors: Frame( ) Frame(String title)  After a frame window has been created, it will not be visible until you call setVisible( true).
  • 36. Frame Location  By default, a frame is displayed in the upper- left corner of the screen.  To display a frame at a specified location, use the setLocation(x,y) method in the Frame class. screenHeight screenWidth frameHeight frameWidth (x, y) Frame Screen (0,0)
  • 37. //Method 1 import java.awt.*; public class MyFrame{ public static void main( String args[]){ Frame f = new Frame("MyFrame"); f.setSize(300,200); f.setVisible(true); } }
  • 38. //Method 2 import java.awt.*; public class MyFrame extends Frame{ MyFrame(){ super(“title of Frame”); setSize(300,200); setVisible(true); } } class ExFrame{ public static void main( String args[]){ new MyFrame(); } }
  • 39. //Method 3 import java.awt.*; public class MyFrame extends Frame{ MyFrame(){ super(“title of Frame”); setSize(300,200); setVisible(true); } public static void main( String args[]){ new MyFrame(); } }
  • 40. User interface components Label Button Scrollbar TextField TextArea List Checkbox CheckboxGroup Choice MenuBar Menu MenuItem …
  • 41. Label Labels are passive controls that do not support any interaction with the user. Constructors Label() Label( String text ) Label( String text , int alignment ) Alignment Constants Label.LEFT , Label.RIGHT , Label.CENTER Methods void setText(String text) String getText() void setAlignment(int alignment) int getAlignment()
  • 42. import java.awt.*; public class ExLabel extends Frame { public ExLabel() { super("Label test"); Label label1 = new Label(“Enter User Name"); add( label1 ); setSize(300,200); setVisible(true); } public static void main( String args[] ) { new ExLabel(); } } //Label Example
  • 44. import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="ButtonDemo" width=250 height=150> </applet>*/ public class ButtonDemo extends Applet implements ActionListener { String msg = "“; Button yes, no, maybe; public void init() { yes = new Button("Yes"); no = new Button("No"); maybe = new Button("Undecided"); add(yes); add(no); add(maybe); yes.addActionListener(this); no.addActionListener(this); maybe.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String str = ae.getActionCommand(); if(str.equals("Yes")) { msg = "You pressed Yes."; } else if(str.equals("No")) { msg = "You pressed No."; } else { msg = "You pressed Undecided."; } repaint(); } public void paint(Graphics g) { g.drawString(msg, 6, 100); } } }
  • 45. Checkbox Constructors Checkbox() Checkbox(String text) Checkbox(String text , boolean state) Checkbox(String text , CheckboxGroup group , boolean state) Methods String getLabel() void setLabel() boolean getState() void setState()
  • 46. CheckboxGroup, Choice and List Three types of interface components are used to allow the user to select one item from a large number of possibilities.  First is a group of connected check boxes with the property that only one can be selected at a time.( also called radio buttons ).  Second is Choice.  A third is a List. A List is similar to a choice, but several items will be displayed at a time.
  • 47. Constructors CheckboxGroup() Checkbox(String text , CheckboxGroup group , boolean state) Methods Checkbox getSelectedCheckbox( ) void setSelectedCheckbox(Checkbox which) CheckboxGroup / Radio buttons
  • 48. Choice Constructors Choice() Methods void add(String) – To add items to the list String getItem(int) String getSelectedItem() void select(int index) void select(String name)
  • 49. List Constructors List() List(int rows) List(int rows, boolean multipleMode) Methods void add(String) //To add item to the end of the list void add(String, int index) //To add item at an specified index int getItemCount() //To get the count of items in the list String getItem(int) //To get the specified item from the list void remove(int) //To remove the item form the list String getSelectedItem() //To get selected item from the list
  • 50. TextField Constructors TextField() void setText(String) TextField(int columns) TextField(String text) TextField(String text, int columns) Methods void setText(String) String getText() void setEchoChar(char) //To enter text that is not displayed void setEditable(bolean) //if false, text cann’t be modified
  • 51. //TextField Example import java.awt.*; import java.awt.event.*; import java.applet.*; /*<applet code="TextFieldDemo" width=380 height=150></applet>*/ public class TextFieldDemo extends Applet implements ActionListener { TextField name, pass; public void init() { Label namep = new Label("Name: ", Label.RIGHT); Label passp = new Label("Password: ", Label.RIGHT); name = new TextField(1); pass = new TextField(8); pass.setEchoChar('?'); add(namep); add(name); add(passp); add(pass); // register to receive action events name.addActionListener(this); pass.addActionListener(this); } // User pressed Enter. public void actionPerformed(ActionEvent ae) { repaint(); } public void paint(Graphics g) { g.drawString("Name: " + name.getText(), 6, 60); g.drawString("Selected text in name: "+ name.getSelectedText(), 6, 80); g.drawString("Password: " + pass.getText(), 6, 100); } }
  • 52. Constructors TextArea() TextArea(String text) TextArea(int rows, int numChars) TextArea(String text , int rows, int numChars) TextArea(String str, int numLines, int numChars, int sBars) sBars must be one of these values: SCROLLBARS_BOTH SCROLLBARS_NONE SCROLLBARS_HORIZONTAL_ONLY SCROLLBARS_VERTICAL_ONLY Methods void append(String) void setText(String) String getText() void setEditable(boolean) void insert(String str, int index) TextArea
  • 53. // Demonstrate TextArea. import java.awt.*; import java.applet.*; /*<applet code="TextAreaDemo" width=300 height=250></applet>*/ public class TextAreaDemo extends Applet { public void init() { String val = "There are two ways of constructing " + "a software design.n" + "One way is to make it so simplen" + "that there are obviously no deficiencies.n" + "And the other way is to make it so complicatedn" + "that there are no obvious deficiencies.nn" + " -C.A.R. Hoarenn" + "There's an old story about the person who wishedn" + "his computer were as easy to use as his telephone.n" + "That wish has come true,n" + "since I no longer know how to use my telephone.nn" + " -Bjarne Stroustrup, AT&T, (inventor of C++)"; TextArea text = new TextArea(val, 10, 30); add(text); } }
  • 54. Scrollbar Scroll bars are used to select continuous values between a specified minimum and maximum. The maximum and minimum values can be specified. The line increment can be specified( the amount scroll bar will move when it is touched in the line ends). The page increment can be specified ( the amount scroll bar will move when it is touched in the background area between the thumb and the end).
  • 55. Constructors Scrollbar() Scrollbar(int style) Scrollbar(int style, int initialValue, int thumbSize, int min, int max) Constants  Scrollbar.VERTICAL  Scrollbar.HORIZONTAL Methods getValue() setValue(int newValue); void setUnitIncrement(int newIncr) void setBlockIncrement(int newIncr) int getMinimum( ) int getMaximum( ) Minimum : default 0. Maximum : default 100 Default line increment is 1 Default page increment is 10.
  • 56. import java.awt.*; import java.awt.event.*; import java.applet.*; /*<applet code="SBDemo" width=300 height=200></applet>*/ public class SBDemo extends Applet implements AdjustmentListener, MouseMotionListener { String msg = ""; Scrollbar vertSB, horzSB; int width = 300, height = 200; public void init() { vertSB = new Scrollbar(Scrollbar.VERTICAL,0, 1, 0,height); horzSB = new Scrollbar(Scrollbar.HORIZONTAL,0, 1, 0, width); add(vertSB); add(horzSB); vertSB.addAdjustmentListener(this); horzSB.addAdjustmentListener(this); addMouseMotionListener(this); } public void adjustmentValueChanged(AdjustmentEvent ae) { repaint(); } public void mouseDragged(MouseEvent me) { int x = me.getX(); int y = me.getY(); vertSB.setValue(y); horzSB.setValue(x); repaint(); } public void mouseMoved(MouseEvent me) {} public void paint(Graphics g) { msg = "Vertical: " + vertSB.getValue(); msg += ", Horizontal: " + horzSB.getValue(); g.drawString(msg, 6, 160); } }
  • 57. 1. To create a menu bar, first create an instance of MenuBar class. This class only defines the default constructor. A menu bar contains one or more Menu objects. Constructor: MenuBar( ) Methods: setMenuBar(menubarInstance) menubarInstance.add(menuInstance) 2. Next, create instances of Menu class. Constructors: Menu( ) Menu(String menuName) Methods: menuInstance.add(menuitemInstance) 3. Add menu items using MenuItem class. Constructors: MenuItem( ) MenuItem(String itemName) MenuItem(String itemName, MenuShortcut keyAccel) MenuBar , Menu and MenuItem
  • 58.  You can disable or enable a menu item by using the setEnabled( ) method.  You can determine an item’s status by calling isEnabled( ).  You can change the name of a menu item by calling setLabel( ).  You can retrieve the current name by using getLabel( ).
  • 59. import java.awt.*; public class ExMenubar extends Frame implements ActionListener{ public ExMenubar(){ super("Menubar test"); MenuBar mbar = new MenuBar(); setMenuBar(mbar); 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); setSize(300,400); setVisible(true); //item1.addItem } public static void main(String args[]){ new ExMenubar(); } }
  • 60.  A dialog box is a special window used to alert user or take input from user.  They are similar to frame windows, except that dialog boxes are always child windows of a top-level window.  Also, dialog boxes don’t have menu bars. In other respects, dialog boxes function like frame windows.  You can add controls to them, for example, in the same way that you add controls to a frame window.)  Dialog boxes may be modal or modeless.  When a modal dialog box is active, you cannot access other parts of your program until the dialog box is closed.  When a modeless dialog box is active, you can access other parts of your program. Dialog Boxes
  • 61. Constructors  Dialog(Frame parentWindow, boolean mode)  Dialog(Frame parentWindow, String title, boolean mode)  Here, parentWindow is the owner of the dialog box.  If mode is true, the dialog box is modal. Otherwise, it is modeless.
  • 62. import java.awt.*; public class ExDialog extends Frame{ public ExDialog() { Dialog d = new Dialog(this ,"Dialog", false); d.add("Center", new Label("Dialog Box")); d.add("South“, new Button("OK")); d.pack(); d.setVisible(true); } public static void main(String args[]){ new ExDialog(); } }
  • 63. Canvas A Canvas is a two-dimensional area used to draw some shapes on it using the Graphics. Constructors Canvas() Methods setSize(int width, int height) setBackground(Color )
  • 64. import java.awt.*; public class ExCanvas extends Frame{ public ExCanvas(){ setLayout(new FlowLayout()); Canvas can1 = new Canvas(); can1.setSize(200,100); can1.setBackground(Color.red); add( can1 ); setSize(200,300); setVisible(true); } public static void main(String args[]){ new ExCanvas(); } }
  • 65. Panel This is simplest invisible container that holds GUI components. It is recommended that you place the user interface components in panels and place the panels in a frame. You can also place panels in a panel. FlowLayout is the default layout for panel. Panel() Panel(LayoutManager layout)
  • 66. import java.awt.*; public class ExPanel extends Frame{ public ExPanel(){ setLayout(new FlowLayout()); Panel pan1 = new Panel(); pan1.setSize(200,100); pan1.setBackground(Color.red); pan1.setLocation(50,50); add( pan1 ); Button button1 = new Button(“ok"); Button button2 = new Button(“cancel"); pan1.add( button1 ); pan1.add( button2 ); } public static void main(String args[]){ new ExPanel(); } }
  • 67. ScrollPane It is similar to a panel. It can hold only one Component.  If size of the component held is larger than the size of the ScrollPane, Scroll bars will be automatically generated.  It does not have a LayoutManager Constructors ScrollPane()
  • 68. import java.awt.*; public class ExScrollPane extends Frame{ public ExScrollPane(){ ScrollPane sPane1 = new ScrollPane(); sPane1.setSize(200,100); sPane1.setBackground(Color.red); sPane1.setLocation(50,50); Panel pan1 = new Panel(); TextArea text1 = new TextArea(300,500); pan1.add( text1 ); sPane1.add( pan1 ); add( sPane1 ); setSize(200,300); setVisible(true); } public static void main(String args[]){ new ExScrollPane(); } }
  • 69. Graphics  Graphics object draws pixels on the screen that represent text and other graphical shapes such as lines, ovals, rectangles, polygons etc.  The graphics class is an abstract class(i.e. Graphics objects can not be instantiated.)  A graphics context is encapsulated by the Graphics class and is obtained in two ways:  It is passed to an applet when one of its various methods, such as paint( ) or update( ), is called.  It is returned by the getGraphics() method of Component.
  • 70. public void paint(Graphics g)  The paint(Graphics g) method is common to all components and containers.  It is needed if you do any drawing or painting other than just using standard GUI components.  Never call paint(Graphics g), call repaint( ) How does the paint(Graphics g) method get called?  It is called automatically by Java whenever the component or container is loaded, resized, minimized, maximized.  You can cause the paint method to be called at any time by calling the component’s repaint() method.
  • 71. class myFrame extends Frame{ …….. …….. public void paint(Graphics g){ g.drawOval(x1,y1,width,height); …… } }
  • 72. The repaint() method will do two things: 1. It calls update(Graphics g), which writes over the old drawing in background color (thus erasing it). 2. It then calls paint(Graphics g) to do the drawing. Java coordinate system ( 0,0) x y (x,y)
  • 73. Graphics methods for drawing shapes g.drawString (str, x, y); //Puts string at x,y g.drawLine( x1, y1, x2, y2 ) //Line from x1, y1 to x2, y2 g.drawRect( x1, y1, width, height) //Draws rectangle with upper left corner x1, y1 g.fillRect(x1, y1, width, height) //Draws a solid rectangle. g.drawRoundRect( x, y, width, height,arcWidth, arcHeight ) //Draws rectangle with rounded corners. g.fillRoundRect( x, y, width, height,arcWidth, arcHeight ) //Draws a solid rectangle with rounded corners.
  • 74. arc width width height (x, y) arc height (x, y) height width drawRoundRect parameters drawOval parameters
  • 75. g.drawOval(x1, y1, width, height) //Draws an oval with specified width and height. The bounding rectangle’s top left corner is at the coordinate (x,y).The oval touches all four sides all four sides of the bounding rectangle. g.fillOval(x1, y1, width, height) //Draws a filled oval. g.setColor(Color.RED) //Sets color, it is remain active until new color is set.
  • 76. g.drawArc(x1, y1, width, height, startAngle,arcAngle) //Draws an arc relative to the bounding rectangle’s top-left coordinates with the specified width and height. The arc segment is drawn starting at startAngle and sweeps arcAngle degrees. 180 180 270 270 90 90 0 0 Positive angle Negative angle
  • 77. Drawing Polygons and Polylines  Polygon - multisided shape  Polyline - series of connected points  Methods of class Polygon drawPolygon( xPoints[], yPoints[], points ) //Draws a polygon, with x and y points specified in arrays. Last argument specifies number of points //Closed polygon, even if last point different from first. drawPolyline ( xPoints[], yPoints[],points ) //Draws a polyline
  • 78. Font  Fonts are encapsulated by the Font class.  To select a new font, you must first construct a Font object that describes that font. Font(String fontName, int fontStyle, int pointSize) //Here, fontName specifies the name of the desired font.  All Java environments will support the following fonts: Dialog, DialogInput, Sans Serif, Serif, Monospaced and Symbol.  The style of the font is specified by fontStyle. It may consist of one or more of these three constants: Font.PLAIN Font.BOLD Font.ITALIC
  • 79. void setFont(Font fontObj) //To set the specified Font . //It is defined in Component class. //Here, fontObj is the object that contains the desired font. Font getFont() //To obtain information about the currently selected font which is defined in Graphics class Methods in Font Class: String getName() //To get the name of the Font String getFamily(); //To get family name of the Font int getSize(); //To get the size of the Font int getStyle(); //To get the style of the Font
  • 80. Layout Managers  Arranges and lays out the GUI components on a container.  Every container has a default Layout Manager:  Panel FlowLayout  Window (Frame) BorderLayout  Types: Flow Layout Border Layout Grid Layout Card Layout Gridbag Layout  To set layout manager: myContainer.setLayout( new LayoutManger() );
  • 81. Flow Layout  The Flow Layout manager arranges the components left-to-right, top- to-bottom in the order they were inserted into the container.  When the container is not wide enough to display all the components, the remaining components are placed in the next row, etc.  By default each row is centered.  The line alignment can be:  FlowLayout.LEFT  FlowLayout.CENTER  FlowLayout.RIGHT
  • 82. Flow Layout Example English French Greek Japanese German Spanish Portuguese Arabic Chinese Russian
  • 83. Flow Layout Constructors  FlowLayout() //A centered alignment and a default 5-unit horizontal and vertical gap.  FlowLayout(align) align – alignment used by the manager. A default 5-unit horizontal and vertical gap.  FlowLayout(align, hgap, vgap) //align – alignment used by the manager //hgap – horizontal gaps between components //vgap – vertical gaps between components
  • 84. Border Layout  The Border Layout manager arranges components into five regions: North, South, East, West, and Center.  Components in the North and South are set to their natural heights and horizontally stretched to fill the entire width of the container.  Components in the East and West are set to their natural widths and stretched vertically to fill the entire width of the container.  The Center component fills the space left in the center of the container.  If one or more of the components, except the Center component, are missing then the rest of the existing components are stretched to fill the remaining space in the container.  The positional constraints are: BorderLayout.NORTH BorderLayout.SOUTH BorderLayout.EAST BorderLayout.WEST BorderLayout.CENTER
  • 85. BorderLayout Manager North South Center East West To set BorderLayout: add( new Button(“ok”), BorderLayout.NORTH);
  • 86. Border Layout Constructors  BorderLayout() //No vertical or horizontal gaps.  BorderLayout(hgap, vgap) //hgap – horizontal gaps between components //vgap – vertical gaps between components
  • 87. Grid Layout  Container is divided into a grid where components are placed in rows and columns.  Every component has the same width and height.  Example
  • 88. Grid Layout Constructors  GridLayout() //A single row and no vertical or horizontal gaps.  GridLayout(r, c) //r – number of rows in the layout //c – number of columns in the layout //No vertical or horizontal gaps.  GridLayout(r, c, hgap, vgap) //r – number of rows in the layout //c – number of columns in the layout //hgap – horizontal gaps between components //vgap – vertical gaps between components
  • 89. CardLayout  CardLayout places components (usually panels) on top of each other in a stack like a deck of cards.  You can see only one card at a time.  By default, the first card is visible.  We can put a cards on top using another control by using the methods next(), previous(), first(), last(), and show().
  • 90. Methods: public void first(Container parent); public void next(Container parent); public void previous(Container parent); public void last(Container parent); public void show(Container parent, String name); First Card add(component, name) New Card Constructor: CardLayout()
  • 91. import java.awt.*; import java.awt.event.*; public class CardLayoutDemo extends Frame implements ActionListener, MouseListener { Checkbox winXP, winVista, solaris, mac; Button Win, Other; Panel osCards; CardLayout cardLO; public CardLayoutDemo(){ setLayout(new BorderLayout()); cardLO = new CardLayout(); Panel tabs=new Panel(); Win = new Button("Windows"); Other = new Button("Other"); tabs.add(Win); tabs.add(Other); add(tabs,BorderLayout.NORTH); osCards = new Panel(); osCards.setLayout(cardLO); // set panel layout to card layout Panel winPan = new Panel(); winXP = new Checkbox("Windows XP", null, true); winVista = new Checkbox("Windows Vista"); // add Windows check boxes to a panel winPan.setBackground(Color.CYAN); winPan.add(winXP); winPan.add(winVista);
  • 92. // Add other OS check boxes to a panel Panel otherPan = new Panel(); solaris = new Checkbox("Solaris"); mac = new Checkbox("Mac OS"); otherPan.setBackground(Color.RED); otherPan.add(solaris); otherPan.add(mac); // add panels to card deck panel osCards.add(winPan, "Windows"); osCards.add(otherPan, "Other"); // add cards to main applet panel add(osCards,BorderLayout.CENTER); // register to receive action events Win.addActionListener(this); Other.addActionListener(this); // register mouse events addMouseListener(this); setSize(250,250); setVisible(true); }
  • 93. public Insets getInsets(){ return new Insets(30,30,30,30); } public void mousePressed(MouseEvent me) { cardLO.next(osCards); } public void mouseClicked(MouseEvent me) { } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { } public void mouseReleased(MouseEvent me) { } public void actionPerformed(ActionEvent ae) { if(ae.getSource() == Win) { cardLO.first(osCards); //cardLO.show(osCards, "Windows"); } else { cardLO.last(osCards); //cardLO.show(osCards, "Other"); } } public static void main(String arg[]){ new CardLayoutDemo(); } }
  • 94. GridBagLayout Layout Manager  Flexible GridBagLayout  Components can vary in size  Components can occupy multiple rows and columns  Components can be added in any order  There are two classes that are used: GridBagLayout: Provides the overall layout manager. GridBagConstraints: Defines the properties of each component in the grid such as placement, dimension and alignment
  • 95. Specifying a GridBagLayout  To use a gridbag layout, you must declare the GridBagLayout and GridBagConstaraints object and attach the layout to your applet. Example: GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); setLayout(gridbag);
  • 96. Setting Constraints for Components  For each component that you add to the gridbag layout, you must first set an instance of the GridBagContraints class.  Let us look at an example: constraints.gridx = 0 // put component in first cell. constraints.gridy = 0 gridbag.setConstraints(button1, constraints); //set the constraints to button1. add(button1); //add to the Frame
  • 98. The following are the constraints to control the component: gridx, gridy, gridwidth, gridheight, weightx, weighty, ipadx, ipady , fill constraints.gridx=0; //To set the column (Default is RELATIVE). constraints.gridy=0; //To set the row (Default is RELATIVE). constraints.gridwidth = 2; //Joins two cells horizontally constraints.gridheight = 2; //Joins two cells vertically //Default value is 1. GridBagConstraints Data Members
  • 99. constraints.weightx=2; //Determines horizontal spacing between cells. constraints.weighty=3; // Determines vertical spacing between cells. //Default value is 0. constraints.ipadx=2; //Specifies extra horizontal space that surrounds a component within a cell. constraints.ipady=0; //Specifies extra vertical space that surrounds a component within a cell. //Default is 0. fill //Resizing rules for a component smaller than its display area; //HORIZONTAL makes component as wide as the display area; //VERTICAL as tall; BOTH expands it vertically and horizontally. //NONE (default) is default. Examples: constraints.fill = GridBagConstraints.BOTH; //Fill cell height & width constraints.fill = GridBagConstraints.HORIZONTAL; //Fill cell width