UNIT 1 AWT

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

Unit 1: Abstract Windowing Toolkit DKTEYCP ICH

1) Component , Container, Window , frame, panel,

1.1 Component:
java.lang.Object
java.awt.Component
A component is an object having a graphical representation that can be displayed on the screen and that can
interact with the user. Examples of components are the buttons, checkboxes, and scrollbars of a typical
graphical user interface.
The Component class is the abstract superclass of the nonmenu-related Abstract Window Toolkit components.
Class Component can also be extended directly to create a lightweight component. A lightweight component is
a component that is not associated with a native window. On the contrary, a heavyweight component is
associated with a native window. The isLightweight() method may be used to distinguish between the two kinds
of the components.
1.2 Container

java.lang.Object
java.awt.Component
java.awt.Container
generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT
components.
Components added to a container are tracked in a list. The order of the list will define the components' front-to-
back stacking order within the container. If no index is specified when adding a component to a container, it
will be added to the end of the list (and hence to the bottom of the stacking order).

1.3 Window
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
A Window object is a top-level window with no borders and no menubar. The default layout for a window
is BorderLayout.

A window must have either a frame, dialog, or another window defined as its owner when it's constructed.

1.4 Panel
java.lang.Object
Prof. A S Salavi (Kumbhar) Page 1 of 28
Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
java.awt.Component
java.awt.Container
java.awt.Panel
Panel is the simplest container class. A panel provides space in which an application can attach any other
component, including other panels.

The default layout manager for a panel is the FlowLayout layout manager.

2) Creating Window Program & Applet


1.1 Applet

Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs
inside the browser and works at client side.

Advantage of Applet

There are many advantages of applet. They are as follows:

o It works at client side so less response time.


o Secured
o It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.

Drawback of Applet

o Plugin is required at client browser to execute applet.

Hierarchy of Applet

Lifecycle of Java Applet

1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
Prof. A S Salavi (Kumbhar) Page 2 of 28
Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
4. Applet is stopped.
5. Applet is destroyed.

Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle methods
for an applet.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start the
Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class

The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be
used for drawing oval, rectangle, arc etc.

Who is responsible to manage the life cycle of an applet?

Java Plug-in software.

Prof. A S Salavi (Kumbhar) Page 3 of 28


Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
How to run an Applet?

There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile it. After that create an html file and place the
applet code in html file. Now click the html file.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome",150,150);
}

myapplet.html

<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>

Simple example of Applet by appletviewer tool:

To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and compile it.
After that run it by: appletviewer First.java. Now Html file is not required but it is for testing purpose only.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome to applet",150,150);
}

}
/*

Prof. A S Salavi (Kumbhar) Page 4 of 28


Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
<applet code="First.class" width="300" height="300">
</applet>
*/

To execute the applet by appletviewer tool, write in command prompt:

c:\>javac First.java
c:\>appletviewer First.java

1.2 Frame
Frame: A frame has title, border and menu bars. It can contain several components like buttons, text
fields, scrollbars etc. This is most widely used container while developing an application in AWT.

import java.awt.*;
/* We have extended the Frame class here,
* thus our class "SimpleExample" would behave
* like a Frame
*/
public class SimpleExample extends Frame{
SimpleExample(){
Button b=new Button("Button!!");

// setting button position on screen


b.setBounds(50,50,50,50);

//adding button into frame


add(b);

//Setting Frame width and height


setSize(500,300);

//Setting the title of Frame


setTitle("This is my First AWT example");

//Setting the layout for the Frame


setLayout(new FlowLayout());

/* By default frame is not visible so


* we are setting the visibility to true
* to make it visible.
*/
setVisible(true);
}
public static void main(String args[]){
// Creating the instance of Frame
SimpleExample fr=new SimpleExample();
}
}

Prof. A S Salavi (Kumbhar) Page 5 of 28


Unit 1: Abstract Windowing Toolkit DKTEYCP ICH

3) AWT Controls

Sr. No. Control & Description

1 Label
A Label object is a component for placing text in a container.

2 Button
This class creates a labeled button.

3 Check Box
A check box is a graphical component that can be in either an on (true) or off (false)
state.

4 Check Box Group


The CheckboxGroup class is used to group the set of checkbox.

5 List
The List component presents the user with a scrolling list of text items.

6 Text Field
A TextField object is a text component that allows for the editing of a single line of text.

7 Text Area
A TextArea object is a text component that allows for the editing of a multiple lines of
text.

8 Choice

Prof. A S Salavi (Kumbhar) Page 6 of 28


Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
A Choice control is used to show pop up menu of choices. Selected choice is shown on
the top of the menu.

9 Canvas
A Canvas control represents a rectangular area where application can draw something or
can receive inputs created by user.

10 Image
An Image control is superclass for all image classes representing graphical images.

11 Scroll Bar
A Scrollbar control represents a scroll bar component in order to enable user to select
from range of values.

12 Dialog
A Dialog control represents a top-level window with a title and a border used to take
some form of input from the user.

13 File Dialog
A FileDialog control represents a dialog window from which the user can select a file.

1. Labels : This is the simplest component of Java Abstract Window Toolkit. This component is generally
used to show the text or string in your application and label never perform any type of action. Syntax for
defining the label only and with justification :

Label label_name = new Label ("This is the label text.");


Above code simply represents the text for the label.
Label label_name = new Label ("This is the label text.", Label.CENTER);
Justification of label can be left, right or centered. Above declaration used the center justification of the
label using the Label.CENTER.

2. Buttons : This is the component of Java Abstract Window Toolkit and is used to trigger actions and
other events required for your application. The syntax of defining the button is as follow s :

Button button_name = new Button ("This is the label of the button.");


You can change the Button's label or get the label's text by using
the Button.setLabel(String) and Button.getLabel() method. Buttons are added to the it's container using
the add (button_name) method.

3. Check Boxes : This component of Java AWT allows you to create check boxes in your applications.
The syntax of the definition of Checkbox is as follows :

CheckBox checkbox_name = new Checkbox ("Optional check box 1", false);

Prof. A S Salavi (Kumbhar) Page 7 of 28


Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
Above code constructs the unchecked Checkbox by passing the boolean valued argument false with the
Checkbox label through the Checkbox() constructor. Defined Checkbox is added to it's container
using add (checkbox_name) method. You can change and get the checkbox's label using the setLabel
(String) and getLabel() method. You can also set and get the state of the checkbox using
the setState(boolean) and getState() method provided by the Checkbox class.

4. Radio Button : This is the special case of the Checkbox component of Java AWT package. This is used
as a group of checkboxes which group name is same. Only one Checkbox from a Checkbox Group can
be selected at a time. Syntax for creating radio buttons is as follows :

CheckboxGroup chkgp = new CheckboxGroup();


add (new Checkbox ("One", chkgp, false);
add (new Checkbox ("Two", chkgp, false);
add (new Checkbox ("Three",chkgp, false);
In the above code we are making three check boxes with the label "One", "Two" and "Three". If you
mention more than one true valued for checkboxes then your program takes the last true and show the
last check box as checked.

5. Text Area: This is the text container component of Java AWT package. The Text Area contains plain
text. TextArea can be declared as follows:

TextArea txtArea_name = new TextArea();


You can make the Text Area editable or not using the setEditable (boolean) method. If you pass the
boolean valued argument falsethen the text area will be non-editable otherwise it will be editable. The
text area is by default in editable mode. Text are set in the text area using the setText(string) method of
the TextArea class.

6. Text Field: This is also the text container component of Java AWT package. This component contains
single line and limited text information. This is declared as follows :

TextField txtfield = new TextField(20);


You can fix the number of columns in the text field by specifying the number in the constructor. In the
above code we have fixed the number of columns to 20.

Example:

// The Component Applet that displays several components


4
Prof. A S Salavi (Kumbhar) Page 8 of 28
Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
5 import java.applet.Applet;
6 import java.awt.*;
7
8 public class ComponentApplet extends Applet
9{
10 public void init()
11 {
12 Button b = new Button("Test Button");
13 this.add(b);
14
15 Checkbox cb = new Checkbox("Test Checkbox");
16 this.add(cb);
17
18 CheckboxGroup cbg = new CheckboxGroup();
19 this.add(new Checkbox("CB Item 1", cbg, false));
20 this.add(new Checkbox("CB Item 2", cbg, false));
21 this.add(new Checkbox("CB Item 3", cbg, true));
22
23 Choice choice = new Choice();
24 choice.addItem("Choice Item 1");
25 choice.addItem("Choice Item 2");
26 choice.addItem("Choice Item 3");
27 this.add(choice);
28
29 Label l = new Label("Test Label");
30 this.add(l);
31
32 TextField t = new TextField("Test TextField",30);
33 this.add(t);
34 }
35 }

4) Use of Layout Manager

The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface
that is implemented by all the classes of layout managers. There are following classes that represents the layout
managers:

1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout

4.1 Java BorderLayout

The BorderLayout is used to arrange the components in five regions: north, south, east, west and center . Each
region (area) may contain one component only. It is the default layout of frame or window. The BorderLayout
provides five constants for each region:
Prof. A S Salavi (Kumbhar) Page 9 of 28
Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:

o BorderLayout(): creates a border layout but with no gaps between the components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps
between the components.

Example of BorderLayout class:

import java.awt.*;
import javax.swing.*;

public class Border


{
JFrame f;
Border()
{
f=new JFrame();

JButton b1=new JButton("NORTH");;


JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
Prof. A S Salavi (Kumbhar) Page 10 of 28
Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
JButton b4=new JButton("WEST");;
JButton b5=new JButton("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();
}
}

4.2 Java FlowLayout

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

1. public static final int LEFT


2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout class

1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical
gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal
and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the
given horizontal and vertical gap.

Example of FlowLayout class

Prof. A S Salavi (Kumbhar) Page 11 of 28


Unit 1: Abstract Windowing Toolkit DKTEYCP ICH

import java.awt.*;
import javax.swing.*;

public class MyFlowLayout


{
JFrame f;
MyFlowLayout()
{
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("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 MyFlowLayout();
}
}
Prof. A S Salavi (Kumbhar) Page 12 of 28
Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
4.3 Java GridLayout

The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each
rectangle.

Constructors of GridLayout class

1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps
between the components.
3. 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.

Example of GridLayout class

import java.awt.*;
import javax.swing.*;

public class MyGridLayout


{
JFrame f;
MyGridLayout()
{
f=new JFrame();

JButton b1=new JButton("1");


JButton b2=new JButton("2");

Prof. A S Salavi (Kumbhar) Page 13 of 28


Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("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 MyGridLayout();
}
}

4.4 Java CardLayout

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

1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.

Commonly used methods of CardLayout class

o public void next(Container parent): is used to flip to the next card of the given container.
o public void previous(Container parent): is used to flip to the previous card of the given container.
o public void first(Container parent): is used to flip to the first card of the given container.
o public void last(Container parent): is used to flip to the last card of the given container.
o public void show(Container parent, String name): is used to flip to the specified card with the given
name.

Prof. A S Salavi (Kumbhar) Page 14 of 28


Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
Example of CardLayout class

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class CardLayoutExample extends JFrame implements ActionListener


{
CardLayout card;
JButton 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 JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
Prof. A S Salavi (Kumbhar) Page 15 of 28
Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
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);
}
}

4.5 Java GridBagLayout

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. Each component occupies one or more cells known as its display area. Each component associates an
instance of GridBagConstraints. With the help of constraints object we arrange component's display area on the
grid. The GridBagLayout manages each component's minimum and preferred sizes in order to determine
component's size.

Fields

Modifier and Type Field Description

double[] columnWeight It is used to hold the overrides to the column weights.


s

int[] columnWidths It is used to hold the overrides to the column minimum


width.

Prof. A S Salavi (Kumbhar) Page 16 of 28


Unit 1: Abstract Windowing Toolkit DKTEYCP ICH

protected comptable It is used to maintains the association between a


Hashtable<Compone component and its gridbag constraints.
nt,GridBagConstrain
ts>

protected defaultConstra It is used to hold a gridbag constraints instance


GridBagConstraints ints containing the default values.

protected layoutInfo It is used to hold the layout information for the gridbag.
GridBagLayoutInfo

protected static int MAXGRIDSI No longer in use just for backward compatibility
ZE

protected static int MINSIZE It is smallest grid that can be laid out by the grid bag
layout.

protected static int PREFERRED It is preferred grid size that can be laid out by the grid
SIZE bag layout.

int[] rowHeights It is used to hold the overrides to the row minimum


heights.

double[] rowWeights It is used to hold the overrides to the row weights.

Useful Methods

Modifier and Type Method Description

void addLayoutComponent(Component It adds specified component to the


comp, Object constraints) layout, using the specified constraints
object.

void addLayoutComponent(String name, It has no effect, since this layout


Component comp) manager does not use a per-component

Prof. A S Salavi (Kumbhar) Page 17 of 28


Unit 1: Abstract Windowing Toolkit DKTEYCP ICH

string.

protected void adjustForGravity(GridBagConstraints It adjusts the x, y, width, and height


constraints, Rectangle r) fields to the correct values depending on
the constraint geometry and pads.

protected void AdjustForGravity(GridBagConstraints This method is for backwards


constraints, Rectangle r) compatibility only

protected void arrangeGrid(Container parent) Lays out the grid.

protected void ArrangeGrid(Container parent) This method is obsolete and supplied


for backwards compatibility

GridBagConstraints getConstraints(Component comp) It is for getting the constraints for the


specified component.

float getLayoutAlignmentX(Container It returns the alignment along the x axis.


parent)

float getLayoutAlignmentY(Container It returns the alignment along the y axis.


parent)

int[][] getLayoutDimensions() It determines column widths and row


heights for the layout grid.

protected getLayoutInfo(Container parent, int This method is obsolete and supplied


GridBagLayoutInfo sizeflag) for backwards compatibility.

protected GetLayoutInfo(Container parent, int This method is obsolete and supplied


GridBagLayoutInfo sizeflag) for backwards compatibility.

Point getLayoutOrigin() It determines the origin of the layout


area, in the graphics coordinate space of
the target container.

Prof. A S Salavi (Kumbhar) Page 18 of 28


Unit 1: Abstract Windowing Toolkit DKTEYCP ICH

double[][] getLayoutWeights() It determines the weights of the layout


grid's columns and rows.

protected Dimension getMinSize(Container parent, It figures out the minimum size of the
GridBagLayoutInfo info) master based on the information from
getLayoutInfo.

protected Dimension GetMinSize(Container parent, This method is obsolete and supplied


GridBagLayoutInfo info) for backwards compatibility only

Example

import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.*;
public class GridBagLayoutExample extends JFrame
{
public static void main(String[] args)
{
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample()
{
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
Prof. A S Salavi (Kumbhar) Page 19 of 28
Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

Output:

5) 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.

The object of Menu class is a pull down menu component which is displayed on the menu bar. It inherits the
MenuItem class.

Prof. A S Salavi (Kumbhar) Page 20 of 28


Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
AWT MenuItem class declaration
1. public class MenuItem extends MenuComponent implements Accessible

AWT Menu class declaration


1. public class Menu extends MenuItem implements MenuContainer, Accessible

Java AWT MenuItem and Menu Example


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");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
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();
}
}

Output:

Prof. A S Salavi (Kumbhar) Page 21 of 28


Unit 1: Abstract Windowing Toolkit DKTEYCP ICH

6) Dialog box
Java AWT Dialog

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.

Unlike Frame, it doesn't have maximize and minimize buttons.

Frame vs Dialog

Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons but Dialog doesn't
have.

AWT Dialog class declaration


1. public class Dialog extends Window

Java AWT Dialog Example


1. import java.awt.*;
2. import java.awt.event.*;
3. public class DialogExample {
4. private static Dialog d;
5. DialogExample() {
6. Frame f= new Frame();
7. d = new Dialog(f , "Dialog Example", true);
8. d.setLayout( new FlowLayout() );
9. Button b = new Button ("OK");
10. b.addActionListener ( new ActionListener()
11. {
12. public void actionPerformed( ActionEvent e )
13. {
Prof. A S Salavi (Kumbhar) Page 22 of 28
Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
14. DialogExample.d.setVisible(false);
15. }
16. });
17. d.add( new Label ("Click button to continue."));
18. d.add(b);
19. d.setSize(300,300);
20. d.setVisible(true);
21. }
22. public static void main(String args[])
23. {
24. new DialogExample();
25. }
26. }

Output:

7) File Dialog

FileDialog control represents a dialog window from which the user can select a file.

Class declaration
Following is the declaration for java.awt.FileDialog class

Class constructors
S.N. Constructor & Description

1 FileDialog(Dialog parent)

Creates a file dialog for loading a file.

2 FileDialog(Dialog parent, String title)

Prof. A S Salavi (Kumbhar) Page 23 of 28


Unit 1: Abstract Windowing Toolkit DKTEYCP ICH

Creates a file dialog window with the specified title for loading a file.

3 FileDialog(Dialog parent, String title, int mode)

Creates a file dialog window with the specified title for loading or saving a file.

4 FileDialog(Frame parent)

Creates a file dialog for loading a file.

5 FileDialog(Frame parent, String title)

Creates a file dialog window with the specified title for loading a file.

6 FileDialog(Frame parent, String title, int mode)

Creates a file dialog window with the specified title for loading or saving a file.

Class methods

S.N. Method & Description

1 void addNotify()

Creates the file dialog's peer.

2 String getDirectory()

Gets the directory of this file dialog.

3 String getFile()

Gets the selected file of this file dialog.

4 FilenameFilter getFilenameFilter()

Determines this file dialog's filename filter.

5 int getMode()

Indicates whether this file dialog box is for loading from a file or for saving to a
file.

Prof. A S Salavi (Kumbhar) Page 24 of 28


Unit 1: Abstract Windowing Toolkit DKTEYCP ICH

6 protected String paramString()

Returns a string representing the state of this FileDialog window.

7 void setDirectory(String dir)

Sets the directory of this file dialog window to be the specified directory.

8 void setFile(String file)

Sets the selected file for this file dialog window to be the specified file.

9 void setFilenameFilter(FilenameFilter filter)

Sets the filename filter for this file dialog window to the specified filter.

10 void setMode(int mode)

Sets the mode of the file dialog.

Methods inherited
This class inherits methods from the following classes:

 java.awt.Dialog

 java.awt.Window

 java.awt.Component

 java.lang.Object

FileDialog Example
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint
> gui >
AwtControlDemo.java

package com.tutorialspoint.gui;

import java.awt.*;

import java.awt.event.*;

public class AwtControlDemo {


Prof. A S Salavi (Kumbhar) Page 25 of 28
Unit 1: Abstract Windowing Toolkit DKTEYCP ICH

private Frame mainFrame;

private Label headerLabel;

private Label statusLabel;

private Panel controlPanel;

public AwtControlDemo(){

prepareGUI();

public static void main(String[] args){

AwtControlDemo awtControlDemo = new AwtControlDemo();

awtControlDemo.showFileDialogDemo();

private void prepareGUI(){

mainFrame = new Frame("Java AWT Examples");

mainFrame.setSize(400,400);

mainFrame.setLayout(new GridLayout(3, 1));

mainFrame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent){

System.exit(0);

});

headerLabel = new Label();

headerLabel.setAlignment(Label.CENTER);

statusLabel = new Label();

statusLabel.setAlignment(Label.CENTER);

Prof. A S Salavi (Kumbhar) Page 26 of 28


Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
statusLabel.setSize(350,100);

controlPanel = new Panel();

controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);

mainFrame.add(controlPanel);

mainFrame.add(statusLabel);

mainFrame.setVisible(true);

private void showFileDialogDemo(){

headerLabel.setText("Control in action: FileDialog");

final FileDialog fileDialog = new FileDialog(mainFrame,"Select file");

Button showFileDialogButton = new Button("Open File");

showFileDialogButton.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

fileDialog.setVisible(true);

statusLabel.setText("File Selected :"

+ fileDialog.getDirectory() + fileDialog.getFile());

});

controlPanel.add(showFileDialogButton);

mainFrame.setVisible(true);

Prof. A S Salavi (Kumbhar) Page 27 of 28


Unit 1: Abstract Windowing Toolkit DKTEYCP ICH
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Verify the following output

Prof. A S Salavi (Kumbhar) Page 28 of 28

You might also like