SlideShare a Scribd company logo
1 of 48
ο‚— Java AWT (Abstract Window Toolkit) is an API to
develop GUI based applications in java.
ο‚— Java AWT components are platform-dependent i.e.
components are displayed according to the view of
operating system.
ο‚— AWT is heavyweight i.e. its components are using the
resources of OS.
ο‚— The java.awt package provides classes for AWT api
such as TextField, Label, TextArea,
RadioButton, CheckBox, List etc.
ο‚— The Container is a component in
AWT that can contain another
components like buttons, textfields,
labels etc. The classes that extends
Container class are known as
container such as Frame, Dialog and
Panel.
ο‚— The window is the container that
have no borders and menu bars. You
must use frame, dialog or another
window for creating a window.
ο‚— The Panel is the container that
doesn't contain menu bars. It can
have other components like button,
textfield etc.
ο‚— The Frame is the container that
contain title bar and can have menu
bars. It can have other components
like button, textfield etc.
1
ο‚— Label: A Label object is a component for placing text in a container.
ο‚— Button:This class creates a labeled button.
ο‚— Check Box: A check box is a graphical component that can be in either an on (true) or off (false) state.
ο‚— Check Box Group: The CheckboxGroup class is used to group the set of checkbox.
ο‚— List: The List component presents the user with a scrolling list of text items.
ο‚— Text Field: A TextField object is a text component that allows for the editing of a single line of text.
ο‚— Text Area : A TextArea object is a text component that allows for the editing of a multiple lines of text.
ο‚— Choice: A Choice control is used to show pop up menu of choices. Selected choice is shown on the top
of the menu.
ο‚— Canvas: A Canvas control represents a rectangular area where application can draw something or can
receive inputs created by user.
ο‚— Image:An Image control is superclass for all image classes representing graphical images.
ο‚— Scroll Bar: A Scrollbar control represents a scroll bar component in order to enable user to select from
range of values.
Method Description
public void add(Component c) inserts a component.
public void setSize(int width,int
height)
sets the size (width and height) of
the component.
public void
setLayout(LayoutManager m)
defines the layout manager for
the component.
public void setVisible(boolean
status)
changes the visibility of the
component, by default false.
ο‚— we can create a frame in AWT in two ways.
ο‚— By extending Frame class (inheritance)
ο‚— By creating the object of Frame class (association)
AWT Example by Inheritanceimport java.awt.*;
import java.awt.event.*;
class FrameEx1 extends Frame{
FrameEx1(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
}
public static void main(String args[]){
FrameEx1 f=new FrameEx1();
}
}
AWT Example by Association
import java.awt.*;
class FrameEx2{
FrameEx2(){
Frame f=new Frame();
Button b=new Button("click Here");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
FrameEx2 f=new FrameEx2();
}
}
Event Classes Listener Interfaces
ActionEvent ActionListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
ο‚— For registering the component with the Listener, many classes provide
the registration methods. For example:
ο‚— Button
public void addActionListener(ActionListener a){}
ο‚— MenuItem
public void addActionListener(ActionListener a){}
ο‚— TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
ο‚— TextArea
public void addTextListener(TextListener a){}
ο‚— Checkbox
public void addItemListener(ItemListener a){}
ο‚— Choice
public void addItemListener(ItemListener a){}
ο‚— List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}
ο‚— The button class is used to create a labeled button that has platform
independent implementation. The application result in some action
when the button is pushed.
ο‚— Syntax:
public class Button extends Component implements Accessible
ο‚— Constructors:
ο‚— Button():Constructs a button with an empty string for its label.
ο‚— Button(String text): Constructs a new button with specified label.
ο‚— Methods:
ο‚— void addActionListener(ActionListener l):Adds the specified action
listener to receive action events from this button.
ο‚— void setLabel(String label): Sets the button's label to be the specified
string.
ο‚— String getLabel(): Gets the label of this button.
Label Class :The object of Label class is a component for placing text in a container. It is
used to display a single line of read only text. The text can be changed by an application
but a user cannot edit it directly.
Syntax:public class Label extends Component implements Accessible
Methods;
int getAlignment(): Gets the current alignment of this label.
String getText(): Gets the text of this label.
void setAlignment(int alignment): Sets the alignment for this label to the specified
alignment.[CENTER,LEFT,RIGHT]
void setText(String text): Sets the text for this label to the specified text.
Constructor
1 Label()
Constructs an empty label.
2 Label(String text)
Constructs a new label with the specified string of text, left justified.
3 Label(String text, int alignment)
Constructs a new label that presents the specified string of text with the
specified alignment.
ο‚— The object of a TextField class is a text component that allows the editing of a
single line text. It inherits TextComponent class.
ο‚— Syntax: public class TextField extends TextComponent
ο‚— Constructor:
ο‚— TextField():Constructs a new text field.
ο‚— TextField(int columns): Constructs a new empty text field with the specified
number of columns.
ο‚— TextField(String text): Constructs a new text field initialized with the
specified text.
ο‚— TextField(String text, int columns): Constructs a new text field initialized
with the specified text to be displayed, and wide enough to hold the specified
number of columns.
ο‚— Method :
ο‚— void addActionListener(ActionListener l): Adds the specified action
listener to receive action events from this text field.
ο‚— int getColumns(): Gets the number of columns in this text field.
ο‚— void setColumns(int columns): Sets the number of columns in this text
field.
ο‚— void setText(String t): Sets the text that is presented by this text component
to be the specified text.
import java.awt.*;
import java.awt.event.*;
public class ButtonExample {
ButtonExample(){
Frame f=new Frame("Button Example");
Label l1;
l1=new Label("First Label.");
l1.setBounds(30,100, 100,30);
final TextField tf=new TextField();
tf.setBounds(100,100, 100,20);
Button b=new Button("Click Here");
b.setBounds(70,150,60,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Java.");
}
});
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
f.add(b);
f.add(tf);
f.add(l1);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
ο‚— The TextArea control in AWT provide us multiline editor area. When the text
in the text area become larger than the viewable area the scroll bar is
automatically appears which help us to scroll the text up & down and right &
left.
ο‚— Constructor:
ο‚— TextArea(): Constructs a new text area with the empty string as text.
ο‚— TextArea(int rows, int columns): Constructs a new text area with the
specified number of rows and columns and the empty string as text.
ο‚— TextArea(String text): Constructs a new text area with the specified text.
ο‚— TextArea(String text, int rows, int columns): Constructs a new text area
with the specified text, and with the specified number of rows and columns.
ο‚— TextArea(String text, int rows, int columns, int scrollbars)
ο‚— Constructs a new text area with the specified text, and with the rows, columns,
and scroll bar visibility as specified.
ο‚— static int SCROLLBARS_BOTH -- Create and display both vertical and
horizontal scrollbars.
ο‚— static int SCROLLBARS_HORIZONTAL_ONLY -- Create and display
horizontal scrollbar only.
ο‚— static int SCROLLBARS_NONE -- Do not create or display any scrollbars for
the text area.
ο‚— static int SCROLLBARS_VERTICAL_ONLY -- Create and display vertical
scrollbar only.
Method
ο‚— void append(String str): Appends the given text to the
text area's current text.
ο‚— int getColumns(): Returns the number of columns in this
text area.
ο‚— void insert(String str, int pos): Inserts the specified text
at the specified position in this text area.
ο‚— void replaceRange(String str, int start, int
end):Replaces text between the indicated start and end
positions with the specified replacement text.
ο‚— void setColumns(int columns): Sets the number of
columns for this text area.
ο‚— void setRows(int rows): Sets the number of rows for this
text area.
ο‚— int getRows(): Returns the number of rows in the text
area.
import java.awt.*;
public class TextAreaExample
{
TextAreaExample(){
Frame f= new Frame();
TextArea area=new TextArea("Welcome to KJC");
area.setBounds(10,30, 300,300);
f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
area.insert(β€œIII B.Sc Java”,150,150);
}
public static void main(String args[])
{
new TextAreaExample();
}
}
ο‚— Checkbox control is used to turn an option on(true) or off(false).
There is label for each checkbox representing what the checkbox
does.The state of a checkbox can be changed by clicking on it.
ο‚— Class constructors:
ο‚— Checkbox(): Creates a check box with an empty string for its
label.
ο‚— Checkbox(String label): Creates a check box with the specified
label.
ο‚— Checkbox(String label, boolean state):Creates a check box
with the specified label and sets the specified state.
ο‚— Checkbox(String label, boolean state, CheckboxGroup
group): Constructs a Checkbox with the specified label, set to
the specified state, and in the specified check box group.
ο‚— Checkbox(String label, CheckboxGroup group, boolean
state): Creates a check box with the specified label, in the
specified check box group, and set to the specified state.
ο‚— Class methods:
ο‚— void addItemListener(ItemListener l): Adds the
specified item listener to receive item events from this
check box.
ο‚— String getLabel(): Gets the label of this check box.
ο‚— boolean getState():Determines whether this check
box is in the on or off state.
ο‚— void setState(boolean state); Sets the state of this
check box to the specified state.
import java.awt.*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java", true);
checkbox2.setBounds(100,150, 50,50);
f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxExample();
}
}
ο‚— The CheckboxGroup class is used to group the set of
checkbox.
ο‚— Constructor:
ο‚— CheckboxGroup(): Creates a new instance of
CheckboxGroup.
ο‚— Methods:
ο‚— Checkbox getSelectedCheckbox(): Gets the current
choice from this check box group.
ο‚— void setSelectedCheckbox(Checkbox box): Sets the
currently selected check box in this group to be the
specified check box.
ο‚— Choice control is used to show pop up menu of choices.
Selected choice is shown on the top of the menu.
ο‚— Constructor:
ο‚— Choice(): Creates a new choice menu.
ο‚— Methods:
ο‚— void add(String item):Adds an item to this Choice menu.
ο‚— void addItemListener(ItemListener l):Adds the
specified item listener to receive item events from this
Choice menu.
ο‚— void insert(String item, int index):Inserts the item into
this choice at the specified position.
ο‚— void remove(int position):Removes an item from the
choice menu at the specified position.
ο‚— void remove(String item):Removes the first occurrence
of item from the Choice menu.
ο‚— The List represents a list of text items. The list can be configured
that user can choose either one item or multiple items.
ο‚— Constructors:
ο‚— List(): Creates a new scrolling list.
ο‚— List(int rows):Creates a new scrolling list initialized with the
specified number of visible lines.
ο‚— List(int rows, boolean multipleMode):Creates a new scrolling
list initialized to display the specified number of rows.
ο‚— Methods:
ο‚— void add(String item):Adds the specified item to the end of
scrolling list.
ο‚— void add(String item, int index):Adds the specified item to
the the scrolling list at the position indicated by the index.
ο‚— void addItemListener(ItemListener l):Adds the specified
item listener to receive item events from this list.
ο‚— String getItem(int index):Gets the item associated with the
specified index.
ο‚— int getItemCount():Gets the number of items in the list.
public class ListExample
{
ListExample(){
Frame f= new Frame();
List l1=new List(5);
l1.setBounds(100,100, 75,75);
l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");
l1.add("Item 4");
l1.add("Item 5");
f.add(l1);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}
}
ο‚— The object of Scrollbar class is used to add horizontal
and vertical scrollbar. Scrollbar is a GUI component
allows us to see invisible number of rows and
columns.Constructor:
ο‚— Scrollbar(): Constructs a new vertical scroll bar.
ο‚— Scrollbar(int orientation): Constructs a new scroll bar
with the specified orientation.
ο‚— Scrollbar(int orientation, int value, int visible, int
minimum, int maximum):Constructs a new scroll bar
with the specified orientation, initial value, visible
amount, and minimum and maximum values.
ο‚— static int HORIZONTAL --A constant that indicates a
horizontal scroll bar.
ο‚— static int VERTICAL --A constant that indicates a
vertical scroll bar.
ο‚— void addAdjustmentListener(AdjustmentListener l)
Adds the specified adjustment listener to receive instances of
AdjustmentEvent from this scroll bar.
ο‚— int getMaximum():Gets the maximum value of this scroll
bar.
ο‚— int getMinimum():Gets the minimum value of this scroll
bar.
ο‚— int getOrientation():Returns the orientation of this scroll
bar.
ο‚— int getValue():Gets the current value of this scroll bar.
ο‚— void setMaximum(int newMaximum):Sets the
maximum value of this scroll bar.
ο‚— void setMinimum(int newMinimum):Sets the
minimum value of this scroll bar.
ο‚— void setOrientation(int orientation): Sets the
orientation for this scroll bar.
Layout Manager
ο‚— Layout is the arrangement of components within the
container. i.e>placing the components at a particular
position within the container.
ο‚— The task of layouting the controls is done
automatically by the Layout Manager.
ο‚— If we do not use layout manager then also the
components are positioned by the default layout
manager.
ο‚— The layout managers adapt to the dimensions of
appletviewer or the application window.
ο‚— The layout manager is associated with every Container
object.
ο‚— The class BorderLayout arranges the components to fit in the five
regions: east, west, north, south and center.
ο‚— Each region can contain only one component and each component in
each region is identified by the corresponding constant NORTH,
SOUTH, EAST, WEST, and CENTER
ο‚— Constructor:
ο‚— BorderLayout():Constructs a new border layout with no gaps between
components.
ο‚— BorderLayout(int hgap, int vgap): Constructs a border layout with the
specified gaps between components.
ο‚— static String CENTER -- The center layout constraint (middle of
container).
ο‚— static String EAST -- The east layout constraint (right side of
container).
ο‚— static String NORTH -- The north layout constraint (top of
container).
ο‚— static String SOUTH -- The south layout constraint (bottom of
container).
ο‚— static String WEST -- The west layout constraint (left side of
container).
ο‚— void addLayoutComponent(String name,
Component comp): If the layout manager uses a per-
component string, adds the component comp to the
layout, associating it with the string specified by
name.
ο‚— int getHgap(): Returns the horizontal gap between
components.
ο‚— int getVgap():Returns the vertical gap between
components.
ο‚— void setHgap(int hgap):Sets the horizontal gap
between components.
ο‚— void setVgap(int vgap): Sets the vertical gap between
components.
import java.awt.*;
public class Border {
Frame f;
Border(){
f=new Frame();
Button b1=new Button("NORTH");;
Button b2=new Button("SOUTH");;
Button b3=new Button("EAST");;
Button b4=new Button("WEST");;
Button b5=new Button("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
ο‚— The GridLayout is used to arrange the components in
rectangular grid. One component is displayed in each
rectangle.
ο‚— Constructors:
ο‚— GridLayout(): creates a grid layout with one column
per component in a row.
ο‚— GridLayout(int rows, int columns): creates a grid
layout with the given rows and columns but no gaps
between the components.
ο‚— GridLayout(int rows, int columns, int hgap, int vgap):
creates a grid layout with the given rows and columns
alongwith given horizontal and vertical gaps.
import java.awt.*;
import javax.swing.*;
public class GridLayoutEx{
Frame f;
GridLayoutEx(){
f=new JFrame();
Button b1=new Button("1");
Button b2=new Button("2");
Button b3=new Button("3");
Button b4=new Button("4");
Button b5=new Button("5");
Button b6=new Button("6");
Button b7=new Button("7");
Button b8=new Button("8");
Button b9=new Button("9");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new GridLayoutEx();
}
}
ο‚— The FlowLayout is used to arrange the components in a line,
one after another (in a flow). It is the default layout of applet or
panel.
Fields of FlowLayout class
ο‚— public static final int LEFT
ο‚— public static final int RIGHT
ο‚— public static final int CENTER
ο‚— public static final int LEADING
ο‚— public static final int TRAILING
ο‚— Constructors of FlowLayout class:
ο‚— FlowLayout(): creates a flow layout with centered alignment and
a default 5 unit horizontal and vertical gap.
ο‚— FlowLayout(int align): creates a flow layout with the given
alignment and a default 5 unit horizontal and vertical gap.
ο‚— FlowLayout(int align, int hgap, int vgap): creates a flow layout
with the given alignment and the given horizontal and
import java.awt.*;
public class FlowLayoutEx{
Frame f;
FlowLayoutEx(){
f=new Frame();
Button b1=new Button("1");
Button b2=new Button("2");
Button b3=new Button("3");
Button b4=new Button("4");
Button b5=new Button("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new FlowLayoutEx();
}
}
ο‚— The CardLayout class manages the components in such a
manner that only one component is visible at a time. It treats
each component as a card that is why it is known as CardLayout.
ο‚— Constructors of CardLayout class
ο‚— CardLayout(): creates a card layout with zero horizontal and
vertical gap.
ο‚— CardLayout(int hgap, int vgap): creates a card layout with the
given horizontal and vertical gap.
ο‚— methods of CardLayout class
ο‚— public void next(Container parent): is used to flip to the next
card of the given container.
ο‚— public void previous(Container parent): is used to flip to the
previous card of the given container.
ο‚— public void first(Container parent): is used to flip to the first
card of the given container.
ο‚— public void last(Container parent): is used to flip to the last card
of the given container.
ο‚— public void show(Container parent, String name): is used to flip
to the specified card with the given name.
import java.awt.*;
import java.awt.event.*;
Import java.swing.*;
public class CardLayoutExample extends Jrame implements ActionListener{
CardLayout card;
Button b1,b2,b3;
Container c;
CardLayoutExample(){
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
b1=new Button("Apple");
b2=new Button("Boy");
b3=new Button("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3);
}
public void actionPerformed(ActionEvent e) {
card.next(c);
}
public static void main(String[] args) {
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
ο‚— The Java GridBagLayout class is used to align components
vertically, horizontally or along their baseline.
ο‚— The components may not be of same size. Each
GridBagLayout object maintains a dynamic, rectangular
grid of cells.
ο‚— The GridBagLayout manages each component's minimum
and preferred sizes in order to determine component's size.
ο‚— Constructor:
ο‚— GridBagLayout(): Creates a grid bag layout manager.
ο‚— Method :
ο‚— void addLayoutComponent(Component comp, Object
constraints):Adds the specified component to the layout,
using the specified constraints object.
ο‚— void addLayoutComponent(String name, Component
comp): Adds the specified component with the specified
name to the layout.
ο‚— void removeLayoutComponent(Component
comp):Removes the specified component from this layout.
Menu Bars and Menus
ο‚— The object of MenuItem class adds a simple labeled menu
item on menu. The items used in a menu must belong to
the MenuItem or any of its subclass.
ο‚— Constructor :
ο‚— MenuBar(): Creates a new menu bar.
ο‚— Method :
ο‚— Menu add(Menu m):Adds the specified menu to the
menu bar.
ο‚— Menu getHelpMenu():Gets the help menu on the menu b
ο‚— Menu getMenu(int i):Gets the specified menu.
ο‚— int getMenuCount(): Gets the number of menus on the
menu bar.
import java.awt.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
menu.add(i1);
menu.add(i2);
submenu.add(i3);
submenu.add(i4);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
}
ο‚— The Dialog control represents a top level window with a border
and a title used to take some form of input from the user. It
inherits the Window class.
ο‚— Modal dialog or modeless
ο‚— Unlike Frame, it doesn't have maximize and minimize buttons.
ο‚— Dialog(Dialog owner): Constructs an initially invisible, modeless
Dialog with the specified owner Dialog and an empty title.
ο‚— Dialog(Dialog owner, String title):Constructs an initially
invisible, modeless Dialog with the specified owner Dialog and
title.
ο‚— Dialog(Frame owner):Constructs an initially invisible, modeless
Dialog with the specified owner Frame and an empty title.
ο‚— Dialog(Frame owner, boolean modal):Constructs an initially
invisible Dialog with the specified owner Frame and modality
and an empty title.
ο‚— Dialog(Frame owner, String title):Constructs an initially
invisible, modeless Dialog with the specified owner Frame and
title.
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static Dialog d;
DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new Label ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
ο‚— FileDialog control represents a dialog window from which the user
can select a file.
ο‚— static int LOAD -- This constant value indicates that the purpose of the
file dialog window is to locate a file from which to read.
ο‚— static int SAVE -- This constant value indicates that the purpose of the
file dialog window is to locate a file to which to write.
ο‚— Constructor:
ο‚— FileDialog(Dialog parent): Creates a file dialog for loading a file.
ο‚— FileDialog(Dialog parent, String title):Creates a file dialog window with
the specified title for loading a file.
ο‚— FileDialog(Dialog parent, String title, int mode): Creates a file dialog
window with the specified title for loading or saving a file.
ο‚— FileDialog(Frame parent): Creates a file dialog for loading a file.
ο‚— FileDialog(Frame parent, String title): Creates a file dialog window
with the specified title for loading a file.
ο‚— FileDialog(Frame parent, String title, int mode): Creates a file dialog
window with the specified title for loading or saving a file.
ο‚— Method
ο‚— String getDirectory(): Gets the directory of this file
dialog.
ο‚— String getFile(): Gets the selected file of this file dialog.
ο‚— int getMode(): Indicates whether this file dialog box
is for loading from a file or for saving to a file.
ο‚— void setMode(int mode): Sets the mode of the file
dialog.
import java.awt.*;
import java.awt.event.*;
public class FileControlDemo {
Frame f= new Frame("Java AWT Examples");
Label l1=new Label(),l2=new Label();
Panel controlPanel=new Panel();
public FileControlDemo(){
prepareGUI();
}
public static void main(String[] args){
FileControlDemo awtControlDemo = new FileControlDemo();
awtControlDemo.showFileDialogDemo();
}
private void prepareGUI(){
f f.setSize(400,400);
f.setLayout(new GridLayout(3, 1));
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
l1.setAlignment(Label.CENTER);
l2.setAlignment(Label.CENTER);
l2.setSize(350,100);
controlPanel.setLayout(new FlowLayout());
f.add(l1);
f.add(controlPanel);
f.add(l2);
f.setVisible(true);
}
private void showFileDialogDemo(){
l1.setText("Control in action: FileDialog");
final FileDialog fileDialog = new FileDialog(f,"Select file");
Button showFileDialogButton = new Button("Open File");
showFileDialogButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fileDialog.setVisible(true);
l2.setText("File Selected :" + fileDialog.getDirectory() + fileDialog.getFile());
}
});
controlPanel.add(showFileDialogButton);
f.setVisible(true);
}
}
Adapter Class
ο‚— Adapter classes provide an implementation of listener
interfaces. When you inherit the adapter class
implementation for all methods is not mandatory
ο‚— java.awt.event
Adapter Class Listener Interface
WindowAdapter WindowListener
KeyAdapter
KeyListener
MouseAdapter
MouseListener
MouseMotionAdapter
MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
Mouse Adapter
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter{
Frame f;
MouseAdapterExample(){
f=new Frame("Mouse Adapter");
f.addMouseListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
Graphics g=f.getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
public static void main(String[] args) {
new MouseAdapterExample();
}
}
MouseMotionAdapter
import java.awt.*;
import java.awt.event.*;
public class MouseMotionAdapterExample extends MouseMotionAdapter{
Frame f;
MouseMotionAdapterExample(){
f=new Frame("Mouse Motion Adapter");
f.addMouseMotionListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g=f.getGraphics();
g.setColor(Color.ORANGE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public static void main(String[] args) {
new MouseMotionAdapterExample();
}
}
KeyAdapter
import java.awt.*;
import java.awt.event.*;
public class KeyAdapterExample extends KeyAdapter{
Label l;
TextArea area;
Frame f;
KeyAdapterExample(){
f=new Frame("Key Adapter");
l=new Label();
l.setBounds(20,50,200,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
f.add(l);f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void keyReleased(KeyEvent e) {
String text=area.getText();
String words[]=text.split("s");
l.setText("Words: "+words.length+" Characters:"+text.length());
}
public static void main(String[] args) {
new KeyAdapterExample();
}

More Related Content

What's hot

Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in javaGoogle
Β 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)Manisha Keim
Β 
Java package
Java packageJava package
Java packageCS_GDRCST
Β 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
Β 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
Β 
Namespaces in C#
Namespaces in C#Namespaces in C#
Namespaces in C#yogita kachve
Β 
java token
java tokenjava token
java tokenJadavsejal
Β 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object ModelWebStackAcademy
Β 
Javascript functions
Javascript functionsJavascript functions
Javascript functionsAlaref Abushaala
Β 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variablesPushpendra Tyagi
Β 
Php string function
Php string function Php string function
Php string function Ravi Bhadauria
Β 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
Β 

What's hot (20)

Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
Β 
Generics
GenericsGenerics
Generics
Β 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
Β 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
Β 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Β 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
Β 
Awt
AwtAwt
Awt
Β 
Java package
Java packageJava package
Java package
Β 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
Β 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Β 
Namespaces in C#
Namespaces in C#Namespaces in C#
Namespaces in C#
Β 
java token
java tokenjava token
java token
Β 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
Β 
Java swing
Java swingJava swing
Java swing
Β 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
Β 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
Β 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variables
Β 
Php string function
Php string function Php string function
Php string function
Β 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
Β 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Β 

Similar to Unit 5 java-awt (1)

Unit – I-AWT-updated.pptx
Unit – I-AWT-updated.pptxUnit – I-AWT-updated.pptx
Unit – I-AWT-updated.pptxssuser10ef65
Β 
tL19 awt
tL19 awttL19 awt
tL19 awtteach4uin
Β 
DSJ_Unit III.pdf
DSJ_Unit III.pdfDSJ_Unit III.pdf
DSJ_Unit III.pdfArumugam90
Β 
Unit-1 awt advanced java programming
Unit-1 awt advanced java programmingUnit-1 awt advanced java programming
Unit-1 awt advanced java programmingAmol Gaikwad
Β 
java- Abstract Window toolkit
java- Abstract Window toolkitjava- Abstract Window toolkit
java- Abstract Window toolkitJayant Dalvi
Β 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01Ankit Dubey
Β 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01JONDHLEPOLY
Β 
object oriented programming examples
object oriented programming examplesobject oriented programming examples
object oriented programming examplesAbdii Rashid
Β 
Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDrRajeshreeKhande
Β 
Windows Programming with AWT
Windows Programming with AWTWindows Programming with AWT
Windows Programming with AWTbackdoor
Β 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024nehakumari0xf
Β 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024kashyapneha2809
Β 
Abstract Window Toolkit
Abstract Window ToolkitAbstract Window Toolkit
Abstract Window ToolkitRutvaThakkar1
Β 
GUI components in Java
GUI components in JavaGUI components in Java
GUI components in Javakirupasuchi1996
Β 

Similar to Unit 5 java-awt (1) (20)

Unit – I-AWT-updated.pptx
Unit – I-AWT-updated.pptxUnit – I-AWT-updated.pptx
Unit – I-AWT-updated.pptx
Β 
AWT New-3.pptx
AWT New-3.pptxAWT New-3.pptx
AWT New-3.pptx
Β 
tL19 awt
tL19 awttL19 awt
tL19 awt
Β 
DSJ_Unit III.pdf
DSJ_Unit III.pdfDSJ_Unit III.pdf
DSJ_Unit III.pdf
Β 
Unit-1 awt advanced java programming
Unit-1 awt advanced java programmingUnit-1 awt advanced java programming
Unit-1 awt advanced java programming
Β 
java- Abstract Window toolkit
java- Abstract Window toolkitjava- Abstract Window toolkit
java- Abstract Window toolkit
Β 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01
Β 
Treinamento Qt bΓ‘sico - aula III
Treinamento Qt bΓ‘sico - aula IIITreinamento Qt bΓ‘sico - aula III
Treinamento Qt bΓ‘sico - aula III
Β 
13457272.ppt
13457272.ppt13457272.ppt
13457272.ppt
Β 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01
Β 
Java awt
Java awtJava awt
Java awt
Β 
object oriented programming examples
object oriented programming examplesobject oriented programming examples
object oriented programming examples
Β 
Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWT
Β 
Windows Programming with AWT
Windows Programming with AWTWindows Programming with AWT
Windows Programming with AWT
Β 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
Β 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
Β 
Abstract Window Toolkit
Abstract Window ToolkitAbstract Window Toolkit
Abstract Window Toolkit
Β 
AWT.pptx
AWT.pptxAWT.pptx
AWT.pptx
Β 
B.Sc. III(VI Sem) Advance Java Unit3: AWT & Event Handling
B.Sc. III(VI Sem) Advance Java Unit3: AWT & Event HandlingB.Sc. III(VI Sem) Advance Java Unit3: AWT & Event Handling
B.Sc. III(VI Sem) Advance Java Unit3: AWT & Event Handling
Β 
GUI components in Java
GUI components in JavaGUI components in Java
GUI components in Java
Β 

More from DevaKumari Vijay

Unit 1 computer architecture (1)
Unit 1   computer architecture (1)Unit 1   computer architecture (1)
Unit 1 computer architecture (1)DevaKumari Vijay
Β 
Unit 2 monte carlo simulation
Unit 2 monte carlo simulationUnit 2 monte carlo simulation
Unit 2 monte carlo simulationDevaKumari Vijay
Β 
Decisiontree&game theory
Decisiontree&game theoryDecisiontree&game theory
Decisiontree&game theoryDevaKumari Vijay
Β 
Unit2 network optimization
Unit2 network optimizationUnit2 network optimization
Unit2 network optimizationDevaKumari Vijay
Β 
Unit 4 simulation and queing theory(m/m/1)
Unit 4  simulation and queing theory(m/m/1)Unit 4  simulation and queing theory(m/m/1)
Unit 4 simulation and queing theory(m/m/1)DevaKumari Vijay
Β 
Unit4 systemdynamics
Unit4 systemdynamicsUnit4 systemdynamics
Unit4 systemdynamicsDevaKumari Vijay
Β 
Unit 1 introduction to simulation
Unit 1 introduction to simulationUnit 1 introduction to simulation
Unit 1 introduction to simulationDevaKumari Vijay
Β 
Unit2 montecarlosimulation
Unit2 montecarlosimulationUnit2 montecarlosimulation
Unit2 montecarlosimulationDevaKumari Vijay
Β 
Unit 3-Greedy Method
Unit 3-Greedy MethodUnit 3-Greedy Method
Unit 3-Greedy MethodDevaKumari Vijay
Β 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threadsDevaKumari Vijay
Β 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfacesDevaKumari Vijay
Β 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritanceDevaKumari Vijay
Β 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysDevaKumari Vijay
Β 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to JavaDevaKumari Vijay
Β 
Introduction to design and analysis of algorithm
Introduction to design and analysis of algorithmIntroduction to design and analysis of algorithm
Introduction to design and analysis of algorithmDevaKumari Vijay
Β 

More from DevaKumari Vijay (20)

Unit 1 computer architecture (1)
Unit 1   computer architecture (1)Unit 1   computer architecture (1)
Unit 1 computer architecture (1)
Β 
Os ch1
Os ch1Os ch1
Os ch1
Β 
Unit2
Unit2Unit2
Unit2
Β 
Unit 1
Unit 1Unit 1
Unit 1
Β 
Unit 2 monte carlo simulation
Unit 2 monte carlo simulationUnit 2 monte carlo simulation
Unit 2 monte carlo simulation
Β 
Decisiontree&game theory
Decisiontree&game theoryDecisiontree&game theory
Decisiontree&game theory
Β 
Unit2 network optimization
Unit2 network optimizationUnit2 network optimization
Unit2 network optimization
Β 
Unit 4 simulation and queing theory(m/m/1)
Unit 4  simulation and queing theory(m/m/1)Unit 4  simulation and queing theory(m/m/1)
Unit 4 simulation and queing theory(m/m/1)
Β 
Unit4 systemdynamics
Unit4 systemdynamicsUnit4 systemdynamics
Unit4 systemdynamics
Β 
Unit 3 des
Unit 3 desUnit 3 des
Unit 3 des
Β 
Unit 1 introduction to simulation
Unit 1 introduction to simulationUnit 1 introduction to simulation
Unit 1 introduction to simulation
Β 
Unit2 montecarlosimulation
Unit2 montecarlosimulationUnit2 montecarlosimulation
Unit2 montecarlosimulation
Β 
Unit 3-Greedy Method
Unit 3-Greedy MethodUnit 3-Greedy Method
Unit 3-Greedy Method
Β 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
Β 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
Β 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
Β 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
Β 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Β 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
Β 
Introduction to design and analysis of algorithm
Introduction to design and analysis of algorithmIntroduction to design and analysis of algorithm
Introduction to design and analysis of algorithm
Β 

Recently uploaded

Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
Β 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
Β 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
Β 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)Dr. Mazin Mohamed alkathiri
Β 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
Β 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
Β 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
Β 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
Β 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
Β 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
Β 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
Β 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
Β 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
Β 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
Β 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
Β 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
Β 

Recently uploaded (20)

Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
Β 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
Β 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Β 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
Β 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
Β 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
Β 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
Β 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
Β 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
Β 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Β 
Model Call Girl in Tilak Nagar Delhi reach out to us at πŸ”9953056974πŸ”
Model Call Girl in Tilak Nagar Delhi reach out to us at πŸ”9953056974πŸ”Model Call Girl in Tilak Nagar Delhi reach out to us at πŸ”9953056974πŸ”
Model Call Girl in Tilak Nagar Delhi reach out to us at πŸ”9953056974πŸ”
Β 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
Β 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
Β 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
Β 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
Β 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
Β 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
Β 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
Β 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
Β 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
Β 

Unit 5 java-awt (1)

  • 1.
  • 2. ο‚— Java AWT (Abstract Window Toolkit) is an API to develop GUI based applications in java. ο‚— Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system. ο‚— AWT is heavyweight i.e. its components are using the resources of OS. ο‚— The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton, CheckBox, List etc.
  • 3. ο‚— The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel. ο‚— The window is the container that have no borders and menu bars. You must use frame, dialog or another window for creating a window. ο‚— The Panel is the container that doesn't contain menu bars. It can have other components like button, textfield etc. ο‚— The Frame is the container that contain title bar and can have menu bars. It can have other components like button, textfield etc.
  • 4. 1 ο‚— Label: A Label object is a component for placing text in a container. ο‚— Button:This class creates a labeled button. ο‚— Check Box: A check box is a graphical component that can be in either an on (true) or off (false) state. ο‚— Check Box Group: The CheckboxGroup class is used to group the set of checkbox. ο‚— List: The List component presents the user with a scrolling list of text items. ο‚— Text Field: A TextField object is a text component that allows for the editing of a single line of text. ο‚— Text Area : A TextArea object is a text component that allows for the editing of a multiple lines of text. ο‚— Choice: A Choice control is used to show pop up menu of choices. Selected choice is shown on the top of the menu. ο‚— Canvas: A Canvas control represents a rectangular area where application can draw something or can receive inputs created by user. ο‚— Image:An Image control is superclass for all image classes representing graphical images. ο‚— Scroll Bar: A Scrollbar control represents a scroll bar component in order to enable user to select from range of values.
  • 5. Method Description public void add(Component c) inserts a component. public void setSize(int width,int height) sets the size (width and height) of the component. public void setLayout(LayoutManager m) defines the layout manager for the component. public void setVisible(boolean status) changes the visibility of the component, by default false.
  • 6. ο‚— we can create a frame in AWT in two ways. ο‚— By extending Frame class (inheritance) ο‚— By creating the object of Frame class (association)
  • 7. AWT Example by Inheritanceimport java.awt.*; import java.awt.event.*; class FrameEx1 extends Frame{ FrameEx1(){ Button b=new Button("click me"); b.setBounds(30,100,80,30);// setting button position add(b);//adding button into frame setSize(300,300);//frame size 300 width and 300 height setLayout(null);//no layout manager setVisible(true);//now frame will be visible, by default not visible addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); } public static void main(String args[]){ FrameEx1 f=new FrameEx1(); } }
  • 8. AWT Example by Association import java.awt.*; class FrameEx2{ FrameEx2(){ Frame f=new Frame(); Button b=new Button("click Here"); b.setBounds(30,50,80,30); f.add(b); f.setSize(300,300); f.setLayout(null); f.setVisible(true); } public static void main(String args[]){ FrameEx2 f=new FrameEx2(); } }
  • 9. Event Classes Listener Interfaces ActionEvent ActionListener ItemEvent ItemListener TextEvent TextListener AdjustmentEvent AdjustmentListener WindowEvent WindowListener ComponentEvent ComponentListener ContainerEvent ContainerListener FocusEvent FocusListener
  • 10. ο‚— For registering the component with the Listener, many classes provide the registration methods. For example: ο‚— Button public void addActionListener(ActionListener a){} ο‚— MenuItem public void addActionListener(ActionListener a){} ο‚— TextField public void addActionListener(ActionListener a){} public void addTextListener(TextListener a){} ο‚— TextArea public void addTextListener(TextListener a){} ο‚— Checkbox public void addItemListener(ItemListener a){} ο‚— Choice public void addItemListener(ItemListener a){} ο‚— List public void addActionListener(ActionListener a){} public void addItemListener(ItemListener a){}
  • 11. ο‚— The button class is used to create a labeled button that has platform independent implementation. The application result in some action when the button is pushed. ο‚— Syntax: public class Button extends Component implements Accessible ο‚— Constructors: ο‚— Button():Constructs a button with an empty string for its label. ο‚— Button(String text): Constructs a new button with specified label. ο‚— Methods: ο‚— void addActionListener(ActionListener l):Adds the specified action listener to receive action events from this button. ο‚— void setLabel(String label): Sets the button's label to be the specified string. ο‚— String getLabel(): Gets the label of this button.
  • 12. Label Class :The object of Label class is a component for placing text in a container. It is used to display a single line of read only text. The text can be changed by an application but a user cannot edit it directly. Syntax:public class Label extends Component implements Accessible Methods; int getAlignment(): Gets the current alignment of this label. String getText(): Gets the text of this label. void setAlignment(int alignment): Sets the alignment for this label to the specified alignment.[CENTER,LEFT,RIGHT] void setText(String text): Sets the text for this label to the specified text. Constructor 1 Label() Constructs an empty label. 2 Label(String text) Constructs a new label with the specified string of text, left justified. 3 Label(String text, int alignment) Constructs a new label that presents the specified string of text with the specified alignment.
  • 13. ο‚— The object of a TextField class is a text component that allows the editing of a single line text. It inherits TextComponent class. ο‚— Syntax: public class TextField extends TextComponent ο‚— Constructor: ο‚— TextField():Constructs a new text field. ο‚— TextField(int columns): Constructs a new empty text field with the specified number of columns. ο‚— TextField(String text): Constructs a new text field initialized with the specified text. ο‚— TextField(String text, int columns): Constructs a new text field initialized with the specified text to be displayed, and wide enough to hold the specified number of columns. ο‚— Method : ο‚— void addActionListener(ActionListener l): Adds the specified action listener to receive action events from this text field. ο‚— int getColumns(): Gets the number of columns in this text field. ο‚— void setColumns(int columns): Sets the number of columns in this text field. ο‚— void setText(String t): Sets the text that is presented by this text component to be the specified text.
  • 14. import java.awt.*; import java.awt.event.*; public class ButtonExample { ButtonExample(){ Frame f=new Frame("Button Example"); Label l1; l1=new Label("First Label."); l1.setBounds(30,100, 100,30); final TextField tf=new TextField(); tf.setBounds(100,100, 100,20); Button b=new Button("Click Here"); b.setBounds(70,150,60,30); b.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ tf.setText("Welcome to Java."); } }); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); f.add(b); f.add(tf); f.add(l1); f.setSize(400,400); f.setLayout(null); f.setVisible(true); }
  • 15. ο‚— The TextArea control in AWT provide us multiline editor area. When the text in the text area become larger than the viewable area the scroll bar is automatically appears which help us to scroll the text up & down and right & left. ο‚— Constructor: ο‚— TextArea(): Constructs a new text area with the empty string as text. ο‚— TextArea(int rows, int columns): Constructs a new text area with the specified number of rows and columns and the empty string as text. ο‚— TextArea(String text): Constructs a new text area with the specified text. ο‚— TextArea(String text, int rows, int columns): Constructs a new text area with the specified text, and with the specified number of rows and columns. ο‚— TextArea(String text, int rows, int columns, int scrollbars) ο‚— Constructs a new text area with the specified text, and with the rows, columns, and scroll bar visibility as specified. ο‚— static int SCROLLBARS_BOTH -- Create and display both vertical and horizontal scrollbars. ο‚— static int SCROLLBARS_HORIZONTAL_ONLY -- Create and display horizontal scrollbar only. ο‚— static int SCROLLBARS_NONE -- Do not create or display any scrollbars for the text area. ο‚— static int SCROLLBARS_VERTICAL_ONLY -- Create and display vertical scrollbar only.
  • 16. Method ο‚— void append(String str): Appends the given text to the text area's current text. ο‚— int getColumns(): Returns the number of columns in this text area. ο‚— void insert(String str, int pos): Inserts the specified text at the specified position in this text area. ο‚— void replaceRange(String str, int start, int end):Replaces text between the indicated start and end positions with the specified replacement text. ο‚— void setColumns(int columns): Sets the number of columns for this text area. ο‚— void setRows(int rows): Sets the number of rows for this text area. ο‚— int getRows(): Returns the number of rows in the text area.
  • 17. import java.awt.*; public class TextAreaExample { TextAreaExample(){ Frame f= new Frame(); TextArea area=new TextArea("Welcome to KJC"); area.setBounds(10,30, 300,300); f.add(area); f.setSize(400,400); f.setLayout(null); f.setVisible(true); area.insert(β€œIII B.Sc Java”,150,150); } public static void main(String args[]) { new TextAreaExample(); } }
  • 18. ο‚— Checkbox control is used to turn an option on(true) or off(false). There is label for each checkbox representing what the checkbox does.The state of a checkbox can be changed by clicking on it. ο‚— Class constructors: ο‚— Checkbox(): Creates a check box with an empty string for its label. ο‚— Checkbox(String label): Creates a check box with the specified label. ο‚— Checkbox(String label, boolean state):Creates a check box with the specified label and sets the specified state. ο‚— Checkbox(String label, boolean state, CheckboxGroup group): Constructs a Checkbox with the specified label, set to the specified state, and in the specified check box group. ο‚— Checkbox(String label, CheckboxGroup group, boolean state): Creates a check box with the specified label, in the specified check box group, and set to the specified state.
  • 19. ο‚— Class methods: ο‚— void addItemListener(ItemListener l): Adds the specified item listener to receive item events from this check box. ο‚— String getLabel(): Gets the label of this check box. ο‚— boolean getState():Determines whether this check box is in the on or off state. ο‚— void setState(boolean state); Sets the state of this check box to the specified state.
  • 20. import java.awt.*; public class CheckboxExample { CheckboxExample(){ Frame f= new Frame("Checkbox Example"); Checkbox checkbox1 = new Checkbox("C++"); checkbox1.setBounds(100,100, 50,50); Checkbox checkbox2 = new Checkbox("Java", true); checkbox2.setBounds(100,150, 50,50); f.add(checkbox1); f.add(checkbox2); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } public static void main(String args[]) { new CheckboxExample(); } }
  • 21. ο‚— The CheckboxGroup class is used to group the set of checkbox. ο‚— Constructor: ο‚— CheckboxGroup(): Creates a new instance of CheckboxGroup. ο‚— Methods: ο‚— Checkbox getSelectedCheckbox(): Gets the current choice from this check box group. ο‚— void setSelectedCheckbox(Checkbox box): Sets the currently selected check box in this group to be the specified check box.
  • 22. ο‚— Choice control is used to show pop up menu of choices. Selected choice is shown on the top of the menu. ο‚— Constructor: ο‚— Choice(): Creates a new choice menu. ο‚— Methods: ο‚— void add(String item):Adds an item to this Choice menu. ο‚— void addItemListener(ItemListener l):Adds the specified item listener to receive item events from this Choice menu. ο‚— void insert(String item, int index):Inserts the item into this choice at the specified position. ο‚— void remove(int position):Removes an item from the choice menu at the specified position. ο‚— void remove(String item):Removes the first occurrence of item from the Choice menu.
  • 23. ο‚— The List represents a list of text items. The list can be configured that user can choose either one item or multiple items. ο‚— Constructors: ο‚— List(): Creates a new scrolling list. ο‚— List(int rows):Creates a new scrolling list initialized with the specified number of visible lines. ο‚— List(int rows, boolean multipleMode):Creates a new scrolling list initialized to display the specified number of rows. ο‚— Methods: ο‚— void add(String item):Adds the specified item to the end of scrolling list. ο‚— void add(String item, int index):Adds the specified item to the the scrolling list at the position indicated by the index. ο‚— void addItemListener(ItemListener l):Adds the specified item listener to receive item events from this list. ο‚— String getItem(int index):Gets the item associated with the specified index. ο‚— int getItemCount():Gets the number of items in the list.
  • 24. public class ListExample { ListExample(){ Frame f= new Frame(); List l1=new List(5); l1.setBounds(100,100, 75,75); l1.add("Item 1"); l1.add("Item 2"); l1.add("Item 3"); l1.add("Item 4"); l1.add("Item 5"); f.add(l1); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } public static void main(String args[]) { new ListExample(); } }
  • 25. ο‚— The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a GUI component allows us to see invisible number of rows and columns.Constructor: ο‚— Scrollbar(): Constructs a new vertical scroll bar. ο‚— Scrollbar(int orientation): Constructs a new scroll bar with the specified orientation. ο‚— Scrollbar(int orientation, int value, int visible, int minimum, int maximum):Constructs a new scroll bar with the specified orientation, initial value, visible amount, and minimum and maximum values. ο‚— static int HORIZONTAL --A constant that indicates a horizontal scroll bar. ο‚— static int VERTICAL --A constant that indicates a vertical scroll bar.
  • 26. ο‚— void addAdjustmentListener(AdjustmentListener l) Adds the specified adjustment listener to receive instances of AdjustmentEvent from this scroll bar. ο‚— int getMaximum():Gets the maximum value of this scroll bar. ο‚— int getMinimum():Gets the minimum value of this scroll bar. ο‚— int getOrientation():Returns the orientation of this scroll bar. ο‚— int getValue():Gets the current value of this scroll bar. ο‚— void setMaximum(int newMaximum):Sets the maximum value of this scroll bar. ο‚— void setMinimum(int newMinimum):Sets the minimum value of this scroll bar. ο‚— void setOrientation(int orientation): Sets the orientation for this scroll bar.
  • 27. Layout Manager ο‚— Layout is the arrangement of components within the container. i.e>placing the components at a particular position within the container. ο‚— The task of layouting the controls is done automatically by the Layout Manager. ο‚— If we do not use layout manager then also the components are positioned by the default layout manager. ο‚— The layout managers adapt to the dimensions of appletviewer or the application window. ο‚— The layout manager is associated with every Container object.
  • 28. ο‚— The class BorderLayout arranges the components to fit in the five regions: east, west, north, south and center. ο‚— Each region can contain only one component and each component in each region is identified by the corresponding constant NORTH, SOUTH, EAST, WEST, and CENTER ο‚— Constructor: ο‚— BorderLayout():Constructs a new border layout with no gaps between components. ο‚— BorderLayout(int hgap, int vgap): Constructs a border layout with the specified gaps between components. ο‚— static String CENTER -- The center layout constraint (middle of container). ο‚— static String EAST -- The east layout constraint (right side of container). ο‚— static String NORTH -- The north layout constraint (top of container). ο‚— static String SOUTH -- The south layout constraint (bottom of container). ο‚— static String WEST -- The west layout constraint (left side of container).
  • 29. ο‚— void addLayoutComponent(String name, Component comp): If the layout manager uses a per- component string, adds the component comp to the layout, associating it with the string specified by name. ο‚— int getHgap(): Returns the horizontal gap between components. ο‚— int getVgap():Returns the vertical gap between components. ο‚— void setHgap(int hgap):Sets the horizontal gap between components. ο‚— void setVgap(int vgap): Sets the vertical gap between components.
  • 30. import java.awt.*; public class Border { Frame f; Border(){ f=new Frame(); Button b1=new Button("NORTH");; Button b2=new Button("SOUTH");; Button b3=new Button("EAST");; Button b4=new Button("WEST");; Button b5=new Button("CENTER");; f.add(b1,BorderLayout.NORTH); f.add(b2,BorderLayout.SOUTH); f.add(b3,BorderLayout.EAST); f.add(b4,BorderLayout.WEST); f.add(b5,BorderLayout.CENTER); f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new Border(); } }
  • 31. ο‚— The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle. ο‚— Constructors: ο‚— GridLayout(): creates a grid layout with one column per component in a row. ο‚— GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps between the components. ο‚— GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and columns alongwith given horizontal and vertical gaps.
  • 32. import java.awt.*; import javax.swing.*; public class GridLayoutEx{ Frame f; GridLayoutEx(){ f=new JFrame(); Button b1=new Button("1"); Button b2=new Button("2"); Button b3=new Button("3"); Button b4=new Button("4"); Button b5=new Button("5"); Button b6=new Button("6"); Button b7=new Button("7"); Button b8=new Button("8"); Button b9=new Button("9"); f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5); f.add(b6);f.add(b7);f.add(b8);f.add(b9); f.setLayout(new GridLayout(3,3)); //setting grid layout of 3 rows and 3 columns f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new GridLayoutEx(); } }
  • 33. ο‚— The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout of applet or panel. Fields of FlowLayout class ο‚— public static final int LEFT ο‚— public static final int RIGHT ο‚— public static final int CENTER ο‚— public static final int LEADING ο‚— public static final int TRAILING ο‚— Constructors of FlowLayout class: ο‚— FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap. ο‚— FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and vertical gap. ο‚— FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given horizontal and
  • 34. import java.awt.*; public class FlowLayoutEx{ Frame f; FlowLayoutEx(){ f=new Frame(); Button b1=new Button("1"); Button b2=new Button("2"); Button b3=new Button("3"); Button b4=new Button("4"); Button b5=new Button("5"); f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5); f.setLayout(new FlowLayout(FlowLayout.RIGHT)); //setting flow layout of right alignment f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new FlowLayoutEx(); } }
  • 35. ο‚— The CardLayout class manages the components in such a manner that only one component is visible at a time. It treats each component as a card that is why it is known as CardLayout. ο‚— Constructors of CardLayout class ο‚— CardLayout(): creates a card layout with zero horizontal and vertical gap. ο‚— CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap. ο‚— methods of CardLayout class ο‚— public void next(Container parent): is used to flip to the next card of the given container. ο‚— public void previous(Container parent): is used to flip to the previous card of the given container. ο‚— public void first(Container parent): is used to flip to the first card of the given container. ο‚— public void last(Container parent): is used to flip to the last card of the given container. ο‚— public void show(Container parent, String name): is used to flip to the specified card with the given name.
  • 36. import java.awt.*; import java.awt.event.*; Import java.swing.*; public class CardLayoutExample extends Jrame implements ActionListener{ CardLayout card; Button b1,b2,b3; Container c; CardLayoutExample(){ c=getContentPane(); card=new CardLayout(40,30); //create CardLayout object with 40 hor space and 30 ver space c.setLayout(card); b1=new Button("Apple"); b2=new Button("Boy"); b3=new Button("Cat"); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); c.add("a",b1);c.add("b",b2);c.add("c",b3); } public void actionPerformed(ActionEvent e) { card.next(c); } public static void main(String[] args) { CardLayoutExample cl=new CardLayoutExample(); cl.setSize(400,400); cl.setVisible(true); cl.setDefaultCloseOperation(EXIT_ON_CLOSE); } }
  • 37. ο‚— The Java GridBagLayout class is used to align components vertically, horizontally or along their baseline. ο‚— The components may not be of same size. Each GridBagLayout object maintains a dynamic, rectangular grid of cells. ο‚— The GridBagLayout manages each component's minimum and preferred sizes in order to determine component's size. ο‚— Constructor: ο‚— GridBagLayout(): Creates a grid bag layout manager. ο‚— Method : ο‚— void addLayoutComponent(Component comp, Object constraints):Adds the specified component to the layout, using the specified constraints object. ο‚— void addLayoutComponent(String name, Component comp): Adds the specified component with the specified name to the layout. ο‚— void removeLayoutComponent(Component comp):Removes the specified component from this layout.
  • 38. Menu Bars and Menus ο‚— The object of MenuItem class adds a simple labeled menu item on menu. The items used in a menu must belong to the MenuItem or any of its subclass. ο‚— Constructor : ο‚— MenuBar(): Creates a new menu bar. ο‚— Method : ο‚— Menu add(Menu m):Adds the specified menu to the menu bar. ο‚— Menu getHelpMenu():Gets the help menu on the menu b ο‚— Menu getMenu(int i):Gets the specified menu. ο‚— int getMenuCount(): Gets the number of menus on the menu bar.
  • 39. import java.awt.*; class MenuExample { MenuExample(){ Frame f= new Frame("Menu and MenuItem Example"); MenuBar mb=new MenuBar(); Menu menu=new Menu("Menu"); Menu submenu=new Menu("Sub Menu"); MenuItem i1=new MenuItem("Item 1"); MenuItem i2=new MenuItem("Item 2"); MenuItem i3=new MenuItem("Item 3"); MenuItem i4=new MenuItem("Item 4"); menu.add(i1); menu.add(i2); submenu.add(i3); submenu.add(i4); menu.add(submenu); mb.add(menu); f.setMenuBar(mb); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } public static void main(String args[]) { new MenuExample(); } }
  • 40. ο‚— The Dialog control represents a top level window with a border and a title used to take some form of input from the user. It inherits the Window class. ο‚— Modal dialog or modeless ο‚— Unlike Frame, it doesn't have maximize and minimize buttons. ο‚— Dialog(Dialog owner): Constructs an initially invisible, modeless Dialog with the specified owner Dialog and an empty title. ο‚— Dialog(Dialog owner, String title):Constructs an initially invisible, modeless Dialog with the specified owner Dialog and title. ο‚— Dialog(Frame owner):Constructs an initially invisible, modeless Dialog with the specified owner Frame and an empty title. ο‚— Dialog(Frame owner, boolean modal):Constructs an initially invisible Dialog with the specified owner Frame and modality and an empty title. ο‚— Dialog(Frame owner, String title):Constructs an initially invisible, modeless Dialog with the specified owner Frame and title.
  • 41. import java.awt.*; import java.awt.event.*; public class DialogExample { private static Dialog d; DialogExample() { Frame f= new Frame(); d = new Dialog(f , "Dialog Example", true); d.setLayout( new FlowLayout() ); Button b = new Button ("OK"); b.addActionListener ( new ActionListener() { public void actionPerformed( ActionEvent e ) { DialogExample.d.setVisible(false); } }); d.add( new Label ("Click button to continue.")); d.add(b); d.setSize(300,300); d.setVisible(true); } public static void main(String args[]) { new DialogExample(); } }
  • 42. ο‚— FileDialog control represents a dialog window from which the user can select a file. ο‚— static int LOAD -- This constant value indicates that the purpose of the file dialog window is to locate a file from which to read. ο‚— static int SAVE -- This constant value indicates that the purpose of the file dialog window is to locate a file to which to write. ο‚— Constructor: ο‚— FileDialog(Dialog parent): Creates a file dialog for loading a file. ο‚— FileDialog(Dialog parent, String title):Creates a file dialog window with the specified title for loading a file. ο‚— FileDialog(Dialog parent, String title, int mode): Creates a file dialog window with the specified title for loading or saving a file. ο‚— FileDialog(Frame parent): Creates a file dialog for loading a file. ο‚— FileDialog(Frame parent, String title): Creates a file dialog window with the specified title for loading a file. ο‚— FileDialog(Frame parent, String title, int mode): Creates a file dialog window with the specified title for loading or saving a file.
  • 43. ο‚— Method ο‚— String getDirectory(): Gets the directory of this file dialog. ο‚— String getFile(): Gets the selected file of this file dialog. ο‚— int getMode(): Indicates whether this file dialog box is for loading from a file or for saving to a file. ο‚— void setMode(int mode): Sets the mode of the file dialog.
  • 44. import java.awt.*; import java.awt.event.*; public class FileControlDemo { Frame f= new Frame("Java AWT Examples"); Label l1=new Label(),l2=new Label(); Panel controlPanel=new Panel(); public FileControlDemo(){ prepareGUI(); } public static void main(String[] args){ FileControlDemo awtControlDemo = new FileControlDemo(); awtControlDemo.showFileDialogDemo(); } private void prepareGUI(){ f f.setSize(400,400); f.setLayout(new GridLayout(3, 1)); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); l1.setAlignment(Label.CENTER); l2.setAlignment(Label.CENTER); l2.setSize(350,100); controlPanel.setLayout(new FlowLayout()); f.add(l1); f.add(controlPanel); f.add(l2); f.setVisible(true); } private void showFileDialogDemo(){ l1.setText("Control in action: FileDialog"); final FileDialog fileDialog = new FileDialog(f,"Select file"); Button showFileDialogButton = new Button("Open File"); showFileDialogButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fileDialog.setVisible(true); l2.setText("File Selected :" + fileDialog.getDirectory() + fileDialog.getFile()); } }); controlPanel.add(showFileDialogButton); f.setVisible(true); } }
  • 45. Adapter Class ο‚— Adapter classes provide an implementation of listener interfaces. When you inherit the adapter class implementation for all methods is not mandatory ο‚— java.awt.event Adapter Class Listener Interface WindowAdapter WindowListener KeyAdapter KeyListener MouseAdapter MouseListener MouseMotionAdapter MouseMotionListener FocusAdapter FocusListener ComponentAdapter ComponentListener ContainerAdapter ContainerListener
  • 46. Mouse Adapter import java.awt.*; import java.awt.event.*; public class MouseAdapterExample extends MouseAdapter{ Frame f; MouseAdapterExample(){ f=new Frame("Mouse Adapter"); f.addMouseListener(this); f.setSize(300,300); f.setLayout(null); f.setVisible(true); } public void mouseClicked(MouseEvent e) { Graphics g=f.getGraphics(); g.setColor(Color.BLUE); g.fillOval(e.getX(),e.getY(),30,30); } public static void main(String[] args) { new MouseAdapterExample(); } }
  • 47. MouseMotionAdapter import java.awt.*; import java.awt.event.*; public class MouseMotionAdapterExample extends MouseMotionAdapter{ Frame f; MouseMotionAdapterExample(){ f=new Frame("Mouse Motion Adapter"); f.addMouseMotionListener(this); f.setSize(300,300); f.setLayout(null); f.setVisible(true); } public void mouseDragged(MouseEvent e) { Graphics g=f.getGraphics(); g.setColor(Color.ORANGE); g.fillOval(e.getX(),e.getY(),20,20); } public static void main(String[] args) { new MouseMotionAdapterExample(); } }
  • 48. KeyAdapter import java.awt.*; import java.awt.event.*; public class KeyAdapterExample extends KeyAdapter{ Label l; TextArea area; Frame f; KeyAdapterExample(){ f=new Frame("Key Adapter"); l=new Label(); l.setBounds(20,50,200,20); area=new TextArea(); area.setBounds(20,80,300, 300); area.addKeyListener(this); f.add(l);f.add(area); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } public void keyReleased(KeyEvent e) { String text=area.getText(); String words[]=text.split("s"); l.setText("Words: "+words.length+" Characters:"+text.length()); } public static void main(String[] args) { new KeyAdapterExample(); }