Java Unit-Iv
Java Unit-Iv
Object oriented thinking and Java Basics- Need for oop paradigm, summary of oop concepts,
History of Java, Java buzzwords, data types, variables, scope and lifetime of variables, arrays,
operators, expressions, control statements, type conversion and casting, simple java program,
concepts of classes, objects, constructors, methods, access control, this keyword, garbage
collection, overloading methods and constructors, parameter passing, recursion, nested and inner
classes, exploring string class.
UNIT - II
Inheritance, Packages and Interfaces – Hierarchical abstractions, Base class object, subclass,
subtype, substitutability, forms of inheritance specialization, specification, construction,
extension, limitation, combination, benefits of inheritance, costs of inheritance. Member access
rules, super uses, using final with inheritance, polymorphism- method overriding, abstract
classes, the Object class. Defining, Creating and Accessing a Package, Understanding
CLASSPATH, importing packages, differences between classes and interfaces, defining an
interface, implementing interface, applying interfaces, variables in interface and extending
interfaces. Exploring java.io.
UNIT - III
Exception handling and Multithreading-- Concepts of exception handling, benefits of exception
handling, Termination or resumptive models, exception hierarchy, usage of try, catch, throw,
throws and finally, built in exceptions, creating own exception subclasses. Exploring java.util.
Differences between multithreading and multitasking, thread life cycle, creating threads, thread
priorities, synchronizing threads, inter thread communication, thread groups, daemon threads.
Enumerations, autoboxing, annotations, generics.
UNIT - IV
Event Handling: Events, Event sources, Event classes, Event Listeners, Delegation event model,
handling mouse and keyboard events, Adapter classes. The AWT class hierarchy, user interface
components- labels, button, canvas, scrollbars, text components, check box, checkbox groups,
choices, lists panels – scrollpane, dialogs, menubar, graphics, layout manager – layout manager
types – border, grid, flow, card and grid bag.
UNIT - V
Applets – Concepts of Applets, differences between applets and applications, life cycle of an
applet, types of applets, creating applets, passing parameters to applets. Swing – Introduction,
limitations of AWT, MVC architecture, components, containers, exploring swing- JApplet,
JFrame and JComponent, Icons and Labels, text fields, buttons – The JButton class, Check
boxes, Radio buttons, Combo boxes, Tabbed Panes, Scroll Panes, Trees, and Tables.
TEXT BOOKS:
1. Java the complete reference, 7th edition, Herbert schildt, TMH.
2. Understanding OOP with Java, updated edition, T. Budd, Pearson education.
REFERENCE BOOKS:
1. An Introduction to programming and OO design using Java, J.Nino and F.A. Hosch, John
wiley& sons.
2. An Introduction to OOP, third edition, T. Budd, Pearson education.
3. Introduction to Java programming, Y. Daniel Liang, Pearson education.
4. An introduction to Java programming and object-oriented application development, R.A.
Johnson- Thomson.
5. Core Java 2, Vol 1, Fundamentals, Cay.S. Horstmann and Gary Cornell, eighth Edition,
Pearson Education.
6. Core Java 2, Vol 2, Advanced Features, Cay.S. Horstmann and Gary Cornell, eighth Edition,
Pearson Education
7. Object Oriented Programming with Java, R.Buyya, S.T.Selvi, X.Chu, TMH.
8. Java and Object Orientation, an introduction, John Hunt, second edition, Springer.
9. Maurach’s Beginning Java2 JDK 5, SPD.
Output:
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Components
All the elements like the button, text fields, scroll bars, etc. are called components. In order to
place every component in a particular position on a screen, we need to add them to a container.
Container
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.
There are four types of containers in Java AWT:
● Window
● Panel
● Frame
● Dialog
Window: Window is a top-level container that represents a graphical window or dialog box. The
Window class extends the Container class, which means it can contain other components, such
as buttons, labels, and text fields.
Panel: Panel is a container class in Java. It is a lightweight container that can be used for
grouping other components together within a window or a frame.
Frame: The Frame is the container that contains the title bar and border and can have menu bars.
Dialog: A dialog box is a temporary window an application creates to retrieve user input.
Useful Methods of Component Class
Method Description
public void setLayout(LayoutManager m) Defines the layout manager for the component.
Following is the list of commonly used controls while designed GUI using AWT.
1. Label
2.Button
3.Check Box
A check box is a graphical component that can be in either an on (true) or off (false) state.
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
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
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.
Label
Label( )
String getText( )
• To set the alignment of the string within the label, call setAlignment( )
int getAlignment( )
Example:
import java.awt.*;
import java.awt.event.*;
Label label;
public LabelExample() {
setLayout(new FlowLayout());
// Creating a Label
add(label);
setSize(300, 200);
setVisible(true);
// Adding Window Listener to close the Frame
addWindowListener(new WindowAdapter() {
dispose();
new LabelExample();
}}
OUTPUT:
Button:
The most widely used control is Button. A button is a component that contains a label and that
generates an event when it is pressed.
Creating Button : Button b = new Button(String label);
Button Constructors:
1. Button() throws HeadlessException: It creates an empty button.
2. Button(String str) throws HeadlessException: It creates a button that contains str as a
label.
Button Methods :
1. void setLabel(String str): You can set its label by calling setLabel(). Here, str is the new
Label for the button.
2. String getLabel(): You can retrieve its label by calling getLabel() method.
Example to understand AWT Button Control in Java:
import java.awt.*;
import java.awt.event.*;
public class ButtonDemo extends Frame
{
Button b1, b2;
ButtonDemo ()
{
b1 = new Button ("OK");
b2 = new Button ("CANCEL");
this.setLayout (null);
b1.setBounds (100, 100, 80, 40);;
b2.setBounds (200, 100, 80, 40);
this.add (b1);
this.add (b2);
this.setVisible (true);
this.setSize (300, 300);
this.setTitle ("button");
this.addWindowListener (new WindowAdapter ()
{
public void windowClosing (WindowEvent we)
{
System.exit (0);
}
});
}
public static void main (String args[])
{
new ButtonDemo ();
}
}
OUTPUT:
Check Box
A checkbox may be a control that’s used to turn an option on or off. It consists of a little box
that will either contain a check or not. There’s a label related to each checkbox that describes
what option the box represents. You modify the state of a checkbox by clicking on.
Checkboxes are often used individually or as a part of a gaggle. Checkboxes are objects of
the Checkbox class.
Checkbox Constructor
3. Checkbox(String str, Boolean on) throws HeadlessException: It allows you to line the
initial state of the checkbox. If one is true, the checkbox is initially checked; otherwise,
it’s cleared.
4. Checkbox(String str, Boolean on, CheckboxGroupcbGroup) throws HeadlessException
or Checkbox(String str, CheckboxGroupcbGroup, Boolean on) throws
HeadlessException: It creates a checkbox whose label is specified by str and whose group
is specified by cbGroup. If this checkbox isn’t a part of a gaggle, then cbGroup must be
null. the worth of on determines the initial state of the checkbox.
Methods of Checkbox
2. void setState(boolean on): To line its state, call setState(). Here, if one is true, the box is
checked. If it’s false, the box is cleared.
3. String getLabel(): you’ll obtain the present label related to a checkbox by calling
getLabel().
4. void setLabel(String str): To line the label, call setLabel(). The string passed in str
becomes the new label related to the invoking checkbox.
import java.awt.*;
CheckboxExample() {
f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
new CheckboxExample();
OUTPUT:
OUTPUT:
List
This component will display a group of items as a drop-down menu from which a user can select
only one item. The List class provides a compact, multiple-choice, scrolling selection list. Unlike
the selection object, which shows only the only selected item within the menu, an inventory
object is often constructed to point out any number of choices within the visible window. It also
can be created to permit multiple selections.
Creating List : List l = new List(int, Boolean);
List Constructor
1. List() throws HeadlessException: It creates a list control that allows only one item to be
selected at any one time.
2. List(int numRows) throws HeadlessException: Here, the value of numRows specifies the
number of entries in the list that will always be visible.
3. List(int numRows, booleanmultipleSelect) throws HeadlessException: If multipleSelect
is true, then the user may select two or more items at a time. If it’s false, then just one
item could also be selected.
Method of Lists
1. void add(String name): To add a selection to the list, use add(). Here, the name is the
name of the item being added. It adds items to the end of the list.
2. void add(String name, int index): It also adds items to the list but it adds the items at the
index specified by the index.
3. String getSelectedItem(): It determines which item is currently selected. It returns a string
containing the name of the item. If more than one item is selected, or if no selection has
been made yet, null is returned.
4. int getSelectedIndex(): It determines which item is currently selected. It returns the index
of the item. The first item is at index 0. If more than one item is selected, or if no
selection has yet been made, -1 is returned.
5. String[] getSelectedItems(): It allows multiple selections. It returns an array containing
the names of the currently selected items.
6. int[] getSelectedIndexes(): It also allows multiple selections. It returns an array
containing the indexes of the currently selected items.
7. int getItemCount(): It obtains the number of items in the list.
8. void select(int index): It is used to set the currently selected item with a zero-based
integer index.
9. String getItem(int index): It is used to obtain the name associated with the item at the
given index. Here, the index specifies the index of the desired items.
Example:
import java.awt.*;
import java.awt.event.*;
public class ListExamp
{
ListExamp() {
Frame f = new Frame();
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(500, 100);
Button b = new Button("Show");
b.setBounds(200, 150, 80, 30);
final List l1 = new List(4, false);
l1.setBounds(100, 100, 70, 70);
l1.add("C");
l1.add("C++");
l1.add("Java");
l1.add("PHP");
final List l2=new List(4, true);
l2.setBounds(100, 200, 70, 70);
l2.add("Turbo C++");
l2.add("Spring");
l2.add("Hibernate");
l2.add("CodeIgniter");
f.add(l1);
f.add(l2);
f.add(label);
f.add(b);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected:
"+l1.getItem(l1.getSelectedIndex());
data += "\nFramework Selected:";
for(String frame:l2.getSelectedItems()) {
data += frame + " ";
}
label.setText(data);
}
});
}
public static void main(String args[])
{
new ListExamp();
}
}
OUTPUT:
Text Field
The TextField component will allow the user to enter some text. It is used to implement a
single-line text-entry area, usually called an edit control. It also allows the user to enter
strings and edit the text using the arrow keys, cut and paste keys, and mouse selections.
TextField is a subclass of TextComponent.
TextField Constructors
3. TextField(String str) throws HeadlessException: It initializes the text field with the string
contained in str.
TextField Methods
1. String getText(): It is used to obtain the string currently contained in the text field.
2. void setText(String str): It is used to set the text. Here, str is the new String.
3. void select(int startIndex, int endIndex): It is used to select a portion of the text under
program control. It selects the characters beginning at startIndex and ending at endIndex-
1.
7. void setEchoChar(char ch): It is used to disable the echoing of the characters as they are
typed. This method specifies a single character that TextField will display when
characters are entered.
8. booleanechoCharIsSet(): By this method, you can check a text field to see if it is in this
mode.
Text Area
Sometimes one line of text input isn’t enough for a given task. To handle these situations, the
AWT includes an easy multiline editor called TextArea.
TextArea Constructor
3. TextArea(String str) throws HeadlessException: It initializes the text area with the string
contained in str.
1. SCROLLBARS_BOTH
2. SCROLLBARS_NONE
3. SCROLLBARS_HORIZONTAL_ONLY
4. SCROLLBARS_VERTICAL_ONLY
TextArea Methods
2. void insert(String str, int index): It inserts the string passed in str at the specified index.
3. voidReplaceRange(String str, int startIndex, int endIndex): It is used to replace the text. It
replaces the characters from startIndex to endIndex-1.
import java.awt.*;
import java.awt.event.*;
TextField nameField;
List itemList;
TextArea displayArea;
Button showButton;
public TextFieldTextAreaListExample() {
setSize(400, 300);
setLayout(new FlowLayout());
add(nameField);
// Create a List with multiple items and add it to the Frame
itemList.add("Java");
itemList.add("Python");
itemList.add("C++");
itemList.add("JavaScript");
itemList.add("Ruby");
add(itemList);
add(displayArea);
showButton.addActionListener(this);
add(showButton);
setVisible(true);
addWindowListener(new WindowAdapter() {
dispose();
}
});
@Override
displayArea.setText(displayText);
new TextFieldTextAreaListExample();
OUTPUT:
Choice
This component will display a group of times as a drop-down menu from which a user can select
only one item. The choice component is used to create a pop-up list of items from which the user
may choose. Therefore, Choice control is a form of a menu. When it is inactive, a Choice
component takes up only enough space to show the currently selected item. When the user clicks
on a Choice component, the whole list of choices pops up, and a new selection can be made.
Note: Choice only defines the default constructor, which creates an empty list.
Creating Choice : Choice ch = new Choice();
Choice Methods
1. void add(String name): To add a selection to the list, use add(). Here, the name is the
name of the item being added.
2. String getSelectedItem(): It determines which item is currently selected. It returns a string
containing the name of the item.
3. int getSelectedIndex(): It determines which item is currently selected. It returns the index
of the item.
4. int getItemCount(): It obtains the number of items in the list.
5. void select(int index): It is used to set the currently selected item with a zero-based
integer index.
6. void select(String name): It is used to set the currently selected item with a string that
will match a name in the list.
7. String getItem(int index): It is used to obtain the name associated with the item at the
given index. Here, the index specifies the index of the desired items.
Example:
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
//Choice in Java AWT
class MyApp extends Frame{
Choice c;
Button btn;
Label lbl;
public MyApp() {
super("Choice Example");
setSize(1000, 600);// w,h
setLayout(null);
setVisible(true);
c = new Choice();
c.setBounds(10, 50, 100, 100);
c.add("C");
c.add("C++");
c.add("Java");
c.add("PHP");
c.add("Android");
btn = new Button("Show Details");
btn.setBounds(120, 50, 100, 20);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: " + c.getItem(c.getSelectedIndex());
lbl.setText(data);
}
});
lbl = new Label("Empty Label");
lbl.setBounds(10, 70, 300, 30);
add(c);
add(btn);
add(lbl);
// Close Button Code
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}
public class appchoice {
public static void main(String[] args) {
MyApp frm = new MyApp();
}
}
OUTPUT:
Canvas
Canvas encapsulates a blank window upon which you can draw in an application or receive
inputs created by the user.
Canvas Constructor:
1. Canvas() : Constructs a new Canvas.
2. Canvas (GraphicsConfiguration config) : Constructs a new Canvas given a
GraphicsConfiguration object.
Canvas Methods:
1. void addNotify(): It is used to create the peer of the canvas.
2. void createBufferStrategy(int numBuffers): It is used to create a new strategy for multi-
buffering on this component.
3. BufferStrategygetBufferStrategy(): It is used to return the BufferStrategy used by this
component.
Example:
import java.awt.*;
import java.awt.event.*;
//Canvas in Java AWT
class MyCanvas extends Canvas
{
public MyCanvas() {
setBackground (Color.GRAY);
setSize(300, 200);
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
}
}
class MyApp extends Frame{
public MyApp() {
super("Tutor Joes");
setSize(1000, 600);// w,h
setLayout(null);
setVisible(true);
add(new MyCanvas());
// Close Button Code
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}
public class appcanvas {
public static void main(String[] args) {
MyApp frm = new MyApp();
}
}
OUTPUT:
Image
Image control is superclass for all image classes representing graphical images.
Class declaration
Following is the declaration for java.awt.Image class:
public abstract class Image extends Object
Field
Following are the fields for java.awt.Image class:
● protected float accelerationPriority -- Priority for accelerating this image.
● static int SCALE_AREA_AVERAGING -- Use the Area Averaging image scaling
algorithm.
● static int SCALE_DEFAULT -- Use the default image-scaling algorithm.
● static int SCALE_FAST -- Choose an image-scaling algorithm that gives higher priority
to scaling speed than smoothness of the scaled image.
● static int SCALE_REPLICATE -- Use the image scaling algorithm embodied in the
ReplicateScaleFilter class.
● static int SCALE_SMOOTH -- Choose an image-scaling algorithm that gives higher
priority to image smoothness than scaling speed.
● static Object UndefinedProperty -- The UndefinedProperty object should be returned
whenever a property which was not defined for a particular image is
Class constructors
1 Image()
Class methods
void flush()
1
Flushes all reconstructable resources being used by this Image object.
2 float getAccelerationPriority()
Returns the current value of the acceleration priority hint.
Methods inherited
This class inherits methods from the following classes:
● java.lang.Object
Example
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
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.showImageDemo();
}
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);
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 showImageDemo(){
headerLabel.setText("Control in action: Image");
controlPanel.add(new ImageComponent("resources/java.jpg"));
mainFrame.setVisible(true);
}
class ImageComponent extends Component {
BufferedImage img;
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
public ImageComponent(String path) {
try {
img = ImageIO.read(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
}
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100,100);
} else {
return new Dimension(img.getWidth(), img.getHeight());
} } }}
OUTPUT:
Scroll Bar
Scrollbars are used to select continuous values between a specified minimum and maximum.
Scroll bars may be oriented horizontally or vertically. A scroll bar is really a composite of
several individual parts. Each end has an arrow that you simply can click to get the present value
of the scroll bar one unit within the direction of the arrow. The current value of the scroll bar
relative to its minimum and maximum values are indicated by the slider box for the scroll bar.
Scrollbars are encapsulated by the Scrollbar class.
Creating Scrollbar : Scrollbar sb = new Scrollbar();
Scrollbar Constructor
1. Scrollbar() throws HeadlessException: It creates a vertical scrollbar.
2. Scrollbar(int style) throws HeadlessException: It allows you to specify the orientation of
the scrollbar. If the style isScrollbar.VERTICAL, a vertical scrollbar is created. If a style
is Scrollbar.HORIZONTAL, the scroll bar is horizontal.
3. Scrollbar(int style, int initialValue, int thumbSize, int min, int max) throws
HeadlessException: Here, the initial value of the scroll bar is passed in initialValue. The
number of units represented by the peak of the thumb is passed in thumbSize. The
minimum and maximum values for the scroll bar are specified by min and max.
Scrollbar Methods
1. void setValues(int initialValue, int thumbSize, int min, int max): It is used to set the
parameters of the constructors.
2. int getValue(): It is used to obtain the current value of the scroll bar. It returns the current
setting.
3. void setValue(int newValue): It is used to set the current value. Here, newValue specifies
the new value for the scroll bar. When you set a worth, the slider box inside the scroll bar
is going to be positioned to reflect the new value.
4. int getMaximum(): It is used to retrieve the minimum values. They return the requested
quantity. By default, 1 is the increment added to the scroll bar.
5. int getMaximun(): It is used to retrieve the maximum value. By default, 1 is the
increment subtracted from the scroll bar.
Example:
import java.awt.*;
import java.awt.event.*;
public class TextAreaWithScrollbars extends Frame {
private TextArea textArea;
public TextAreaWithScrollbars() {
// Set up the Frame properties
setTitle("TextArea with Scrollbars Example");
setSize(400, 300);
setLayout(null);
setVisible(true);
// Add a window listener to handle the close operation
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Initialize the TextArea with scrollbars
textArea = new TextArea("Enter your text here...", 10, 30,
TextArea.SCROLLBARS_BOTH);
textArea.setBounds(50, 50, 300, 200); // Position and size
// Add the TextArea to the Frame
add(textArea);
}
public static void main(String[] args) {
new TextAreaWithScrollbars();
} }
OUTPUT:
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.
AWT Dialog class declaration
public class Dialog extends Window
Example:
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();
}
}
OUTPUT:
File Dialog
Java's FileDialog class is part of the AWT (Abstract Window Toolkit) package, specifically
designed for creating a file dialog box. This dialog box serves as an intermediary between the
user and the underlying file system, allowing users to browse through directories, select files,
and perform operations on the selected files. With its easy-to-use methods, developers can
integrate file-handling capabilities seamlessly into their Java applications.
Example:
import java.awt.FileDialog;
import java.awt.Frame;
fileDialog.setVisible(true);
if (file == null) {
} else {
// A file was selected; print the selected file's name to the console.
} } }
OUTPUT:
ScrollPane:
A ScrollPane in AWT is a container that provides a scrollable view for a component (such as a
TextArea or Panel) when the content is larger than the visible area of the container. It
automatically adds horizontal and vertical scrollbars when required.
EXAMPLE:
import java.awt.*;
// Create a frame
scrollPane.add(textArea);
frame.add(scrollPane);
// Set frame size and layout
frame.setLayout(new BorderLayout());
frame.setVisible(true);
frame.addWindowListener(new java.awt.event.WindowAdapter() {
System.exit(0);
});
} }
OUTPUT:
Dialogs:
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.
Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons but
Dialog doesn't have.
Class constructors
Dialog(Dialog owner)
1 Constructs an initially invisible, modeless Dialog with the specified owner Dialog and an
empty title.
4 Constructs an initially invisible Dialog with the specified owner Dialog, title, modality and
GraphicsConfiguration.
Dialog(Frame owner)
5 Constructs an initially invisible, modeless Dialog with the specified owner Frame and an
empty title.
9 Constructs an initially invisible Dialog with the specified owner Frame, title, modality, and
GraphicsConfiguration.
Dialog(Window owner)
10 Constructs an initially invisible, modeless Dialog with the specified owner Window and an
empty title.
11 Constructs an initially invisible Dialog with the specified owner Window and modality and an
empty title.
Class methods
void addNotify()
1
Makes this Dialog displayable by connecting it to a native screen resource.
AccessibleContext getAccessibleContext()
2
Gets the AccessibleContext associated with this Dialog.
Dialog.ModalityType getModalityType()
3
Returns the modality type of this dialog.
String getTitle()
4
Gets the title of the dialog.
void hide()
5
Deprecated. As of JDK version 1.5, replaced by setVisible(boolean).
boolean isModal()
6
Indicates whether the dialog is modal.
7 boolean isResizable()
Indicates whether this dialog is resizable by the user.
boolean isUndecorated()
8
Indicates whether this dialog is undecorated.
void setVisible(boolean b)
15
Shows or hides this Dialog depending on the value of parameter b.
16 void show()
Deprecated. As of JDK version 1.5, replaced by setVisible(boolean).
void toBack()
If this Window is visible, sends this Window to the back and may cause it to lose focus or
17
activation if it is the focused or active Window.
Methods inherited
● java.awt.Window
● java.awt.Component
● java.lang.Object
EXAMPLE:
import java.awt.*;
import java.awt.event.*;
Choice choice;
MyFrame() {
setLayout(new FlowLayout());
choice.add("Guntur");
choice.add("Vijayawada");
choice.add("Vizag");
choice.add("Kurnool");
choice.add("Tirupati");
add(choice);
choice.addItemListener(this);
dialog.setLayout(new FlowLayout());
dialog.setSize(200, 100);
dialog.add(okButton);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
});
dialog.setVisible(true);
} }
frame.setSize(500, 500);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
System.exit(0);
});
} }
Menubar:
Method Description
public void
Adds an action listener to the menu item.
addActionListener(ActionListener l)
The Java AWT Menu class represents a pop-up menu component in a graphical user interface
(GUI) that can contain a collection of MenuItem objects. It provides a way to create and manage
menus in Java AWT applications.
Method Description
public Menu(String label) Constructs a new menu with the specified label.
public void add(MenuItem mi) Adds the specified menu item to the menu.
public void addSeparator() Adds a separator between menu items within the menu.
public MenuShortcut getShortcut() Returns the menu shortcut key associated with this menu.
Example:
import java.awt.*;
import java.awt.event.*;
public MyApp() {
setLayout(null);
setVisible(true);
MenuBar m=new MenuBar();
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
m.add(menu);
setMenuBar(m);
this.addWindowListener(new WindowAdapter() {
System.exit(0);
});
} }
public class appmenu {
} }
OUTPUT:
Graphics:
The Graphics class is the abstract super class for all graphics contexts which allow an application
to draw onto components that can be realized on various devices, or onto off-screen images as
well.
Class declaration
Class constructors
Graphics() ()
1
Constructs a new Graphics object.
Class methods
1 Clears the specified rectangle by filling it with the background color of the current drawing
surface.
abstract void copyArea(int x, int y, int width, int height, int dx, int dy)
3
Copies an area of the component by a distance specified by dx and dy.
5 Creates a new Graphics object based on this Graphics object, but with a new translation and
clip area.
abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
8
Draws the outline of a circular or elliptical arc covering the specified rectangle.
void drawBytes(byte[] data, int offset, int length, int x, int y)
9 Draws the text given by the specified byte array, using this graphics context's current font and
color.
10 Draws the text given by the specified character array, using this graphics context's current
font and color.
11 observer)
abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor,
ImageObserver observer)
13
Draws as much of the specified image as has already been scaled to fit inside the specified
rectangle.
abstract boolean drawImage(Image img, int x, int y, int width, int height,
ImageObserver observer)
14
Draws as much of the specified image as has already been scaled to fit inside the specified
rectangle.
15 abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int
sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer)
Draws as much of the specified area of the specified image as is currently available, scaling it
on the fly to fit inside the specified area of the destination drawable surface.
abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int
sy1, int sx2, int sy2, ImageObserver observer)
16
Draws as much of the specified area of the specified image as is currently available, scaling it
on the fly to fit inside the specified area of the destination drawable surface.
abstract void drawLine(int x1, int y1, int x2, int y2)
17 Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics
context's coordinate system.
void drawPolygon(Polygon p)
20
Draws the outline of a polygon defined by the specified Polygon object.
23 abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int
arcHeight)
Draws an outlined round-cornered rectangle using this graphics context's current color.
24 Renders the text of the specified iterator applying its attributes in accordance with the
specification of the TextAttribute class.
25 Draws the text given by the specified string, using this graphics context's current font and
color.
abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)
27
Fills a circular or elliptical arc covering the specified rectangle.
void fillPolygon(Polygon p)
30 Fills the polygon defined by the specified Polygon object with the graphics context's current
color.
abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int
32 arcHeight)
Fills the specified rounded corner rectangle with the current color.
void finalize()
33
Disposes of this graphics context once it is no longer referenced.
Rectangle getClipBounds(Rectangle r)
36
Returns the bounding rectangle of the current clipping area.
Rectangle getClipRect()
37
Deprecated. As of JDK version 1.1, replaced by getClipBounds().
40 FontMetrics getFontMetrics()
Gets the font metrics of the current font.
47 Sets the paint mode of this graphics context to overwrite the destination with this graphics
context's current color.
Sets the paint mode of this graphics context to alternate between this graphics context's
current color and the new specified color.
String toString()
49
Returns a String object representing this Graphics object's value.
50 Translates the origin of the graphics context to the point (x, y) in the current coordinate
system.
Methods inherited
● java.lang.Object
Example:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public AWTGraphicsDemo(){
prepareGUI();
awtGraphicsDemo.setVisible(true);
setSize(400,400);
addWindowListener(new WindowAdapter() {
System.exit(0);
});
@Override
g.setColor(Color.GREEN);
g.setFont(font);
} }
OUTPUT:
Layout Manager in Java:
The layout will specify the format or the order in which the components have to be placed on the
container. Layout Manager may be a class or component that’s responsible for rearranging the
components on the container consistent with the required layout. A layout manager automatically
arranges your controls within a window by using some algorithm.
Each Container object features a layout manager related to it. A layout manager is an instance of
any class implementing the LayoutManager interface. The layout manager is about by the
setLayout( ) method. If no call to setLayout( ) is formed, the default layout manager is employed.
Whenever a container is resized (or sized for the primary time), the layout manager is employed
to position each of the components within it.
The setLayout( ) method has the subsequent general form: void setLayout(LayoutManager
layoutObj)
Here, layoutObj may be a regard to the specified layout manager. If you want to manually
disable the layout manager and position components, pass null for layoutObj. If you do this,
you’ll get to determine the form and position of every component manually, using the
setBounds() method defined by Component.
1. Flow Layout
2. Border Layout
3. Card Layout
4. Grid Layout
5. GridBag Layout
Flow Layout
This layout will display the components from left to right, from top to bottom. The components
will always be displayed in the first line and if the first line is filled, these components are
displayed on the next line automatically.
In this Layout Manager, initially, the container assumes 1 row and 1 column of the window.
Depending on the number of components and size of the window, the number of rows and
columns count is decided dynamically.
Note: If the row contains only one component, then the component is aligned in the center
position of that row.
Example
import java.awt.*;
import java.awt.event.*;
Frame f;
FlowLayoutDemo() {
// Create a Frame
f = new Frame();
// Create AWT components
f.add(l1);
f.add(tf1);
f.add(b1);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
f.setSize(300, 300);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
System.exit(0);
});
new FlowLayoutDemo();
} }
OUTPUT:
This layout will display the components along the border of the container. This layout contains
five locations where the component can be displayed. Locations are North, South, East, west,
and Center. The default region is the center. The above regions are the predefined static
constants belonging to the BorderLayout class. Whenever other regions’ spaces are not in use,
automatically container is selected as a center region default, and the component occupies the
surrounding region’s spaces of the window, which damages the look and feel of the user
interface.
Creation of BorderLayout
Example
import java.awt.*;
f1.add (b5);
f1.setVisible (true);
OUTPUT:
Card Layout in Java
A card layout represents a stack of cards displayed on a container. At a time, only one card can
be visible, each containing only one component.
add(“Cardname”, Component);
show(Container, cardname): It is used to flip to the specified card with the given
name.
Example:
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
CardLayoutDemo() {
// Initialize buttons
b1 = new Button("Button1");
b2 = new Button("Button2");
b3 = new Button("Button3");
b4 = new Button("Button4");
b5 = new Button("Button5");
setLayout(cl);
add("Card1", b1);
add("Card2", b2);
add("Card3", b3);
add("Card4", b4);
add("Card5", b5);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
// Frame properties
setSize(400, 400);
setVisible(true);
// Close operation
addWindowListener(new WindowAdapter() {
System.exit(0);
});
new CardLayoutDemo();
} }
OUTPUT:
Grid Layout in Java
The layout will display the components in the format of rows and columns statically. The
container will be divided into a table of rows and columns. The intersection of a row and column
cell and every cell contains only one component, and all the cells are of equal size. According to
Grid Layout Manager, the grid cannot be empty.
GridLayout gl = new GridLayout(int rows, int cols, int vgap, int hgap);
Example
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
Frame frameObj;
// Constructor
GridLayoutExampleee() {
// Creating 9 buttons
Button btn1 = new Button("1");
frameObj.add(btn1);
frameObj.add(btn2);
frameObj.add(btn3);
frameObj.add(btn4);
frameObj.add(btn5);
frameObj.add(btn6);
frameObj.add(btn7);
frameObj.add(btn8);
frameObj.add(btn9);
// Setting frame size and visibility
frameObj.setSize(300, 300);
frameObj.setVisible(true);
frameObj.addWindowListener(new WindowAdapter() {
System.exit(0);
});
// Main method
new GridLayoutExampleee();
} }
OUTPUT:
Grid Bag Layout in Java
In GridLayout manager, there is no grid control, i.e., inside a grid, we cannot align the
component in a specific position. To overcome this problem, we have an advanced Layout
Manager, i.e., Grid Bag Layout Manager. This layout is the most efficient layout that can be used
for displaying components. In this layout, we can specify the location, size, etc. In this Layout
manager, we need to define grid properties or constraints for each grid. Based on grid properties,
the layout manager aligns a component on the grid, and we can also span multiple grids as per
the requirement. Gris properties are defined using the GridBagConstraints class.
Note: We can specify the location (or) the size with the help of GridBagConstraints.
Properties of GridBagConstraints:
gridx, gridy: For defining x and y coordinate values, i.e., specifying grid location.
gridwidth, grid height: For defining the number of grids to span a document.
fill: Used whenever component size is greater than the area (i.e., VERTICAL or
HORIZONTAL).
ipadx, ipady: For defining the width and height of the components, i.e., for increasing
component size.
insets: For defining the surrounding space of the component, i.e., top, left, right, bottom.
anchor: Used whenever component size is smaller than area, i.e., where to place in a grid.
The above format is equal to one grid, so we can specify components in any grid position.
weightx, weighty: These are used to determine how to distribute space among columns(weightx)
and among rows(weighty), which is important for specifying resizing behavior.
Example
import java.awt.*;
public GridBagLayoutExampleee() {
setLayout(grid);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridx = 0;
gbc.gridy = 2;
setSize(300, 300);
setVisible(true);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent we) {
System.exit(0);
});
} }
OUTPUT: