Java Unit 4&5
Java Unit 4&5
Fundamentals
An applet is a special kind of Java program that runs in a Java enabled browser. This is the first Java
program that can run over the network using the browser. Applet is typically embedded inside a web
page and runs in the browser.
In other words, we can say that Applets are small Java applications that can be accessed on an Internet
server, transported over Internet, and can be automatically installed and run as apart 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.
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.
Java Applet is deprecated since Java 9. It means Applet API is no longer considered important.
1. Applet is initialized.
2. Applet is started
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
import [Link].*;
import [Link].*;
public class Simple extends Applet
{
public void paint(Graphics g)
{
[Link]("A simple Applet", 20, 20);
}
}
Every Applet application must import two packages - [Link] and [Link].
[Link].* imports the Abstract Window Toolkit (AWT) classes. Applets interact with the user
(either directly or indirectly) through the AWT. The AWT contains support for a window-based,
graphical user interface. [Link].* imports the applet package, which contains the class
Applet. Every applet that we create must be a subclass of Applet class.
The class in the program must be declared as public, because it will be accessed by code that is outside
the [Link] Applet application must declare a paint() method. This method is defined by AWT
class and must be overridden by the applet. The paint() method is called each time when an applet
needs to redisplay its output. Another important thing to notice about applet application is that, execution
of an applet does not begin at main() method. In fact an applet application does not have
any main() method.
Advantages of Applets
1. It takes very less response time as it works on the client side.
2. It can be run on any browser which has JVM running in it.
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.
Applet Skeleton
import [Link].*;
import [Link].*;
public class AppletTest extends Applet
{
public void init() { //initialization }
public void start () { //start or resume execution }
public void stop() { //suspend execution }
public void destroy() { //perform shutdown activity }
public void paint (Graphics g) { //display the content of window }
}
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 is
called 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
been stopped.
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 wer applet needs to be removed completely from
memory.
Note: The stop() method is always called before destroy() method.
Example
import [Link].*;
import [Link].*;
public class MyApplet extends Applet
{
int height, width;
public void init()
{
height = getSize().height;
width = getSize().width;
setName("MyApplet");
}
public void paint(Graphics g)
{
[Link](10, 30, 120, 120, 2, 3);
} }
Parameter in Applet
User-define Parameter can be applied in applet using <PARAM…> tags. Each <PARAM…> tag has a
name and value attribute.
Example:
name = color
Value = red
Syntax:
<PARAM name = ……… Value = “………” >
In an applet code, applet can refer to a parameter by its name and then find its value.
The two most important thing to handle and set up the parameter is the <PARAM> tag in the HTML
document and an applet code to parse this parameter.
init() method is used to get hold of the parameters which is defined in the <PARAM> tags. And
getParameter() method is used for getting the [Link] Applet, Parameters are passed
on applet when it is loaded.
[Link]
import [Link].*;
import [Link].*;
public class param extends Applet
{
String str;
public void init()
{
str=getParameter("pname");
if (str == null)
str = "Hello " + str;
}
public void paint(Graphics g)
{
[Link](str, 200, 200);
}
}
[Link]
<html>
<applet code=[Link] height=300
width=300>
<param Name="pname" value="Welcome ">
</applet>
</html>
An Applet program is compiled in the same way as we have been compiling wer console programs.
However there are two ways to run an applet.
Executing the Applet within Java-compatible web browser.
Using an Applet viewer, such as the standard tool, applet viewer. An applet viewer executes wer
applet in a window
For executing an Applet in an web browser, create short HTML file in the same directory.
Inside body tag of the file, include the following code. (applet tag loads the Applet class)
< applet code = "MyApplet" width=400 height=400 > < /applet >
f:/>appletviewer [Link]
Graphics in Applet
All graphics are drawn relative to a window. This can be the main window of an applet, a child window
of an applet, or a stand-alone application window. The origin of each window is at the top-left
Coordinates 0,0. Coordinates are specified in pixels. All output to a window takes place through a
graphics context. A graphics context is encapsulated by the Graphics class and is obtained in two ways:
1. It is passed to an applet when one of its various methods, such as paint() or update(), is called.
2. It is returned by the getGraphics( ) method of Component.
The Graphics class defines a number of drawing functions. Each shape can be drawn edge-only or filled.
Objects are drawn and filled in the currently selected graphics color, which is black by default. When a
graphics object is drawn that exceeds the dimensions of the window, the output is automatically clipped.
Sr
No. Methods Description
1 public abstract void drawString(String str, int x, int y) Used to draw specified string.
Example
Event Handling
We perform event handling in Swing and AWT and we can also do it in Applets.
As we know, Graphical Programming Interfaces (GUIs) contain the components of the user interface. The
GUI components are responsible to generate events based on user interactions like clicking the mouse or
a key and so on. When an applet is designed, these events are captured and the appropriate actions are
performed in response to each of those events provided.
For handling events, we need event handlers, that must be available in Java. The procedure to be
followed when an event is generated is:
1. First, we must find the type of event that took place.
2. Now, find the component that generated the event.
3. Finally, we need the appropriate code that handles the event.
Button event handling
It is the most common event generating components in user interfaces. When we click on a button, an
action is generated. In fact, the term action is used in button event handling.
Properties
Example
Reuse the graphics classes provided in JDK for constructing wer own Graphical User Interface
(GUI) applications. Writing wer own graphics classes (and re-inventing the wheels) is mission
impossible! These graphics classes, developed by expert programmers, are highly complex and involve
many advanced design patterns. However, re-using them are not so difficult, if we follow the API
documentation, samples and templates provided.
There are current three sets of Java APIs for graphics programming:
1. AWT API was introduced in JDK 1.0. Most of the AWT UI components have become obsolete
and should be replaced by newer Swing UI components.
2. Swing API, a much more comprehensive set of graphics libraries that enhances the AWT,
was introduced as part of Java Foundation Classes (JFC) after the release of JDK 1.1. JFC
consists of Swing, Java2D, Accessibility, Internationalization, and Pluggable Look-and-
Feel Support APIs. JFC has been integrated into core Java since JDK 1.2.
3. The latest JavaFX, which was integrated into JDK 8, was meant to replace Swing. JavaFX was
moved out from the JDK in JDK 11, but still available as a separate module.
AWT Packages
AWT is huge! It consists of 12 packages of 370 classes (Swing is even bigger, with 18 packages of
737 classes as of JDK 8). Fortunately, only 2 packages - [Link] and [Link] - are
commonly-used.
The hierarchy of Java AWT classes are given below, all the classes are available in [Link] 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.
Container
Container is a component in AWT that contains another component like button, text field, tables
etc. Container is a subclass of component class. Container class keeps track of components that are
added to another component.
Panel
Panel class is a concrete subclass of Container. Panel does not contain title bar, menu bar or border. It is
container that is used for holding components.
Window class
Window class creates a top level window. Window does not have borders and menubar.
Frame
Frame is a subclass of Window and have resizing canvas. It is a container that contain several different
components like button, title bar, textfield, label etc. In Java, most of the AWT applications are created
using Frame window. Frame class has two different constructors,
Creating a Frame
There are two ways to create a Frame. They are,
By Instantiating Frame class
By extending Frame class
Creating Frame Window by Instantiating Frame class
import [Link].*;
public class Testawt
{
Testawt()
{
Frame fm=new Frame(); //Creating a frame
//Creating a label
Label lb = new Label("welcome to java graphics");
[Link](lb); //adding label to the frame
[Link](300, 300); //setting frame size.
[Link](true); //set frame visibilty true
}
public static void main(String args[])
{
Testawt ta = new Testawt();
}
}
While creating a frame (either by instantiating or extending Frame class), Following two attributes
are must for visibility of the frame:
When we create other components like Buttons, TextFields, etc. Then we need to add it to the frame by
using the method - add(Component's Object);
We can add the following method also for resizing the frame - setResizable(true);
Dialog Boxes
The main function of a dialog box is for an application or website to retrieve some input from
the user. That input can be an acknowledgment that they have read a message or something
they enter into a text area.
A dialog box immediately captures a user’s attention. It’s a perfect tool for collecting or
displaying important information.
Java is a diverse language that provides several classes to create dialog boxes. These classes include
JOptionPane, JDialog, and JFrame.
Although JOptionPane provides standard dialog boxes, it has many options allowing you to tweak its
behavior. For example, the message dialog can take one of several types. The one above is an example
of an INFORMATION_MESSAGE, which is the default. The other message types are:
ERROR_MESSAGE
WARNING_MESSAGE
QUESTION_MESSAGE
PLAIN_MESSAGE
Example
ERROR_MESSAGE
[Link](frame, "This is a JOptionPane error message window.",
"Error", JOptionPane.ERROR_MESSAGE);
Layout Managers
A container has a so-called layout manager to arrange its components. The layout managers
provide a level of abstraction to map your user interface on all windowing systems, so that the
layout can be platform-independent.
AWT provides the following layout managers (in package [Link]):
FlowLayout, GridLawet, BorderLayout, GridBagLayout, BoxLayout, CardLayout, and others.
1. Construct an instance of the chosen layout object, via new and constructor, e.g., new
FlowLayout())
2. Invoke the setLayout() method of the Container, with the layout object created as the argument;
3. Place the GUI components into the Container using the add() method in the correct order; or into
the correct zones.
For example,
// Allocate a Panel (container)
Panel pnl = new Panel();
// Allocate a new Layout object. The Panel container sets to this layout.
[Link](new FlowLayout());
// The Panel container adds components in the proper order.
[Link](new JLabel("One"));
[Link](new JLabel("Two"));
[Link](new JLabel("Three"));
......
import [Link].*;
import [Link].*;
// An AWT GUI program inherits the top-level container
[Link]
public class AWTFlowLayoutDemo extends Frame {
private Button btn1, btn2, btn3, btn4, btn5, btn6;
// Constructor to setup GUI components and event
//handlers
public AWTFlowLayoutDemo () {
setLayout(new FlowLayout());
// "super" Frame sets layout to FlowLayout, which
//arranges the components
// from left-to-right, and flow from top-to-bottom.
btn1 = new Button("Button 1"); add(btn1);
btn2 = new Button("This is Button 2"); add(btn2);
btn3 = new Button("3"); add(btn3);
btn4 = new Button("Another Button 4"); add(btn4);
btn5 = new Button("Button 5"); add(btn5);
btn6 = new Button("One More Button 6"); add(btn6);
// "super" Frame sets title
setTitle("FlowLayout Demo"); setSize(280, 150);
setVisible(true); }
public static void main(String[] args) {
new AWTFlowLayoutDemo(); }}
AWT provides many ready-made and reusable GUI components in package [Link]. The
frequently-used are: Button, TextField, Label, Checkbox, CheckboxGroup (radio buttons), List,
and Choice, as illustrated below.
A [Link] provides a descriptive text string. Take note that [Link]() prints to the
system console, NOT to the graphics screen. You could use a Label to label another component (such as
text field) to provide a text description.
Constructors
// Construct a Label with the given text String, of the text alignment
public Label(String strLabel); // Construct a Label with the given text String
The first constructor constructs a Label object with the given text string in the given
alignment. Note that three static constants [Link], [Link], and [Link] are
defined in the class for we to specify the alignment (rather than asking you to memorize arbitrary integer
values).
The second constructor constructs a Label object with the given text string in default of left-
aligned.
The third constructor constructs a Label object with an initially empty string. You could set the
label text via the setText() method later.
Public Methods
// Examples
public String getText();
public void setText(String strLabel);
public int getAlignment();
public void setAlignment(int alignment); // [Link], [Link], [Link]
The getText() and setText() methods can be used to read and modify the Label's text. Similarly, the
getAlignment() and setAlignment() methods can be used to retrieve and modify the alignment of the
text.
Example
A [Link] is a GUI component that triggers a certain programmed action upon clicking.
Constructors
The Button class has two constructors. The first constructor creates a Button object with the given
label painted over the button. The second constructor creates a Button object with no label.
Public Methods
public void setLabel(String btnLabel); // Set the label of this Button instance
The getLabel() and setLabel() methods can be used to read the current label and modify the label of a
button, respectively.
Event
Clicking a button fires a so-called ActionEvent and triggers a certain programmed action. I will explain
event-handling later.
Example
Constructors
Public Methods
Event
Hitting the "ENTER" key on a TextField fires a ActionEvent, and triggers a certain programmed action.
Example
TextField tfInput = new TextField(30); // Declare and allocate an TextField instance
called tfInput
// Read an int from TextField "tfInput", square it, and display on "tfResult".
// getText() returns a String, need to convert to int
int number = [Link]([Link]());
number *= number;
[Link](number + "");
Swing Components
Java Swing is a GUI toolkit and a part of JFC (Java Foundation Class) helpful in developing
window-based applications. Java Swing is lightweight and platform-independent that
contains various components and container classes. Furthermore, the Java swing library is built on
the top of the AWT(Abstract Window Toolkit), an API completely written in Java. In every
application, users can find an interactive and user-friendly interface that gives them the freedom to use
the app.
In Java Swing, there are several components like a scroll bar, button, text field, text area,
checkbox, radio button, etc. These components jointly form a GUI that offers a rich set of
functionalities and allows high-level customization.
A component is independent visual control, and Java Swing Framework contains a large set of these
components, providing rich functionalities and allowing high customization. They all are derived from
JComponent class. All these components are lightweight components. This class offers some standard
functionality like pluggable look and feel, support for accessibility, drag and drop, layout, etc.
A container holds a group of components. It delivers a space where a component can be managed and
displayed. Containers are of two types:
It is a general-purpose container.
Lightweight
Containers We can use it to organize related components
together.
Example: JPanel
JButton
We use JButton class to create a push button on the UI. The button can include some display text or
images. It yields an event when clicked and double-clicked. We can implement a JButton in the
application by calling one of its constructors.
Syntax:
JButton okBtn = new JButton(“Click”); This constructor returns a button with the text Click on it.
JButton homeBtn = new JButton(carIcon); Returns a button with a car Icon on it.
JButton homeBtn2 = new JButton(carIcon, “Car”); Returns a button with the car icon and text
as Car.
JLabel
We use JLabel class to render a read-only text label or images on the UI. It does not generate any event.
Syntax:
JLabel textLabel = new JLabel(“This is 1st L...”);
Display:
JTextField
The JTextField renders an editable single-line text box. Users can input non-formatted text in the box. We
can initialize the text field by calling its constructor and passing an optional integer parameter. This
parameter sets the box width measured by the number of columns. Also, it does not limit the number of
characters that can be input into the box.
Syntax:
JCheckBox
The JCheckBox renders a check-box with a label. The check-box has two states, i.e., on and off. On
selecting, the state is set to "on," and a small tick is displayed inside the box.
Syntax:
CheckBox chkBox = new JCheckBox(“Java Swing”, true);
It returns a checkbox with the label Pepperoni pizza. Notice the second parameter in the constructor. It is
a boolean value that denotes the default state of the check-box. True means the check-box defaults to
the "on" state.
Display:
JRadioButton
A radio button is a group of related buttons from which we can select only one. We use JRadioButton
class to create a radio button in Frames and render a group of radio buttons in the UI. Users can select
one choice from the group.
Syntax:
JRadioButton jrb = new JRadioButton("Easy");
Display:
JComboBox
The combo box is a combination of text fields and a drop-down list. We use JComboBox component to
create a combo box in Swing.
Syntax:
JComboBox jcb = new JComboBox(name);
Display:
JTextArea
In Java, the Swing toolkit contains a JTextArea Class. It is under package [Link] class. It
is used for displaying multiple-line text.
Declaration:
public class JTextArea extends JTextComponent
Syntax:
Display:
AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
}
public static void main(String args[])
{
MyLoginWindow ml=new MyLoginWindow();
[Link](true);
[Link](400,400);
[Link]("my login window");
}
}
UNIT – V : GUI Part II and Java Database Connectivity Event handling – AWT components –
AWT graphics classes – Swing controls – application using Swing and AWT; Java Database Connectivity:
types of drivers – JDBC architecture – JDBC classes & interfaces – steps in JDBC applications – creating a
new Database and table with JDBC.
AWT components
AWT Components
1. 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 [Link] and is responsible for keeping a track of components being
added. There are four types of containers provided by AWT in Java.
Types of Containers
1. Window: It is an instance of the Window class having neither border nor title. It is used for
creating a top-level window.
2. Frame: Frame is a subclass of Window and contains title, border and menu bars. It comes with
a resizing canvas and is the most widely used container for developing AWT applications. It is
capable of holding various components such as buttons, text fields, scrollbars, etc. You can
create a Java AWT Frame in two ways:
i. By Instantiating Frame class
ii. By extending Frame class
3. Dialog: Dialog class is also a subclass of Window and comes with the border as well as the title.
Dialog class’s instance always needs an associated Frame class instance to exist.
4. Panel: Panel is the concrete subclass of Container and doesn’t contain any title bar, menu bar or
border. Panel class is a generic container for holding the GUI components. You need the instance
of the Panel class in order to add the components.
2. Button
[Link] class is used to create a labeled button. GUI component that triggers a certain
programmed action upon clicking it. The Button class has two constructors:
3. Text Field
A [Link] class creates a single-line text box for users to enter texts. The TextField class has
three constructors which are:
//Construct a TextField instance with the given initial text string with the number
of columns.
public TextField(String initialText, int columns);
4. Label
The [Link] class provides a descriptive text string that is visible on GUI. An AWT Label object is a
component for placing text in a container. Label class has three constructors which are:
// Construct a Label with the given text String, of the text alignment
public Label(String strLabel, int alignment);
6. Choice
Choice class is used to represent a pop-up menu of choices. The selected choice is shown on the top of
the given menu.
7. Scroll Bar
The Scrollbar class object is used to add horizontal and vertical scrollbar in the GUI. It enables a user to
see the invisible number of rows and columns.
8. List
The object of List class represents a list of text items. Using the List class a user can choose either one
item or multiple items.
9. CheckBox
The Checkbox is a class is a graphical component that is used to create a checkbox. It has two state
options; true and false. At any point in time, it can have either of the two.
import [Link];
// import awt and its subclasses
import [Link].*;
// class extending applet
public class AWTDemo extends Applet {
// this method gets automatically called
public void init() {
Button button = new Button("Click Here to Submit"); // creating a button
[Link](button); // adding button to container
Checkbox checkbox = new Checkbox("My Checkbox"); // creating a checkbox
[Link](checkbox); //adding checkbox to container
CheckboxGroup checkboxgrp = new CheckboxGroup(); // creating checkbox group
[Link](new Checkbox("Check box Option 1", checkboxgrp, false));
[Link](new Checkbox("Check box Option 2", checkboxgrp, false));
[Link](new Checkbox("Check box Option 3", checkboxgrp, true));
// adding to container
Choice choice = new Choice(); // creating a choice
[Link]("Choice Option 1");
[Link]("Choice Option 2");
[Link]("Choice Option 3");
[Link](choice); //adding choice to container
Label label = new Label("Demo Label"); // creating a label
[Link](label); //adding label to container
TextField textfield = new TextField("Demo TextField", 30); // creating a Textfield
[Link](textfield); // adding Textfield to container
}
}
//OUTPUT
AWT graphics classes
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.
A Graphics object encapsulates all state information required for the basic rendering
operations that Java supports. State information includes the following properties.
The Component object on which to draw.
A translation origin for rendering and clipping coordinates.
The current clip.
The current color.
The current font.
The current logical pixel operation function.
The current XOR alternation color
Class declaration
Class constructors
1 Graphics() ()
1. abstract void clearRect(int x, int y, int width, int height) - Clears the specified rectangle
by filling it with the background color of the current drawing surface.
2. abstract void clipRect(int x, int y, int width, int height) - Intersects the current clip with
the specified rectangle.
3. abstract void copyArea(int x, int y, int width, int height, int dx, int dy) - Copies an area
of the component by a distance specified by dx and dy.
4. abstract Graphics create() - Creates a new Graphics object that is a copy of this Graphics
object.
5. Graphics create(int x, int y, int width, int height) - Creates a new Graphics object based on
this Graphics object, but with a new translation and clip area.
6. abstract void dispose() - Disposes of this graphics context and releases any system resources
that it is using.
7. void draw3DRect(int x, int y, int width, int height, boolean raised) - Draws a 3-D
highlighted outline of the specified rectangle.
8. abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) -
Draws the outline of a circular or elliptical arc covering the specified rectangle.
9. void drawBytes(byte[] data, int offset, int length, int x, int y) - Draws the text given by
the specified byte array, using this graphics context's current font and color.
10. void drawChars(char[] data, int offset, int length, int x, int y) - Draws the text given by
the specified character array, using this graphics context's current font and color.
11. abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver
observer) - Draws as much of the specified image as is currently available.
12. abstract boolean drawImage(Image img, int x, int y, ImageObserver observer) -
Draws as much of the specified image as is currently available.
13. abstract boolean drawImage(Image img, int x, int y, int width, int height, Color
bgcolor, ImageObserver observer) - Draws as much of the specified image as has already
been scaled to fit inside the specified rectangle.
14. abstract boolean drawImage(Image img, int x, int y, int width, int height,
ImageObserver observer) - 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.
16. abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int
sy1, int sx2, int sy2, 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.
17. abstract void drawLine(int x1, int y1, int x2, int y2) - Draws a line, using the current color,
between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system.
18. abstract void drawOval(int x, int y, int width, int height) - Draws the outline of an oval.
19. abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) - Draws a closed
polygon defined by arrays of x and y coordinates.
20. void drawPolygon(Polygon p) - Draws the outline of a polygon defined by the specified
Polygon object.
21. abstract void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) - Draws a sequence
of connected lines defined by arrays of x and y coordinates.
22. void drawRect(int x, int y, int width, int height) - Draws the outline of the specified
rectangle.
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. abstract void drawString(AttributedCharacterIterator iterator, int x, int y) - Renders
the text of the specified iterator applying its attributes in accordance with the specification of the
TextAttribute class.
25. abstract void drawString(String str, int x, int y) - Draws the text given by the specified
string, using this graphics context's current font and color.
26. void fill3DRect(int x, int y, int width, int height, boolean raised) - Paints a 3-D
highlighted rectangle filled with the current color.
27. abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) -
Fills a circular or elliptical arc covering the specified rectangle.
28. abstract void fillOval(int x, int y, int width, int height) - Fills an oval bounded by the
specified rectangle with the current color.
29. abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) - Fills a closed polygon
defined by arrays of x and y coordinates.
30. void fillPolygon(Polygon p) - Fills the polygon defined by the specified Polygon object with
the graphics context's current color.
31. abstract void fillRect(int x, int y, int width, int height) - Fills the specified rectangle.
32. abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int
arcHeight) - Fills the specified rounded corner rectangle with the current color.
33. void finalize() - Disposes of this graphics context once it is no longer referenced.
34. abstract Shape getClip() - Gets the current clipping area.
35. abstract Rectangle getClipBounds() - Returns the bounding rectangle of the current clipping
area.
36. Rectangle getClipBounds(Rectangle r) - Returns the bounding rectangle of the current
clipping area.
37. Rectangle getClipRect() - Deprecated. As of JDK version 1.1, replaced by getClipBounds().
38. abstract Color getColor() - Gets this graphics context's current color.
39. abstract Font getFont() - Gets the current font.
40. FontMetrics getFontMetrics() - Gets the font metrics of the current font.
41. abstract FontMetrics getFontMetrics(Font f) - Gets the font metrics for the specified font.
42. boolean hitClip(int x, int y, int width, int height) - Returns true if the specified rectangular
area might intersect the current clipping area.
43. abstract void setClip(int x, int y, int width, int height) - Sets the current clip to the
rectangle specified by the given coordinates.
44. abstract void setClip(Shape clip) - Sets the current clipping area to an arbitrary clip shape.
45. abstract void setColor(Color c) - Sets this graphics context's current color to the specified
color.
46. abstract void setFont(Font font) - Sets this graphics context's font to the specified font.
47. abstract void setPaintMode() - Sets the paint mode of this graphics context to overwrite the
destination with this graphics context's current color.
48. abstract void setXORMode(Color c1) - Sets the paint mode of this graphics context to
alternate between this graphics context's current color and the new specified color.
49. String toString() - Returns a String object representing this Graphics object's value.
50. abstract void translate(int x, int y) - Translates the origin of the graphics context to the
point (x, y) in the current coordinate system.
application using Swing and AWT
AWT
import [Link].*;
public class AwtApp extends Frame {
AwtApp(){
Label firstName = new Label("First Name");
[Link](20, 50, 80, 20);
add(firstName); add(lastName);
add(dob); add(firstNameTF);
add(lastNameTF); add(dobTF);
add(sbmt); add(reset);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
AwtApp awt = new AwtApp();
}
}
Swing
import [Link].*;
public class JComboBoxDemo
{
JFrame f;
JComboBoxDemo ()
{
f = new JFrame ("ComboBox Example");
String country[] ={ "Hyderabad", "Chennai", "Bengaluru",
"Mumbai", "Delhi" };
JComboBox cb = new JComboBox (country);
[Link] (50, 50, 90, 20);
[Link] (cb);
[Link] (null);
[Link] (400, 500);
[Link] (true);
}
public static void main (String[]args)
{
new JComboBoxDemo ();
}
}
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 [Link] package contains classes and interfaces for JDBC API.
A list of popular interfaces of JDBC API are given below:
Driver interface
Connection interface
Statement interface
PreparedStatement interface
CallableStatement interface
ResultSet interface
ResultSetMetaData interface
DatabaseMetaData interface
RowSet interface
DriverManager class
Blob class
Clob class
Types class
Use of JDBC
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:
Types of Drivers
DBC Driver is a software component that enables java application to interact with the database. There
are 4 types of JDBC drivers:
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge
driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin
driver.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use JDBC
drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.
Advantages:
easy to use.
can be easily connected to any database.
Disadvantages:
Performance degraded because JDBC method call is converted into the ODBC function calls.
The ODBC driver needs to be installed on the client machine.
2) 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:
performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
The Native driver needs to be installed on the each client machine.
The Vendor client library needs to be installed on client machine.
Advantage:
No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.
Disadvantages:
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:
Better performance than all other drivers.
No software is required at client side or server side.
Disadvantage:
Drivers depend on the Database.
JDBC architecture
Two-Tier Architecture
A Java applet or application communicates directly with the data source in the two-tier paradigm. This
necessitates the use of a JDBC driver that can interface with the data source in question. The user’s
commands are transmitted to the database or other data source, and the statements’ results are returned
to the user. The data source could be on another machine to which the user has a network connection. A
client/server configuration is one in which the user’s machine acts as the client and the system that
houses the data source acts as the server. An intranet, for example, can connect people within a
company, or the Internet can be used as the network.
Three-Tier Architecture
Commands are sent to a “middle tier” of services in the three-tier paradigm, which subsequently
transmits the commands to the data source. The data source interprets the commands and provides the
results to the middle tier, which ultimately passes them on to the user. The three-tier architecture
appeals to MIS directors because the intermediate tier allows them to maintain control over access and
the types of changes that can be made to company data. Another benefit is that it makes application
deployment easier. Finally, the three-tier architecture can bring performance benefits in many
circumstances.
The components of JDBC are listed below. These elements assist us in interacting with a database.
The following are the JDBC components:
1. JDBC Driver Manager: In a JDBC application, the Driver Manager loads database-specific
drivers. This driver manager makes a database connection. To handle the user request, it
additionally makes a database-specific call to the database.
3. JDBC-ODBC Bridge Drivers: They are used to link database drivers to the database. The JDBC
method calls are translated into ODBC method calls by the bridge. To access the ODBC (Open
Database Connectivity) characteristics, it uses the [Link] package, which includes the
native library.
4. JDBC API: Sun Microsystem has provided JDBC API, which allows you to write a Java program
that talks with any database without modifying the code. The JDBC API is implemented by the
JDBC Driver.
5. JDBC Test Suite: The JDBC Test Suite aids in the testing of JDBC Driver operations such as
insertion, deletion, and updating. It aids in determining whether or not the JDBC Drivers will run
the program. It ensures that the program will be run by JDBC Drivers with confidence and
conformity.
6. Database Server: This is the database server that the JDBC client wants to communicate with,
such as Oracle, MySQL, SQL Server, and so on.
7. Statement: To send SQL statements to the database, you use objects built using this interface.
In addition to performing stored procedures, certainly derived interfaces accept parameters.
8. RuleSet: These objects retain data retrieved from a database when you use Statement objects
to conduct a SQL query. It functions as an iterator, allowing you to cycle through the data it
contains.
9. SQL Exception: This class is responsible for any errors that occur in a database application.
It can read any database. The only condition for it to do so is that all of the drivers be properly
installed.
It pulls information from a database and converts it to XML.
It does not necessitate the conversion of the content.
Software maintenance is centralized with no client settings necessary. Because the driver is built
in Java, the JDBC URL or a DataSource object has all of the information required to establish a
connection.
It supports queries and stored procedures completely.
The JDBC API contains a DataSource object that can be used to identify and connect to a data
source. This improves the code’s portability and maintainability.
Both synchronous and asynchronous processing is supported.
The Java API and the JDBC API work together to make application development simple and cost-
effective.
Modules are supported.
Even if data is housed on various database management systems, businesses can continue to use
their installed databases and access information.
JDBC API is available in two packages [Link], core API and [Link] JDBC optional packages.
Following are the important classes and interfaces of JDBC.
Class/interface Description
DriverManager This class manages the JDBC drivers. You need to register your drivers to
[Link] provides methods such as registerDriver() and getConnection().
Driver This interface is the Base interface for every driver class i.e. If you want to
create a JDBC Driver of your own you need to implement this interface. If
you load a Driver class (implementation of this interface), it will create an
instance of itself and register with the driver manager.
Statement This interface represents a static SQL statement. Using the Statement object
and its methods, you can execute an SQL statement and get the results of
[Link] provides methods such as execute(), executeBatch(), executeUpdate()
Class/interface Description
CallableStatement Using an object of this interface you can execute the stored procedures. This
returns single or multiple results. It will accept input parameters too. You can
create a CallableStatement using the prepareCall() method of the Connection
[Link] like Prepared statement, this will also provide setXXX() and
getXXX() methods to pass the input parameters and to get the output
parameters of the procedures.
Connection This interface represents the connection with a specific database. SQL
statements are executed in the context of a [Link] interface
provides methods such as close(), commit(), rollback(), createStatement(),
prepareCall(), prepareStatement(), setAutoCommit() setSavepoint() etc.
ResultSet This interface represents the database result set, a table which is generated
by executing statements. This interface provides getter and update methods
to retrieve and update its contents respectively.
ResultSetMetaData This interface is used to get the information about the result set such as,
number of columns, name of the column, data type of the column, schema of
the result set, table name, etcIt provides methods such as
getColumnCount(), getColumnName(), getColumnType(), getTableName(),
getSchemaName() etc.
There are 5 steps to connect any java application with the database using JDBC. These steps are as
follows:
Register the Driver class
Create connection
Create statement
Execute queries
Close connection
The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.
Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's Jar in the
classpath, and then JDBC driver manager can detect and load the driver automatically.
[Link]("[Link]");
The getConnection() method of DriverManager class is used to establish connection with the
database.
throws SQLException
Connection
con=[Link]("jdbc:oracle:thin:@localhost:1521:xe","system","passw
ord");
The createStatement() method of Connection interface is used to create statement. The object
of statement is responsible to execute queries with the database.
Statement stmt=[Link]();
By closing connection object statement and ResultSet will be closed automatically. The close() method of
Connection interface is used to close the connection.
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:
Driver class: The driver class for the mysql database is [Link].
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 [Link].*;
class MysqlCon{
public static void main(String args[]){
try{
[Link]("[Link]");
Connection con=[Link](
"jdbc:mysql://localhost:3306/employee","root","root");
Statement stmt=[Link]();