UNIT-5 Java Programming
UNIT-5 Java Programming
AWT Controls
AWT Controls:
Controls are components that allow a user to interact with our application.
The AWT supports the following types of controls:
• Labels
• Buttons
• Check boxes
• Choice lists
• Lists
• Scroll bars
• Text editing
All these controls are subclasses of Component class.
Adding Controls:
Steps to add a control to a container (Applet or Frame):
1. Create an instance of the desired control.
2. Add it to the container by calling the add method defined in Container class.
Component add(Component obj)
obj is the instance of the control.
Once a control is added, it will automatically visible on the container.
Removing Controls:
To remove a control, Container class defined a method:
void remove(Component obj)
Label:
Labels are passive controls that do not support any interaction with the user.
Label class Constructors:
Label( )
Label(String str)
Label(String str, int how)
str is the text of the Label
how specifies the alignment
Label.LEFT
Label.RIGHT
Label.CENTER
Methods:
void setText(String str)
String getText( )
void setAlignment(int how)
int getAlignment( )
Button:
A button (push button) is a component that contains a label and that generates
an event when it is pressed.
Button class Constructors:
Button( )
Button(String str)
Methods:
void setLabel(String str)
String getLabel( )
Checkbox:
A check box is a control that is used to turn an option on or off (check mark).
Each time a check box is selected or deselected, an item event is generated.
Checkbox class Constructors:
Checkbox( )
Checkbox(String str)
Checkbox(String str, boolean on)
Checkbox(String str, boolean on, CheckboxGroup cbg)
Checkbox(String str, CheckboxGroup cbg, boolean on)
Checkbox methods:
void setLabel(String str)
String getLabel( )
void setState(boolean on)
boolean getState( )
CheckboxGroup methods:
Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox cb)
Choice:
The Choice is used to create a pop-up list of items.
Each time a choice is selected, an item event is generated.
Choice class contains only the default constructor.
Choice methods:
void addItem(String name)
void add(String name)
String getSelectedItem( )
int getSelectedIndex( )
int getItemCount( )
void select(int index)
void select(String name)
String getItem(int index)
List:
The List provides a compact, multiple-choice, scrolling selection list.
A list shows a number of choices in the visible widow. It also allow multiple selections.
List constructors:
List( )
List(int numRows)
List(int numRows, boolean multipleSelect)
List methods:
void add(String name)
void add(String name, int index)
String getSelectedItem( )
int getSelectedIndex( )
String[ ] getSelectedItems( )
int[ ] getSelectedIndexes( )
int getItemCount( )
void select(int index)
String getItem(int index)
In List:
Each time an item in the list is selected or deselected with a single click, an item event is generated.
When a list item is double-clicked, an action event is generated.
Scrollbar:
Scrollbars are used to select continuous values between a specified minimum
and maximum.
Scrollbar constructors:
Scrollbar( )
Scrollbar(int style)
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
TextField:
TextField is a single line text entry area.
TexField is subclass of TextComponent.
TextField constructors:
TextField( )
TextField(int numChars)
TextField(String str)
TextField(String str, int numChars)
TextField methods:
String getText( )
void setText(String str)
String getSelectedText( )
void select(int startIndex, int endIndex)
boolean isEditable( )
void setEditable(boolean canEdit)
int getSelectionStart( )
int getSelectionEnd( )
void setEchoChar(char ch)
boolean echoCharIsSet( )
char getEchoChar( )
TextArea:
TextArea is a multiline editor.
TextArea is subclass of TextComponent.
TextArea constructors:
TextArea( )
TextArea(int numLines, int numChars)
TextArea(String str)
TextArea(String str, int numLines, int numChars)
TextArea(String str, int numLines, int numChars, int scrBars)
scrBars can be
SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
TextArea methods:
String getText( )
void setText(String str)
String getSelectedText( )
void select(int startIndex, int endIndex)
boolean isEditable( )
void setEditable(boolean canEdit)
int getSelectionStart( )
int getSelectionEnd( )
void append(String str)
void insert(String str, int index)
void replaceRange(String str, int startIndex, ine endIndex)
Menu:
Constructors:
Menu( )
Menu(String optionName)
Menu(String optionName, boolean removable)
MenuItem:
Constructors:
MenuItem( )
MenuItem(String itemName)
MenuItem(String itemName, MenuShortcut keyAccel)
CheckboxMenuItem:
Constructors:
CheckboxMenuItem( )
CheckboxMenuItem(String itemName)
CheckboxMenuItem(String itemName, boolean on)
MenuShortcut:
Constructors:
MenuShortcut(int key)
MenuShortcut(int key, boolean useShiftMidifier)
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 Listenerinterfaces
for event handling.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
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){}
//create components
tf=new TextField();
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
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e){
tf.setText("ANURAG UNIVERSITY");
}
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.
The button class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed.
import java.awt.*;
import java.awt.event.*;
OUTPUT
Java AWT Label
The object of Label class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit
it directly.
import java.awt.*;
import java.awt.event.*;
class LabelExample{
public static void main(String args[]){
Frame f= new Frame("Label Example");
Label l1,l2;
l1=new Label("User Name");
l1.setBounds(50,100, 100,30);
l2=new Label("Password");
l2.setBounds(50,150, 100,30);
f.add(l1); f.add(l2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
Output:
Java AWT TextField
The object of a TextField class is a text component that allows the editing of a single line
text. It inherits TextComponent class.
import java.awt.*;
import java.awt.event.*;
class TextFieldExample{
public static void main(String args[]){
Frame f= new Frame("TextField Example");
TextField t1,t2;
t1=new TextField("Anil Kumar");
t1.setBounds(50,100, 200,30);
t2=new TextField("Hyderabad");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
Output:
Java AWT TextArea
The object of a TextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits TextComponent class.
import java.awt.*;
import java.awt.event.*;
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".
import java.awt.*;
import java.awt.event.*;
Output:
Java AWT CheckboxGroup
The object of CheckboxGroup class is used to group together a set of Checkbox. At a time
only one check box button is allowed to be in "on" state and remaining check box button in
"off" state. It inherits the object class.
Output:
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.
import java.awt.*;
import java.awt.event.*;
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[])
{
new ChoiceExample();
}
}
Output:
Java AWT List
The object of List class represents a list of text items. By the help of list, user can choose
either one item or multiple items. It inherits Component class.
import java.awt.*;
import java.awt.event.*;
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[])
{
new ListExample();
}
}
Output:
Java AWT Canvas
The Canvas control represents a blank rectangular area where the application can draw or trap
input events from the user. It inherits the Component class.
import java.awt.*;
import java.awt.event.*;
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[])
{
new CanvasExample();
}
}
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.
import java.awt.*;
import java.awt.event.*;
class ScrollbarExample{
ScrollbarExample(){
Frame f= new Frame("Scrollbar Example");
Scrollbar s=new Scrollbar();
s.setBounds(100,100, 50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[])
{
new ScrollbarExample();
}
}
Output:
The object of MenuItem class adds a simple labeled menu item on menu. The items used in a
menu must belong to the MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on the menu
bar. It inherits the MenuItem class.
import java.awt.*;
import java.awt.event.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("File");
Output:
Java AWT PopupMenu
import java.awt.*;
import java.awt.event.*;
class PopupMenuExample
{
PopupMenuExample(){
final Frame f= new Frame("PopupMenu Example");
final PopupMenu popupmenu = new PopupMenu("Edit");
MenuItem cut = new MenuItem("Cut");
cut.setActionCommand("Cut");
MenuItem copy = new MenuItem("Copy");
copy.setActionCommand("Copy");
MenuItem paste = new MenuItem("Paste");
paste.setActionCommand("Paste");
popupmenu.add(cut);
popupmenu.add(copy);
popupmenu.add(paste);
f.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
popupmenu.show(f , e.getX(), e.getY());
}
});
f.add(popupmenu);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[])
{
new PopupMenuExample();
}
}
Output:
APPLET
Applet Definition:
• Applets are small Java applications that can be accessed on an Internet server, transported over Internet,
and can be automatically installed and run as a part of a web document.
• After a user receives an applet, the applet can produce a graphical user interface. It has limited access to
resources so that it can run complex computations without introducing the risk of viruses or breaching
data integrity.
• Any applet in Java is a class that extends the java.applet.Applet class.
• An Applet class does not have any main() method. It is viewed using JVM. The JVM can use either a
plug-in of the Web browser or a separate runtime environment to run an applet application.
• JVM creates an instance of the applet class and invokes init() method to initialize an Applet.
An applet is a Java program designed to be included in an HTML Web document. You can write your Java
applet and include it in an HTML page. When you use a Java-enabled browser to view an HTML page that
contains an applet, the applet's code is transferred to your system and is run by the browser's Java virtual
machine.
The HTML document contains tags, which specify the name of the Java applet and its Uniform Resource
Locator (URL). The URL is the location at which the applet bytecodes reside on the Internet. When an HTML
document containing a Java applet tag is displayed, a Java-enabled Web browser downloads the Javabytecodes
from the Internet and uses the Java virtual machine to process the code from within the Web document. These
Java applets are what enable Web pages to contain animated graphics or interactive content.
Difference between Applet and Application in Java:
The Applets are used to provide interactive features to web applications that cannot be provided by HTML
alone.
They can capture mouse input and also have controls like buttons or check boxes. In response to
user actions,
an applet can change the provided graphic content.
Advantages of Applets
Applet class
Applet class provides all necessary support for applet execution, such as initializing and
destroying of applet.It also provide methods that load and display images and methods that
load and play audio clips
Most applets override these four methods. These four methods forms Applet lifecycle.
• init() : init() is the first method to be called. This is where variable are initialized.
This method iscalled only once during the runtime of applet.
• start() : start() method is called after init(). This method is called to restart an applet
after it has beenstopped.
• stop() : stop() method is called to suspend thread that does not need to run when applet is
not visible.
• destroy() : destroy() method is called when your applet needs to be removed
completely frommemory.
Graphics class:
Graphics class is in java.awt package.
Methods:
void drawLine(int startX, int startY, int endX, int endY)
void drawRect(int top, int left, int width, int height)
void fillRect(int top, int left, int width, int height)
void drawRoundRect(int top, int left, int width, int height, int xDiam, int yDiam)
void fillRoundRect(int top, int left, int width, int height, int xDiam, int yDiam)
void drawOval(int top, int left, int width, int height)
void fillOval(int top, int left, int width, int height)
void drawArc(int top, int left, int width, int height, int startAngle, int sweepAngle)
void fillArc(int top, int left, int width, int height, int startAngle, int sweepAngle)
void drawPolygon(int x[ ], int y[ ], int numPoints)
void setColor(Color newColor)
void fillPolygon(int x[ ], int y[ ], int numPoints)
Color getColor( )
JDBC Connectivity
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query
with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to
connect with the database. There are four types of JDBC drivers:
We can use JDBC API to access tabular data stored in any relational database. By the help
of JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.
The current version of JDBC is 4.3. It is the stable release since 21st September, 2017.
It is based on the X/Open SQL Call Level Interface. The java.sql package
contains classes and interfaces for JDBC API. A list of popular interfaces of JDBC
API are given below:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface
o DriverManager class
o Blob class
o Clob class
o Types class
Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC
drivers (written in Java language).
We can use JDBC API to handle database using Java program and can perform the following
activities:
JDBC Driver is a software component that enables java application to interact with the database.
There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC function
calls.
o The ODBC driver needs to be installed on the client machine.
Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into
native calls of the database API. It is not written entirely in java.
Advantage:
o performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
o No client side library is required because of application server that can perform many tasks
like auditing, load balancing, logging etc.
Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known
as thin driver. It is fully written in Java language.
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.
Disadvantage:
o Drivers depend on the Database.
1. Class.forName("oracle.jdbc.driver.OracleDriver");
To connect Java application with the MySQL database, we need to follow 5 following steps.
In this example we are using MySql as the database. So we need to know following informations
for the mysql database:
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address, 3306
is the port number and sonoo is the database name. We may use any database, in such case,
we need to replace the sonoo with our database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql database.
In this example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to create database
first.
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
The above example will fetch all the records of emp table.
To connect java application with the mysql database, mysqlconnector.jar file is required to be
loaded.
Go to environment variable then click on new tab. In variable name write classpath and in variable
value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.; as
C:\folder\mysql-connector-java-5.0.8-bin.jar;.;