0% found this document useful (0 votes)
2 views45 pages

aaaa Java UNIT-1

Advance Java is an extension of the Java programming language designed for developing web-based and enterprise applications, incorporating technologies like Servlets, JSP, and JDBC. It simplifies multi-tier application development and provides frameworks for secure transaction-based applications. The document also contrasts Core Java and Advance Java, detailing Java SE and Java EE, and covers Java AWT for GUI development, including event handling and component usage.

Uploaded by

dncvpssmcbca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views45 pages

aaaa Java UNIT-1

Advance Java is an extension of the Java programming language designed for developing web-based and enterprise applications, incorporating technologies like Servlets, JSP, and JDBC. It simplifies multi-tier application development and provides frameworks for secure transaction-based applications. The document also contrasts Core Java and Advance Java, detailing Java SE and Java EE, and covers Java AWT for GUI development, including event handling and component usage.

Uploaded by

dncvpssmcbca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Advance Java

It is a part of Java programming language. It is an advanced technology or


advance version of Java specially designed to develop web-based, network-centric
or enterprise applications. It includes the concepts like Servlet, JSP,
JDBC, RMI, Socket programming, etc. It is a specialization in specific domain.
Most of the applications developed using advance Java uses tow-tier
architecture i.e. Client and Server. All the applications that runs on Server can be
considered as advance Java applications.
Why advance Java?
o It simplifies the complexity of a building n-tier application.
o Standardizes and API between components and application sever
container.
o JEE application Server and Containers provides the framework services.
Benefits of Advance Java
The four major benefits of advance Java that are, network centric, process
simplification, and futuristic imaging standard.
o JEE (advance Java) provides libraries to understand the concept of Client-
Server architecture for web- based applications.
o We can also work with web and application servers such as Apache
Tomcat and Glassfish Using these servers, we can understand the working
of HTTP protocol. It cannot be done in core Java.
o It is also important understand the advance Java if you are dealing with
trading technologies like cloud-native and data science.
o It provides a set of services, API and protocols, that provides the
functionality which is necessary for developing multi-tiered application,
web-based application.
o There is a number of advance Java frameworks like, Spring, Hibernate,
Struts, that enables us to develop secure transaction-based web
applications such as banking application, inventory management
application.
Difference between Core Java and Advance Java
Criteria Core Java Advance Java
Used for It is used to develop general It is used to develop web-based
purpose application.(Stand applications.
Alone)
Purpose It does not deal with database, It deals with socket
socket programming, etc. programming, Document Object
Model (DOM), and networking
applications.
Architectu It is a single tier architecture. It is a mute-tier architecture.
re
Edition It is a Java Standard Edition. It is a Java Enterprise Edition.
Package It provides java.lang.* It provides java.servlet.*
package. package.

Java SE(Standard Edition)


When most people think of the Java programming language, they think of
the Java SE API. Java SE's API provides the core functionality of the Java
programming language. It defines everything from the basic types and objects of
the Java programming language to high-level classes that are used for networking,
security, database access, graphical user interface (GUI) development, and XML
parsing.
In addition to the core API, the Java SE platform consists of a virtual
machine, development tools, deployment technologies, and other class libraries
and toolkits commonly used in Java technology applications.
Java EE (Enterprise Edition)
The Java EE platform is built on top of the Java SE platform. The Java EE
platform provides an API and runtime environment for developing and running
large-scale, multi-tiered, scalable, reliable, and secure network applications.
Java AWT Tutorial
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface
(GUI) or windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavy weight i.e. its
components are using the resources of underlying operating system (OS).
The java.awt package provides classes for AWT API such
as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below, all the classes are available
in java.awt package.

Component class
Component class is at the top of AWT hierarchy. It is an abstract class that
encapsulates all the attributes of visual component. A component object is
responsible for remembering the current foreground and background colors and
the currently selected text font.
Containers
Container in Java AWT is a component that is used to hold other components
such as text fields, buttons, etc. It is a subclass of java.awt.Component and is
responsible for keeping a track of components being added. There are four types
of containers provided by AWT in Java.
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu bars. You must use
frame, dialog or another window for creating a window. We need to create an
instance of Window class to create this container.
Panel
Panel is the concrete subclass of Container and doesn’t contain any title bar,
menu bar or border It is generic container for holding the components. It can
have other components like button, text field etc. An instance of Panel class
creates a container, in which we can add components.
Frame
The Frame is the container that contain title bar and border and can have menu
bars. It can have other components like button, text field, scrollbar etc. Frame is
most widely used container while developing an AWT application.
There are two ways to create a Frame.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)
=================================================
1. By extending Frame class (inheritance)
import java.awt.*;
import java.awt.event.*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
b.setBounds(30,100,80,30); // setting button position
add(b); //adding button into frame
setSize(300,300); //frame size 300 width and 300 height
setLayout(null); //no layout now bydefaultBorderLayout
setVisible(true); //now frame willbe visible, bydefault not visible
}
public static void main(String args[])
{
First f=new First();
}
}

===================================================================
==
2. By creating the object of Frame class (association)
EX-1
import java.awt.*;
public class Testawt
{
Testawt()
{
Frame fm=new Frame(); //Creating a frame
Label lb = new Label("welcome to java graphics"); //Creating a label
fm.add(lb); //adding label to the frame
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true
}
public static void main(String args[])
{
Testawt ta = new Testawt();
}
}

===================================================================
EX-2

// importing Java AWT class


import java.awt.*;

class AWTExample2 // class AWTExample2 directly creates instance of


Frame class
{

AWTExample2() // initializing using constructor


{
Frame f = new Frame(); // creating a Frame
Label l = new Label("Employee id:"); // creating a Label
Button b = new Button("Submit"); // creating a Button
TextField t = new TextField(); // creating a TextField
// setting position of above components in the frame
l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);
f.add(b); // adding components into frame
f.add(l);
f.add(t);
f.setSize(400,300); // frame size 300 width and 300
height
f.setTitle("Employee info"); // setting the title of frame
f.setLayout(null); // no layout
f.setVisible(true); // setting visibility of frame
}
public static void main(String args[])
{
// creating instance of Frame class
AWTExample2 awt_obj = new AWTExample2();
}
}

===================================================================
=====
Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on
button, dragging mouse etc. The java.awt.event package provides many event
classes and Listener interfaces for event handling.
Java Event classes and Listener interfaces
Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener
Steps to perform Event Handling
Following steps are required to perform event handling:
1. Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
Java Event Handling Code
We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
Java event handling by implementing ActionListener
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener
{
TextField tf;
AEvent()
{
tf=new TextField(); //create components
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
//add components and set size, layout and visibili
ty
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
public void setBounds(int xaxis, int yaxis, int width, int height); have been used
in the above example that sets the position of the component it may be button,
textfield etc.
Skip Ad

=============================================================
3) Java event handling by anonymous class
import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame
{
TextFieldtf;
AEvent3()
{
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}
===================================================================
=
Java AWT Label
The object of the Label class is a component for placing text in a container. It is
used to display a single line of read only text. The text can be changed by a
programmer but a user cannot edit it directly.
It is called a passive control as it does not create any event when it is accessed. To
create a label, we need to create the object of Label class.
AWT Label Class Declaration
1. public class Label extends Component implements Accessible
AWT Label Fields
The java.awt.Component class has following fields:
1. static int LEFT: It specifies that the label should be left justified.
2. static int RIGHT: It specifies that the label should be right justified.
3. static int CENTER: It specifies that the label should be placed in center.
Label class Constructors
Sr. no. Constructor Description
1. Label() It constructs an empty label.
2. Label(String It constructs a label with the given string (left justified
text) by default).
3. Label(String It constructs a label with the specified string and the
text, int specified alignment.
alignement)
Label Class Methods
Sr. no. Method name Description
1. void setText(String It sets the texts for label with the specified text.
text)
2. Void setAlignment It sets the alignment for label with the specified
(int alignment) alignment.
3. String getText() It gets the text of the label
4. int getAlignment() It gets the current alignment of the label.
5. void addNotify() It creates the peer for the label.
6. AccessibleContext It gets the Accessible Context associated with
getAccessibleContext( the label.
)
7. protected String It returns the string the state of the label.
paramString()
Method inherited
The above methods are inherited by the following classes:
o java.awt.Component
o java.lang.Object
Java AWT Label Example
In the following example, we are creating two labels l1 and l2 using the
Label(String text) constructor and adding them into the frame.
LabelExample.java
import java.awt.*;
public class LabelExample
{
public static void main(String args[]){
// creating the object of Frame class and Label class
Frame f = new Frame ("Label example");
Label l1, l2;
l1 = new Label ("First Label."); // initializing the labels
l2 = new Label ("Second Label.");
l1.setBounds(50, 100, 100, 30); // set the location of label
l2.setBounds(50, 150, 100, 30);
f.add(l1); // adding labels to the frame
f.add(l2);
f.setSize(400,400); // setting size, layout and visibility of frame
f.setLayout(null);
f.setVisible(true);
}
}

Java AWT Label Example with ActionListener


In the following example, we are creating the objects of TextField, Label
and Button classes and adding them to the Frame. Using the actionPerformed()
method an event is generated over the button. When we add the website in the
text field and click on the button, we get the IP address of website.
LabelExample2.java
import java.awt.*;
import java.awt.event.*;
// creating class which implements ActionListener interface and inherits Frame class
public class LabelExample2 extends Frame implements ActionListener
{
// creating objects of TextField, Label and Button class
TextField tf;
Label l;
Button b;
// constructor to instantiate the above objects
LabelExample2()
{
tf = new TextField();
tf.setBounds(50, 50, 150, 20);
l = new Label();
l.setBounds(50, 100, 250, 20);
b = new Button("Find IP");
b.setBounds(50,150,60,30);
b.addActionListener(this);
add(b); add(tf); add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
}
// defining actionPerformed method to generate an event
public void actionPerformed(ActionEvent e) {
try {
String host = tf.getText();
String ip =
java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+host+" is: "+ip);
}
catch (Exception ex) {
System.out.println(ex);
}
}
public static void main(String[] args) { // main method
new LabelExample2();
}
}

Java AWT TextField


The object of a TextField class is a text component that allows a user to enter a
single line text and edit it. It inherits TextComponent class, which further
inherits Component class.
When we enter a key in the text field (like key pressed, key released or key
typed), the event is sent to TextField. Then the KeyEvent is passed to the
registered KeyListener. It can also be done using ActionEvent; if the ActionEvent
is enabled on the text field, then the ActionEvent may be fired by pressing return
key. The event is handled by the ActionListener interface.
AWT TextField Class Declaration
1. public class TextField extends TextComponent
TextField Class constructors
Sr.
no.
Constructor Description
1. TextField() It constructs a new text field component.
2. TextField(String text) It constructs a new text field initialized with the
given string text to be displayed.
3. TextField(int columns) It constructs a new textfield (empty) with given
number of columns.
4. TextField(String text, It constructs a new text field with the given text
int columns) and given number of columns (width).
TextField Class Methods
Sr. Method name Description
no.
1. void addNotify() It creates the peer of text field.
2. boolean echoCharIsSet() It tells whether text field has character
set for echoing or not.
3. void addActionListener It adds the specified action listener to
(ActionListener l) receive action events from the text
field.
4. ActionListener[] It returns array of all action listeners
getActionListeners() registered on text field.
5. AccessibleContext It fetches the accessible context related
getAccessibleContext() to the text field.
6. int getColumns() It fetches the number of columns in
text field.
7. char getEchoChar() It fetches the character that is used for
echoing.
8. Dimension getMinimumSize() It fetches the minimum dimensions for
the text field.
9. Dimension getMinimumSize(int It fetches the minimum dimensions for
columns) the text field with specified number of
columns.
10. Dimension getPreferredSize() It fetches the preferred size of the text
field.
11. Dimension getPreferredSize(int It fetches the preferred size of the text
columns) field with specified number of columns.
12. protected String paramString() It returns a string representing state of
the text field.
13. protected void It processes action events occurring in
processActionEvent(ActionEven the text field by dispatching them to a
t e) registered ActionListener object.
14. protected void It processes the event on text field.
processEvent(AWTEvent e)
15. void removeActionListener It removes specified action listener so
(ActionListener l) that it doesn't receive action events
anymore.
16. void setColumns(int columns) It sets the number of columns in text
field.
17. void setEchoChar(char c) It sets the echo character for text field.
18. void setText(String t) It sets the text presented by this text
component to the specified text.
Method Inherited
The AWT TextField class inherits the methods from below classes:
1. java.awt.TextComponent
2. java.awt.Component
3. java.lang.Object
Java AWT TextField Example
TextFieldExample1.java

// importing AWT class


import java.awt.*;
public class TextFieldExample1
{
public static void main(String args[]) // main method
{
Frame f = new Frame("TextField Example"); // creating a
frame
TextField t1, t2; // creating objects of
textfield
// instantiating the textfield objects
// setting the location of those objects in the frame
t1 = new TextField("Welcome to Javatpoint.");
t1.setBounds(50, 100, 200, 30);
t2 = new TextField("AWT Tutorial");
t2.setBounds(50, 150, 200, 30);
f.add(t1); // adding the components to frame
f.add(t2);
f.setSize(400,400); // setting size, layout and visibility of frame
f.setLayout(null);
f.setVisible(true);
}
}

Java AWT TextField Example with ActionListener


TextFieldExample2.java
import java.awt.*;
import java.awt.event.*;
// Our class extends Frame class and implements ActionListener interface
public class TextFieldExample2 extends Frame implements ActionListener
{
TextField tf1, tf2, tf3; // creating instances of TextField
Button b1, b2; // creating instances of Button class
TextFieldExample2() // instantiating using constructor
{
// instantiating objects of text field and button
// setting position of components in frame
tf1 = new TextField();
tf1.setBounds(50, 50, 150, 20);
tf2 = new TextField();
tf2.setBounds(50, 100, 150, 20);
tf3 = new TextField();
tf3.setBounds(50, 150, 150, 20);
tf3.setEditable(false);
b1 = new Button("+");
b1.setBounds(50, 200, 50, 50);
b2 = new Button("-");
b2.setBounds(120,200,50,50);
// adding action listener
b1.addActionListener(this);
b2.addActionListener(this);
// adding components to frame
add(tf1);
add(tf2);
add(tf3);
add(b1);
add(b2);
// setting size, layout and visibility of frame
setSize(300,300);
setLayout(null);
setVisible(true);
}
// defining the actionPerformed method to generate an event on buttons
public void actionPerformed(ActionEvent e)
{
String s1 = tf1.getText();
String s2 = tf2.getText();
int a = Integer.parseInt(s1);
int b = Integer.parseInt(s2);
int c = 0;
if (e.getSource() == b1){
c = a + b;
}
else if (e.getSource() == b2){
c = a - b;
}
String result = String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) { // main method
new TextFieldExample2();
}
}

Java AWT TextArea


The object of a TextArea class is a multiline region that displays text. It allows the
editing of multiple line text. It inherits TextComponent class.
The text area allows us to type as much text as we want. When the text in the text
area becomes larger than the viewable area, the scroll bar appears automatically
which helps us to scroll the text up and down, or right and left.
AWT TextArea Class Declaration
1. public class TextArea extends TextComponent
Fields of TextArea Class
The fields of java.awt.TextArea class are as follows:
o static int SCROLLBARS_BOTH - It creates and displays both horizontal and
vertical scrollbars.
o static int SCROLLBARS_HORIZONTAL_ONLY - It creates and displays only
the horizontal scrollbar.
o static int SCROLLBARS_VERTICAL_ONLY - It creates and displays only the
vertical scrollbar.
o static int SCROLLBARS_NONE - It doesn't create or display any scrollbar in
the text area.
Class constructors:
Sr. Constructor Description
no.
1. TextArea() It constructs a new and empty text area with no
text in it.
2. TextArea (int row, It constructs a new text area with specified number
int column) of rows and columns and empty string as text.
3. TextArea (StringIt constructs a new text area and displays the
text) specified text in it.
4. TextArea (StringIt constructs a new text area with the specified text
text, int row, int in the text area and specified number of rows and
column) columns.
5. TextArea (StringIt construcst a new text area with specified text in
text, int row, int text area and specified number of rows and
column, int
columns and visibility.
scrollbars)
Methods Inherited
The methods of TextArea class are inherited from following classes:
o java.awt.TextComponent
o java.awt.Component
o java.lang.Object
example:
// importing necessary libraries
import java.awt.*;
import java.awt.event.*;
// our class extends the Frame class to inherit its properties
// and implements ActionListener interface to override its methods
public class TextAreaExample2 extends Frame implements ActionListener {
// creating objects of Label, TextArea and Button class.
Label l1, l2;
TextArea area;
Button b;
TextAreaExample2() { // constructor to instantiate
// instantiating and setting the location of components on the frame
l1 = new Label();
l1.setBounds(50, 50, 100, 30);
l2 = new Label();
l2.setBounds(160, 50, 100, 30);
area = new TextArea();
area.setBounds(20, 100, 300, 300);
b = new Button("Count Words");
b.setBounds(100, 400, 100, 30);
b.addActionListener(this); // adding ActionListener to button
add(l1); // adding components to frame
add(l2);
add(area);
add(b);
setSize(400, 450); // setting the size, layout and visibility of
frame
setLayout(null);
setVisible(true);
}
// generating event text area to count number of words and characters
public void actionPerformed(ActionEvent e) {
String text = area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
public static void main(String[] args) { // main method
new TextAreaExample2();
}
}
Java AWT Checkbox
The Checkbox class is used to create a checkbox. It is used to turn an option on
(true) or off (false). Clicking on a Checkbox changes its state from "on" to "off" or
from "off" to "on".
AWT Checkbox Class Declaration
1. public class Checkbox extends Component implements ItemSelectable, Accessibl
e
Checkbox Class Constructors
Sr. Constructor Description
1. Checkbox() It constructs a checkbox with no string as the
label.
2. Checkbox(String label) It constructs a checkbox with the given label.
3. Checkbox(String label, It constructs a checkbox with the given label and
boolean state) sets the given state.
4. Checkbox(String label, It constructs a checkbox with the given label, set
boolean state, the given state in the specified checkbox group.
CheckboxGroup
group)
5. Checkbox(String label, It constructs a checkbox with the given label, in
CheckboxGroup the given checkbox group and set to the specified
group, boolean state) state.
Method inherited by Checkbox
The methods of Checkbox class are inherited by following classes:
o java.awt.Component
o java.lang.Object
example:
// importing necessary packages
import java.awt.*;
import java.awt.event.*;
public class CheckboxExample2
{
CheckboxExample2() { // constructor to initialize
Frame f = new Frame ("CheckBox Example"); // creating the frame
final Label label = new Label(); // creating the label
label.setAlignment(Label.CENTER); // setting the alignment, size of
label
label.setSize(400,100);
Checkbox checkbox1 = new Checkbox("C++"); // creating the
checkboxes
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java");
checkbox2.setBounds(100, 150, 50, 50);
f.add(checkbox1); // adding the checkbox to frame
f.add(checkbox2);
f.add(label);
// adding event to the checkboxes
checkbox1.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
checkbox2.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
f.setSize(400,400); // setting size, layout and visibility of frame
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]) // main method
{
new CheckboxExample2();
}
}

Java AWT CheckboxGroup Example with ItemListener


import java.awt.*;
import java.awt.event.*;
public class CheckboxGroupExample
{
CheckboxGroupExample()
{
Frame f= new Frame("CheckboxGroup Example");
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, false);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1); f.add(checkBox2); f.add(label);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
checkBox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ checkbox: Checked");
}
});
checkBox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java checkbox: Checked");
}
});
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
Java AWT Choice
The object of Choice class is used to show popup menu of choices. Choice
selected by user is shown on the top of a menu. It inherits Component class.
AWT Choice Class Declaration
1. public class Choice extends Component implements ItemSelectable, Accessible
Choice Class constructor
Sr. no. Constructor Description
1. Choice() It constructs a new choice menu.
Methods inherited by class
The methods of Choice class are inherited by following classes:
o java.awt.Component
o java.lang.Object
// importing necessary packages
import java.awt.*;
import java.awt.event.*;
public class ChoiceExample2 {
ChoiceExample2() { // class constructor
Frame f = new Frame(); // creating a frame
final Label label = new Label(); // creating a final object of Label
class

label.setAlignment(Label.CENTER); // setting alignment of label


component
label.setSize(400, 100);
Button b = new Button("Show"); // creating a button
b.setBounds(200, 100, 50, 20); // setting the bounds of button
final Choice c = new Choice(); // creating final object of Choice
class
c.setBounds(100, 100, 75, 75); // setting bounds of choice menu
c.add("C"); // adding 5 items to choice menu
c.add("C++");
c.add("Java");
c.add("PHP");
c.add("Android");
f.add(c); // adding above components into the frame
f.add(label);
f.add(b);
f.setSize(400, 400); // setting size, layout and visibility of frame
f.setLayout(null);
f.setVisible(true);

// adding event to the button


// which displays the selected item from the list when button is clicked
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String data = "Programming language Selected: "+

c.getItem(c.getSelectedIndex());
label.setText(data);
}
});
}
public static void main(String args[])
{
new ChoiceExample2();
}
}
Java AWT List
The object of List class represents a list of text items. With the help of the List
class, user can choose either one item or multiple items. It inherits the
Component class.
AWT List class Declaration
public class List extends Component implements ItemSelectable, Accessible
AWT List Class Constructors
Sr. Constructor Description
no.
1. List() It constructs a new scrolling list.
2. List(int row_num) It constructs a new scrolling list initialized
with the given number of rows visible.
3. List(int row_num, It constructs a new scrolling list initialized
Boolean multipleMode) which displays the given number of rows.
Methods Inherited by the List Class
The List class methods are inherited by following classes:
o java.awt.Component
o java.lang.Object
// importing awt and event class
import java.awt.*;
import java.awt.event.*;
public class ListExample2
{
ListExample2() { // class constructor
Frame f = new Frame(); // creating the frame
final Label label = new Label(); // creating the label which is final
label.setAlignment(Label.CENTER); // setting alignment and size of label
label.setSize(500, 100);
Button b = new Button("Show"); // creating a button
b.setBounds(200, 150, 80, 30); // setting location of button
final List l1 = new List(4, false); // creating the 2 list objects of 4 rows
l1.setBounds(100, 100, 70, 70); // setting location of list components
l1.add("C"); // adding items to the list using add()
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); // adding List, Label and Button to the frame
f.add(l2);
f.add(label);
f.add(b);
f.setSize(450,450); // setting size, layout and visibility of frame
f.setLayout(null);
f.setVisible(true);
// generating event on the button
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
String data = "Programming language Selected:
"+l1.getItem(l1.getSelectedIndex());
data += ", Framework Selected:";
for(String frame:l2.getSelectedItems())
{ data += frame + " ";
}
label.setText(data);
}
});
}
public static void main(String args[])
{
new ListExample2();
}
}

Java AWT Canvas


The Canvas class controls and represents a blank rectangular area where the
application can draw or trap input events from the user. It inherits
the Component class.
AWT Canvas class Declaration
public class Canvas extends Component implements Accessible
Canvas Class Constructors
Sr. Constructor Description
no.
1. Canvas() It constructs a new Canvas.
2. Canvas(GraphicConfiguratio It constructs a new Canvas with the given
n config) Graphic Configuration object.
import java.awt.*;
public class CanvasExample
{
public CanvasExample() // class constructor
{
rame f = new Frame("Canvas Example"); // creating a frame
f.add(new MyCanvas()); // adding canvas to
frame
f.setLayout(null); // setting layout
f.setSize(400, 400); // setting size

f.setVisible(true); // setting visibility of


frame
}
public static void main(String args[]) // main method
{
new CanvasExample();
}
}
// class which inherits the Canvas class to create Canvas
class MyCanvas extends Canvas
{
public MyCanvas() // class constructor
{
setBackground (Color.GRAY);
setSize(300, 200);
}
public void paint(Graphics g) // paint() method to draw inside the
canvas
{
g.setColor(Color.red); // adding specifications
g.fillOval(75, 75, 150, 75);
}
}

Java AWT Scrollbar


The object of Scrollbar class is used to add horizontal and vertical scrollbar.
Scrollbar is a GUI component allows us to see invisible number of rows and
columns.
It can be added to top-level container like Frame or a component like Panel. The
Scrollbar class extends the Component class.
AWT Scrollbar Class Declaration
public class Scrollbar extends Component implements Adjustable, Accessible
Scrollbar Class Fields
The fields of java.awt.Image class are as follows:
o static int HORIZONTAL - It is a constant to indicate a horizontal scroll bar.
o static int VERTICAL - It is a constant to indicate a vertical scroll bar.
Scrollbar Class Constructors
Sr. Constructor Description
no.
1 Scrollbar() Constructs a new vertical scroll bar.
2 Scrollbar(int orientation) Constructs a new scroll bar with the
specified orientation.
3 Scrollbar(int orientation, int Constructs a new scroll bar with the
value, int visible, int specified orientation, initial value, visible
minimum, int maximum) amount, and minimum and maximum
values.
oOrientation: specifiey whether the scrollbar will be horizontal or vertical.
o Value: specify the starting position of the knob of Scrollbar on its track.
o Minimum: specify the minimum width of track on which scrollbar is
moving.
o Maximum: specify the maximum width of track on which scrollbar is
moving.
Method Inherited by Scrollbar
The methods of Scrollbar class are inherited from the following classes:
o java.awt.Component
o java.lang.Object
o
// importing necessary packages
import java.awt.*;
import java.awt.event.*;
public class ScrollbarExample2
{
ScrollbarExample2() // class constructor
{
Frame f = new Frame("Scrollbar Example"); // creating a Frame with a
title
final Label label = new Label(); // creating a final object of
Label
label.setAlignment(Label.CENTER); // setting alignment of label object
label.setSize(400, 100); // setting size of label object
final Scrollbar s = new Scrollbar(); // creating a final object of Scrollbar class
s.setBounds(100, 100, 50, 100); // setting the position of scroll bar
f.add(s); // adding Scrollbar and Label to the Frame
f.add(label);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
// adding AdjustmentListener to the scrollbar object
s.addAdjustmentListener(new AdjustmentListener()
{
public void adjustmentValueChanged(AdjustmentEvent e) {
label.setText("Vertical Scrollbar value is:"+ s.getValue());
}
});
}
public static void main(String args[]) // main method

{
new ScrollbarExample2();
}
}

==============================================================
AWT Menu Class
 A menu bar can be created using MenuBar class.
 A menu bar may contain one or multiple menus, and these menus are
created using Menu class.
 A menu may contain one of multiple menu items and these menu items are
created using MenuItem class.
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();
}
}
// Java program to create a menubar and add menuitems to it and also add menu
shortcut to MenuItems
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Shortcut_1 extends
Frame implements ActionListener {
static MenuBar menubar; // menubar
static Menu menu; // Menu
static MenuItem menuitem_1, menuitem_2, menuitem_3; // Menu items
static Frame frame; // create a frame
Label label; // create label
Shortcut_1() // default constructor
{
frame = new Frame("MenuShortcut Demo"); // create a
frame
// when exit button is pressed
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent)
{
System.exit(0);
}
});
menubar = new MenuBar(); // create a menubar
menu = new Menu("Menu"); // create a menu
label = new Label("Nothing Selected"); // create label
// create menu shortcuts
MenuShortcut menushortcut_1 =
new MenuShortcut(KeyEvent.VK_A, false);
MenuShortcut menushortcut_2 =
new MenuShortcut(KeyEvent.VK_B, false);
MenuShortcut menushortcut_3 =
new MenuShortcut(KeyEvent.VK_C, false);
// create menuitems
menuitem_1 = new MenuItem("MenuItem_1 ", menushortcut_1);
menuitem_2 = new MenuItem("MenuItem_2 ", menushortcut_2);
menuitem_3 = new MenuItem("MenuItem_3 ", menushortcut_3);
// add ActionListener to menuItems
menuitem_1.addActionListener(this);
menuitem_2.addActionListener(this);
menuitem_3.addActionListener(this);
menu.add(menuitem_1); // add menu items to menu
menu.add(menuitem_2);
menu.add(menuitem_3);
menubar.add(menu); // add menu to menu bar
frame.setMenuBar(menubar); // add menubar to frame
frame.add(label); // add label
frame.setSize(500, 500); // set the size of the frame
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) // when an action is performed
{
String s = e.getActionCommand();
label.setText(s + " selected"); // set the label to the menuItem that is
selected
}
public static void main(String args[]) // Main Method
{
Shortcut_1 m = new Shortcut_1(); // create an object
}
}
=================================================================
Java AWT Panel:
The Panel is a simplest container class. It provides space in which an application can attach any
other component. It inherits the Container class.
It doesn't have title bar.
AWT Panel class declaration
public class Panel extends Container implements Accessible
import java.awt.*;
public class PanelExample
{
PanelExample()
{
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}
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
public class Dialog extends Window
Java AWT Dialog 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();
}
}

Java MouseListener Interface:


The Java MouseListener is notified whenever you change the state of mouse. It is
notified against MouseEvent. The MouseListener interface is found in
java.awt.event package. It has five methods.
Methods of MouseListener interface
The signature of 5 methods found in MouseListener interface are given below:
a) public abstract void mouseClicked(MouseEvent e);
b) public abstract void mouseEntered(MouseEvent e);
c) public abstract void mouseExited(MouseEvent e);
d) public abstract void mousePressed(MouseEvent e);
e) public abstract void mouseReleased(MouseEvent e);
Ex.
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener
{
Label l;
MouseListenerExample()
{
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}

Java MouseMotionListener Interface


The Java MouseMotionListener is notified whenever you move or drag mouse. It
is notified against MouseEvent. The MouseMotionListener interface is found in
java.awt.event package. It has two methods.
Methods of MouseMotionListener interface
The signature of 2 methods found in MouseMotionListener interface are given
below:
1. public abstract void mouseDragged(MouseEvent e);
2. public abstract void mouseMoved(MouseEvent e);

Java MouseMotionListener Example


import java.awt.*;
import java.awt.event.*;
public class MouseMotionListenerExample extends Frame implements
MouseMotionListener
{
MouseMotionListenerExample()
{
addMouseMotionListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e)
{
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e)
{ }
public static void main(String[] args)
{
new MouseMotionListenerExample();
}
}
===================================================================
====
Ex.2
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class Paint extends Frame implements MouseMotionListener
{
Label l;
Color c=Color.BLUE;
Paint()
{
l=new Label();
l.setBounds(20,40,100,20);
add(l);
addMouseMotionListener(this);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e)
{
l.setText("X="+e.getX()+", Y="+e.getY());
Graphics g=getGraphics();
g.setColor(Color.RED);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e)
{
l.setText("X="+e.getX()+",
Y="+e.getY());
}
public static void main(String[] args)
{
new Paint();
}
}

==============================END===============================

You might also like