0% found this document useful (0 votes)
29 views

Advance Java Unit 1 Prof Akhil M Jaiswal

Introduction to Advance Java

Uploaded by

AKHIL JAISWAL
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Advance Java Unit 1 Prof Akhil M Jaiswal

Introduction to Advance Java

Uploaded by

AKHIL JAISWAL
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Prof. Akhil M.

Jaiswal

Advance Java
Introduction & Overview
Unit 1 Notes

Prof. Akhil M. Jaiswal


Ph.D. (Scholar), M.E. (CSE), B.E. (I.T.)
Amravati, Maharashtra, India.
9028637523

Objectives
• Develop Programs using GUI Framework
• Handle events of AWT and Swings Component
• Develop Programs to handle events in Java
Programming
• Develop Java Programs using Networking
Concept
• Develop programs using Database
• Develop programs using Servlets
Prof. Akhil M. Jaiswal

Abstract Window Toolkit


• AWT is a set of Application Program Interfaces (API)
used by Java programmers to create Graphical User
Interface ( GUI ) objects, such as buttons, textbox
scroll bars, labels and windows.
• AWT is windowing user-interface widget toolkit.
• The AWT contains Classes & Methods for creation of
window-based, Graphical User Interface.
• AWT contains Components & Container.
• AWT is quite large and sophisticated.
• AWT components are platform-dependent.
• AWT classes & methods are contained in the
java.awt package Prof. Akhil M. Jaiswal
Advance Java

AWT Example

Prof. Akhil M. Jaiswal

AWT Hierarchy

Prof. Akhil M. Jaiswal 9028637523


Advance Java

Component
• A component is the fundamental Graphical User
Interface object in Java that we see on the display in
a Java application is a Component.
• This includes things like buttons, checkboxes,
scrollbars, lists, menus, and text fields.
• A Component usually must be placed in a Container.
• It contains variables that represent the location,
shape, general appearance, and status of the object
as well as methods for basic painting and event
handling.
• Component is a base class from which all of Java’s
GUI components are derived.
Prof. Akhil M. Jaiswal

AWT Components

Radio Button

Scroll Bars
Choice
Prof. Akhil M. Jaiswal

Prof. Akhil M. Jaiswal 9028637523


Advance Java

Container
• The Container class is an extended type of
Component that maintains a list of child components
and helps to group them.
• 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 Container causes its children to be displayed and
arranges them on the screen according to a particular
layout.
• As Container is also a Component, it can be placed
alongside other Component objects in other
Containers in a hierarchical fashion.
Prof. Akhil M. Jaiswal

Container Example

Simple Window Using Frame contain Components

Prof. Akhil M. Jaiswal

Prof. Akhil M. Jaiswal 9028637523


Advance Java

Window
The Window class creates a top-level window. A
top-level window is not contained within any
other object; it sits directly on the desktop.
The window is the container that have no
borders and menu bars. You must use frame,
dialog or another window for creating a
window.

Prof. Akhil M. Jaiswal

Frame
The Frame is the top-level container that contain title
bar and can have menu bars & can have other
components like button, textfield etc.
Frame encapsulates what is commonly thought of as a
“window.” It is a subclass of Window and has a title
bar, menu bar, borders, and resizing corners.

Prof. Akhil M. Jaiswal

Prof. Akhil M. Jaiswal 9028637523


Advance Java

Panel
The Panel is the container that doesn't contain
title bar and menu bars. It can have other
components like button, textfield etc.
The Panel class is a concrete subclass of
Container & provides space in which any other
component can be placed, including other
panels.

Prof. Akhil M. Jaiswal

Dialog
• A Dialog is a top-level small window with a
title and a border that is typically used to take
some form of input from the user.
• The size of the dialog includes any area
designated for the border.
• Dialog extends Window class & Unlike Frame,
it doesn't have maximize and minimize
buttons.

Dialog Ex:
Prof. Akhil M. Jaiswal

Prof. Akhil M. Jaiswal


9028637523

Prof. Akhil M. Jaiswal 9028637523


Advance Java
Unit 1 - Lecture 3
Creating Windowed Programs & Applet
Prof. Akhil Jaiswal (9028637523)

Software Required:-
Notepad
Jdk 1.7 / 1.8 – www.oracle.com
Command prompt

Useful Methods of Component class


Includes in - import java.awt.*;
Method Description

public void add(Component c) inserts a component on this component.

setBounds(int xaxis, int yaxis, int width, int sets the position/bounds of the AWT components
height)

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, for Visibility set true

1. AWT Components:-
 AWT stands for Abstract Window Toolkit.
 It is a platform dependent (API) Application Programming Interface for creating Graphical
User Interface (GUI) for java programs.
 The AWT contains Classes & Methods for creation of window-based, Graphical User Interface.
 AWT contains Components & Container useful for GUI creation.
 AWT is quite large, heavy-weighted and sophisticated windowing user-interface widget toolkit
 AWT components are platform-dependent.
 AWT classes & methods are contained in the java.awt package

The AWT supports the following types of controls & are subclasses of Component :-
1. Labels
2. Push buttons
3. Check boxes
4. Choice lists
Prof. Akhil Jaiswal
5. Lists
6. Scroll bars
7. Text editing
Prof. Akhil Jaiswal
1. Labels
The easiest control to use is a label. A label is an object of type Label, and it contains a
string, which it displays. Labels are passive controls that do not support any interaction with
the user. Label defines the following constructors:

Label( ) //creates a blank label


Label(String str) // creates a label with value str
Label(String str, int how) // creates a label with value str and alignment= Label.LEFT/
Label.RIGHT, or Label.CENTER

// Program to Demonstrate Labels- labeldemo.java

import java.awt.*; // import awt package


import java.applet.*; // import applet package

/*
<applet code="LabelDemo" width=300 height=200>
</applet>
*/ //Applet code

public class LabelDemo extends Applet // Applet class extended


{
public void init()
{
Label one = new Label("One"); // label ‘one’ object created
Label two = new Label("Two"); // label ‘one’ object created
Label three = new Label("Three"); // label ‘one’ object created

add(one); //label one component added


add(two); //label two component added
add(three); //label three component added
}
}

Prof. Akhil Jaiswal


Buttons
Perhaps the most widely used control is the push button. A push button is a component that
contains a label and that generates an event when it is pressed. Push buttons are objects of
type Button. Button defines these two constructors:
Button( ) //creates empty button
Button(String str) //creates button with str as its label

Java AWT Example


To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)

1. AWT Example by Inheritance


Example of AWT where we are inheriting Frame class. Here, we are showing Button component on the Frame.

//Program to create a frame “My Frame” & add a Button “click here” into it.- FirstFrame2.java

import java.awt.*;
class FirstFrame2 extends Frame
{
Prof. Akhil Jaiswal
public static void main(String args[])
{
Frame f=new Frame("My Frame");

Button b=new Button("Test Button");


b.setBounds(30,100,80,30); // setting button position

f.add(b); //adding button into frame

f.setSize(300,300); //frame size 300 width and 300 height


f.setLayout(null); //no layout manager
f.setVisible(true); //now frame will be visible, by default not visible
}
}
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example that sets the
position of the awt button.

10
00

30
3
0 80

Prof. Akhil Jaiswal


Prof. Akhil Jaiswal

2. By creating the object of Frame class- FirstFrame.java


Lecture 4 Prof. Akhil Jaiswal
TextField
The TextField class implements a single-line text-entry area, usually called an edit control.
Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and
paste keys, and mouse selections.
TextField defines the following constructors:-
TextField( )
TextField(int numChars) // creates a text field that is numChars characters wide
TextField(String str)
TextField(String str, int numChars)

WAP to demonstrate following awt components: Label, TextField &Button

import java.awt.*;
class Form1 extends Frame // extends Frame Class
{
Form1( ) // constructor
{
Label l1=new Label("Enter UserName"); // Label l1 object created
l1.setBounds(40,45,100,30); //setting position &
add(l1);

TextField t1=new TextField();


t1.setBounds(180,45,70,30);
add(t1);

Label l2=new Label("Enter Password");


l2.setBounds(40,95,90,30);
add(l2);

TextField t2=new TextField();


t2.setBounds(180,95,70,30);
add(t2);

Button b1=new Button("Submit");


b1.setBounds(80,145,50,30);
add(b1);

Button b2=new Button("Cancel");


b2.setBounds(180,145,50,30);
add(b2);

setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[])
{ Form1 f1=new Form1(); } }

Prof. Akhil Jaiswal


Output:-

Prof. Akhil Jaiswal

Exercise:-
1) Write a Program to create 3 Labels displaying of your NAME, AGE, CITY.
2) WAP to 3 Text Field just one below other.
3) WAP to Create Two Buttons labelled “Positive”, “Negative”
4) WAP to Create Following form:-

Prof. Akhil Jaiswal


9028637523
Advance Java
Lecture 4
AWT Controls
Prof. Akhil M. Jaiswal
9028637523

Software Required:-
Notepad
Jdk 1.7 / 1.8 – www.oracle.com
Command prompt

Unit 1 Syllabus:-

Prof. Akhil M. Jaiswal

CONTENT
Checkbox
Group Checkbox
Scroll Bars
Text Area

Prof. Akhil M. Jaiswal 9028637523


Check Boxes
 A check box is a control that is used to turn an option on(true) or off(false)
 It consists of a small box ‘□’ that can either contain a check mark or not.
 Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".
 It can also be used for selection & deselecting an single or multiple options.
 There is a label associated with each check box that describes what option the box
represents.
 Check boxes can be used individually or as part of a group. Check boxes are objects of
the class Checkbox.

Ex:-
Checkbox supports these constructors:
Checkbox( ) //creates empty checkbox
Checkbox(String str) //creates checkbox with str as label
Checkbox(String str, boolean on) //creates checkbox with str as label and value as true/false

Java AWT Checkbox Example- CheckboxExample1.java

1. import java.awt.*;
2. public class CheckboxExample1
3. {
4. CheckboxExample1()
5. {
6. Frame f= new Frame("First Checkbox"); //create frame object with label
7. Checkbox checkbox1 = new Checkbox("Java",true); //create CB object with label
8. checkbox1.setBounds(100,100, 50,50); /
9. Checkbox checkbox2 = new Checkbox("Advance Java", true);
10. checkbox2.setBounds(100,150, 100,50);
11.
12. f.add(checkbox1); //add checkbox
13. f.add(checkbox2);
14.
15. f.setSize(400,400); //set frame size Prof. Akhil M. Jaiswal
16. f.setLayout(null); //set frame layout
17. f.setVisible(true); //set frame visbility
18. }
19. public static void main(String args[])
20. {
21. new CheckboxExample1();
22. } }

Prof. Akhil M. Jaiswal 9028637523


Checkbox Group
It is possible to create a set of mutually exclusive check boxes in which one and only one
check box in the group can be checked (on) at any one time and remaining checkbox are in
"off" state. These check boxes are often called radio buttons. ‘○’

 Constructors for creating Checkbox:


Checkbox(String str, boolean on, CheckboxGroup cbGroup) // checkbox group is created
Checkbox(String str, CheckboxGroup cbGroup, boolean on) // checkbox group is created

Java AWT CheckboxGroup Example- CheckboxGroupExample.java

1. import java.awt.*;
2. public class CheckboxGroupExample
3. {
4. CheckboxGroupExample()
5. {
6. Frame f= new Frame("CheckboxGroup Example");
7. CheckboxGroup cbg = new CheckboxGroup();
8. Checkbox checkBox1 = new Checkbox("Java", cbg, false);
9. checkBox1.setBounds(100,100, 50,50);
10. Checkbox checkBox2 = new Checkbox("Advance Java", cbg, true);
11. checkBox2.setBounds(100,150, 50,50);
12. f.add(checkBox1);
Prof. Akhil M. Jaiswal
13. f.add(checkBox2);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. public static void main(String args[])
19. {
20. new CheckboxGroupExample();
21. }
22. }

Prof. Akhil M. Jaiswal 9028637523


Scroll Bars
Scroll bars are used to select continuous values between a specified minimum and
maximum. Scroll bars may be oriented horizontally or vertically. A scroll bar is actually a
composite of several individual parts. Each end has an arrow that you can click to move the
current value of the scroll bar one unit in the direction of the arrow.
Scrollbar defines the following constructors:

Scrollbar( ) // creates a vertical scroll bar


Scrollbar(int style) // allow you to specify the orientation (vert, hori) of the scroll bar
Scrollbar(int style, int initialValue, int extent, int min, int max)

1. The first form creates a vertical scroll bar.


2. The second and third forms allow you to specify the orientation of the scroll bar. If style
is Scrollbar.VERTICAL, a vertical scroll bar is created. If style is
Scrollbar.HORIZONTAL, the scroll bar is horizontal.
3. In the third form of the constructor, Parameters are as follows:-
orientation - This parameter specifies the Scrollbar to be a horizontal or a vertical Scrollbar.
initialValue - This parameter specifies the starting position of the knob of Scrollbar on the
track of a Scrollbar.
extent - This parameter specified the width of the knob of Scrollbar.
min - This parameter specifies the minimum width of the track on which Scrollbar moves.
max - This parameter specifies the maximum width of the track.

1.Simple Java AWT Scrollbar Example – ScrollbarExample.java

1. import java.awt.*;
2. class ScrollbarExample
Prof. Akhil M. Jaiswal
3. {
4. ScrollbarExample(){
5. Frame f= new Frame("Scrollbar Example");
6. Scrollbar s=new Scrollbar(); //creates a vertical scroll bar
7. s.setBounds(100,100, 50,100);
8. f.add(s);
9. f.setSize(400,400);
10. f.setLayout(null);
11. f.setVisible(true);
12. }
13. public static void main(String args[])
14. { new ScrollbarExample();
15. } }

Prof. Akhil M. Jaiswal 9028637523


2. Vertical & Horizontal Scrollbar Example extending frame class
1. import java.awt.*;
2. class ScrollDemo extends Frame
3. {
4. ScrollDemo(){
5. setSize(300,300); // First set the frame size *
6. setVisible(true);
7. setLayout(null);
8. Scrollbar vertSB = new Scrollbar(Scrollbar.VERTICAL, 10, 100, 10, 1000);
9. Scrollbar horzSB = new Scrollbar(Scrollbar.HORIZONTAL,10, 100, 10, 1000);
10. vertSB.setBounds(50,50,20,100);
11. horzSB.setBounds(100,50,100,20);
12. add(vertSB);
13. add(horzSB);
Prof. Akhil M. Jaiswal
14. }
15. public static void main(String args[])
16. {
17. ScrollDemo s1=new ScrollDemo();
18. }
19. }
Output:-

Prof. Akhil M. Jaiswal 9028637523


TextArea
Sometimes a single line of text input is not enough for a given task. To handle this, AWT
includes a multiline text editor called TextArea. Where we can display multiline text and
also can edit it.
Following are the constructors for TextArea:

TextArea( )
TextArea(int numLines, int numChars)
TextArea(String str)
TextArea(String str, int numLines, int numChars)
TextArea(String str, int numLines, int numChars, int sBars)

Here,
numLines specifies the height, in lines, of the text area
numChars specifies its width, in characters.
Initial text can be specified by str.
In the fifth form, you can specify the scroll bars that you want the control to have. sBars
must be one of these values:

SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY

Program to Create simple TextArea- TextAreaExample.java


import java.awt.*;
public class TextAreaExample Prof. Akhil M. Jaiswal

{
TextAreaExample(){
Frame f= new Frame("TextAreaExample");
TextArea area=new TextArea("Java is Better than C++");
area.setBounds(10,30, 300,300);
f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{ new TextAreaExample();
} }
Prof. Akhil M. Jaiswal 9028637523
Exercise
1. Create 3 checkbox with Positive, Negative & Neutral label
2. Create a 3 checkbox group with Positive, Negative &
Neutral
3. Create 2 vertical & two horizontal scrollbars
4. Create a TextArea that contains details about your name,
age, city with both scroll bars.

Prof. Akhil M. Jaiswal


9028637523

Prof. Akhil M. Jaiswal 9028637523


Advance Java
Lecture 5 –Unit 1
1.4 – Use of Layout Managers
Prof. Akhil M. Jaiswal
Software Required:-
Notepad
Jdk 1.7 / 1.8 – www.oracle.com
Command prompt

Unit 1 Syllabus:-

CONTENT
1.4- Use of Layout managers
Layout Managers;-
FlowLayout
BorderLayout

What is a Layout in Java?


 Layout means the arrangement of components within the
container.
 In other way we can say that placing the components at a
particular position within the container.
 The task of lay-outing the controls is done automatically by
the Layout Manager & can be set using some methods.
Layout Managers
The layout manager automatically arranges your controls within a
window/Conatiner.
Each Container (frame, panel, dialogbox) object has a layout manager
associated with it.
A layout manager is an instance of any class that implements the
LayoutManager interface.
The layout manager is set by setLayout( ) method. If no call to
setLayout( ) is made, then the default layout manager is used.

Following is the list of commonly used controls while


designed GUI using AWT:-

1.
FlowLayout - The FlowLayout is the default layout. It layouts the
components in a directional flow.

2.
BorderLayout
The borderlayout arranges the components to fit in the five regions: east, west,
north, south and center.

3.
GridLayout
The GridLayout manages the components in form of a rectangular grid.

4.
CardLayout
The CardLayout object treats each component in the container as a card. Only
one card is visible at a time.

FlowLayout
Prof. Akhil M. Jaiswal 9028637523
 FlowLayout is the default layout manager.
 FlowLayout implements a simple layout style, which is similar to
how words flow in a text editor (Left to Right, Top to Bottom).
 The direction of the layout is governed by the container’s component
orientation property, which, by default, is left to right, top to bottom.
 Therefore, by default, components are laid out line-by-line beginning
at the upper-left corner.
 In all cases, when a line is filled, layout advances to the next line.

Here are the constructors for FlowLayout:

FlowLayout( ) // sets default flow of layout L-R, T-D


FlowLayout(int how)
FlowLayout(int how, int horz, int vert)

Valid values for how are as follows:

FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout.LEADING
FlowLayout.TRAILING

Example:- Program to Demonstrate FlowLayout( )- FlowDemo.java


Prof. Akhil M. Jaiswal 9028637523
import java.awt.*; //import awt package

class FlowDemo extends Frame


{
FlowDemo() {
setSize(300,300);
setLayout(new FlowLayout(FlowLayout.LEFT)); //set flow of layout
setVisible(true);
Checkbox java, python, st, ds; // 4 checkbox object
java= new Checkbox("Java", true); // Labelling & checked
python = new Checkbox("Python"); // Labelling
st = new Checkbox("Software Testing");
ds = new Checkbox("Data Structure");
add(java); // Labelling
add(python);
add(st);
add(ds);
}
public static void main(String args[])
{
FlowDemo f1=new FlowDemo(); // create object of class
}}

Prof. Akhil M. Jaiswal 9028637523


Output:-

Homework:-
Program to Demonstrate FlowLayout( ) by adding 10 food Items

Prof. Akhil M. Jaiswal 9028637523


BorderLayout
 The class BorderLayout arranges the components to fit in the five regions:
east, west, north, south and center.
 The BorderLayout class implements a common layout style for top-level
windows.
 It has four narrow, fixed-width components at the edges and one large area in
the center.

Here are the constructors defined by BorderLayout:


BorderLayout( )
BorderLayout(int horz, int vert)

Example:- Program to demonstrate BorderLayout() method.


Borderdemo.java

import java.awt.*;
class BorderDemo extends Frame
{
BorderDemo()
{
setSize(300,300);
setLayout(new BorderLayout()); //arranges components as per defined
setVisible(true);
add(new Button("TOP- North."),BorderLayout.NORTH); //create & add button
add(new Button("Footer Bottom- South"),BorderLayout.SOUTH);
add(new Button("Right- EAST "), BorderLayout.EAST);
add(new Button("Left- WEST "), BorderLayout.WEST);
add(new Button("Center"), BorderLayout.CENTER);
}
public static void main(String args[])
{
BorderDemo b1=new BorderDemo();
}
}

Prof. Akhil M. Jaiswal 9028637523


Output:-

Homework:-
Program to Demonstrate BorberLayout( ) by adding a button in top
Label in left, text field in center, checkbox in right, & Scroll bar in
at bottom

Prof. Akhil M. Jaiswal 9028637523


Advance Java
Lecture 6 –Unit 1
1.4 – Use of Layout Managers:
Grid Layout & Card Layout
Prof. Akhil M. Jaiswal
CONTENTS:
Grid Layout
Card Layout

1.4 Use of Layout managers:


Layout Managers
FlowLayout
BorderLayout
Grid Layout
Cardlayout
GridLayout
 GridLayout lays out components in a two-dimensional grid used to arrange the
components in rectangular grid.
 When we instantiate a GridLayout, we need define the number of rows and columns.
 The GridLayout container is divided into an equal-sized of rectangles, and one of the
components is placed in each rectangle.

The constructors supported by GridLayout are shown here:-


GridLayout( )
GridLayout(int numRows, int numColumns)
GridLayout(int numRows, int numColumns, int horz, int vert)
Example:-Program to demonstrate Gridlayout()- GridDemo.java
import java.awt.*;
class GridDemo extends Frame
{
GridDemo()
{
setSize(300,400);
setLayout(new GridLayout(3,3)); // sets a grid layout of 3 rows, 3 col
setVisible(true);

Button b1=new Button("ONE"); //button object created with label


Button b2=new Button("TWO");
Button b3=new Button("THREE");
Button b4=new Button("FOUR");
Button b5=new Button("FIVE");
Button b6=new Button("SIX");
Button b7=new Button("SEVEN");
Button b8=new Button("EIGHT");
Button b9=new Button("NINE");
add(b1); add(b2); add(b3); add(b4); add(b5); add(b6); add(b7); add(b8);
add(b9);
}
public static void main(String args[])
{ GridDemo g1=new GridDemo();
} }
Prof. Akhil M. Jaiswal 9028637523
Output:-

Example:-Program to demonstrate Gridlayout() by adding 9 labels in 9


places.

GridBagLayout

GridBagLayout, components are also arranged in rectangular grid but can have different
sizes and can occupy multiple rows or columns. A good way to do this is to use a grid bag
layout, which is specified by the GridBagLayout class. The components may not be of same
size. Each GridBagLayout object maintains a dynamic, rectangular grid of cells.The key to
the grid bag is that each component can be a different size, and each row in the grid can have
a different number of columns. This is why the layout is called a grid bag.

Prof. Akhil M. Jaiswal 9028637523


CardLayout- The CardLayout class is unique among the other layout
managers in that it stores several different layouts. Each layout can be
thought of as being on a separate index card in a deck that can be
shuffled so that any card is on top at a given time.
CardLayout provides these two constructors:
CardLayout( ) // creates a default card layout
CardLayout(int horz, int vert) // allows to specify hori, vert space

The first form creates a default card layout. The second form allows you
to specify the horizontal and vertical space left between components in
horz and vert, respectively.

Following methods are defined by CardLayout:


void first(Container deck)
void last(Container deck)
void next(Container deck)
void previous(Container deck)
void show(Container deck, String cardName)

//Program to Demonstrate Card Layout


import java.awt.*;
class CardDemo extends Frame
{
CardDemo()
{
setSize(300,400);
setLayout(new CardLayout(40,30));
setVisible(true);
Button b1=new Button("Apple");
Button b2=new Button("Mango");
Button b3=new Button("Orange");
add(b1); add(b2); add(b3);
}
public static void main(String args[])
{ CardDemo c1=new CardDemo();
} }

Example:-Program to demonstrate Cardlayout() for creating 5 different


card of different Subjects.
Prof. Akhil M. Jaiswal 9028637523
Advance Java
Lecture 7- Unit 1
Menus, MenuBars, Dialog Boxes, File Dialog
Prof. Akhil M. Jaiswal
9028637523
Menus and Menu Bars
Menu is a way to arrange buttons in a bar called as MenuBar. Traditional
dropdown menus are positioned across the top of a window in a Menu bar,
and display below the menu name. Popup menus appear when the user clicks,
eg with the right mouse button, on a component that can handle a popup
request. We can add one or more menuitems & submenu into the Popup menu.
MenuBar consist of various menu choices available to the end user.
Further each choice contains list of options which is called drop down menus.
This concept is implemented in the AWT by the following classes: MenuBar,
Menu, and MenuItem.
Ex:- Menu, MenuBar, MenuItem, SubMenu

Constructor:- Constructors to create Menus, Menubar, Menuitems, submenu.


MenuBar() // Creates a new menu bar.

Menu() //Constructs a new menu with an empty label.


Menu(String label) //Constructs a new menu with the specified label.

MenuItem() //Constructs a new MenuItem with an empty label


MenuItem(String label) //Constructs a new MenuItem with the specified label
MenuItem (String label, MenuShortcut s) //Create a menuitem with keyboard
shortcut.
Function:-
setMenubar(menubar_object_name) // set menubar of the object
Ex:- Write a Program to demonstrate menu & menubars- MenuDemo.java
import java.awt.*;
class MenuDemo1 extends Frame
{
MenuDemo1()
{
setSize(300,400);
setVisible(true);

MenuBar mb=new MenuBar(); //object created

Menu m1=new Menu("Departments"); //menu object created


Menu submenu=new Menu("Other"); //Sub-menu object created
MenuItem i1=new MenuItem("CSE"); //creates menuitem
MenuItem i2=new MenuItem("I.T");
MenuItem i3=new MenuItem("EXTC");
MenuItem i4=new MenuItem("MECH");
MenuItem i5=new MenuItem("Civil");
m1.add(i1);// add menuitems in menu m1
m1.add(i2);
m1.add(i3);

submenu.add(i4); // add menuitems in submenu


submenu.add(i5);
m1.add(submenu); //add submenu in menu
mb.add(m1); //add menu in menubar

setMenuBar(mb);// Sets menu in menubar


}
public static void main(String args[])
{
MenuDemo1 m=new MenuDemo1(); //constructor called
}
}
Output:-

WAP using AWT to create a menubar in a frame where menubar contains menu items
such as File,Edit,View and the sub menu under File menu should contain New and
Open
Dialog Boxes:-

 Dialog Box control represents a top-level window with a title and a border used to
take some form of input from the user.
 Dialog boxes don’t have menu bars, but in other respects, they function like frame
windows.
 Dialog boxes may be modal or modeless.
 When a modal dialog box is active, all input is directed to it until it is closed. This
means that you cannot access other parts of your program until you have closed the
dialog box.
 When a modeless dialog box is active, input focus can be directed to another window
in your program. Thus, other parts of your program remain active and accessible.
 Dialog boxes are of type Dialog. Two commonly used constructors are shown here:

Dialog(Frame parentWindow, boolean mode)


Dialog(Frame parentWindow, String title, boolean mode)

Here, parentWindow is the owner of the dialog box. If mode is true, the dialog box is modal.
Otherwise, it is modeless. The title of the dialog box can be passed in title. Generally, you
will subclass Dialog, adding the functionality required by your application.

Example:- Program to demonstrate Dialog – DialogExample.java

import java.awt.*;
public class DialogExample extends Frame
{
DialogExample()
{
Dialog d = new Dialog(this,"Dialog Example", true); //this refer to current Frame

Button b = new Button ("Click here");

d.add(b);
d.setSize(300,300);
d.setVisible(true);

}
public static void main(String args[])
{
new DialogExample();
}
}
Output:-

Exercise:- WAP to Create Dialog Box


FileDialog

Java provides a built-in dialog box that lets the user specify a file. To create a file dialog box,
instantiate an object of type FileDialog. This causes a file dialog box to be displayed.
Usually, this is the standard file dialog box provided by the operating system.

Here are three FileDialog constructors:

FileDialog(Frame parent)
FileDialog(Frame parent, String boxName)
FileDialog(Frame parent, String boxName, int how)

Here, parent is the owner of the dialog box. The boxName parameter specifies the name
displayed in the box’s title bar. If boxName is omitted, the title of the dialog box is empty. If
how is FileDialog.LOAD, then the box is selecting a file for reading. If how is
FileDialog.SAVE, the box is selecting a file for writing. If how is omitted, the box is
selecting a file for reading by default.

FileDialog provides methods that allow you to determine the name of the file and its path as
selected by the user.

Here are two examples:


String getDirectory( )
String getFile( )
These methods return the directory and the filename, respectively.
Example:- Profram to demonstrate FileDialog- FileDialogExample.java

import java.awt.*;

public class FileDialogExample extends Frame


{
FileDialogExample()
{
FileDialog f = new FileDialog(this,"Select file");

f.setDirectory("D:\\Games");// will set & select the File location to open

f.setVisible(true);

f.setSize(300,300);

}
public static void main(String args[])
{
new FileDialogExample();
}
}
Output:-
Practice Programs:- WAP using AWT to create:-

Prof. Akhil M. Jaiswal


9028637523

You might also like