Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
187 views

Java Programming Unit5 Notes PDF

The document discusses Swing GUI programming and event handling in Java. It introduces Swing as an improvement over AWT, describing how Swing components are lightweight and support pluggable look and feel. It also discusses the MVC architecture used in Swing and some key Swing concepts like components, containers, and the packages used. Finally, it provides a simple example Swing application to demonstrate these concepts.

Uploaded by

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

Java Programming Unit5 Notes PDF

The document discusses Swing GUI programming and event handling in Java. It introduces Swing as an improvement over AWT, describing how Swing components are lightweight and support pluggable look and feel. It also discusses the MVC architecture used in Swing and some key Swing concepts like components, containers, and the packages used. Finally, it provides a simple example Swing application to demonstrate these concepts.

Uploaded by

Vishnu Vardhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 110

20CSE108 JAVA PROGRAMMING

Prepared by
Mrs.M.Bommy,
AP/CSE
UNIT V
GUI PROGRAMMING AND EVENT HANDLING
 Swing – Introduction, limitations of AWT, MVC architecture,
components, containers, Event Handling- Handling mouse and
keyboard events, Exploring Swing- JApplet, JFrame and
JComponent, Icons and Labels, text fields, buttons – The
JButton class, Check boxes, Radio buttons, Combo boxes,
Tabbed Panes, Scroll Panes,Trees, and Tables.
 JDBC: Connecting to Database, querying a database and
processing the results, updating data with JDBC.
INTRODUCTION - AWT
 Java’s original GUI subsystem: the Abstract Window Toolkit.
 The AWT defines a basic set of controls, windows, and dialog boxes that support a
usable, but limited graphical interface.
 One reason for the limited nature of the AWT is that it translates its various visual
components into their corresponding, platform-specific equivalents, or peers.This
means that the look and feel of a component is defined by the platform, not by Java.
 Because the AWT components use native code resources, they are referred to as
heavyweight.
Limitations of AWT
 First, because of variations between operating systems, a component might look,
or even act, differently on different platforms.
 Second, the look and feel of each component was fixed (because it is defined by the
platform) and could not be (easily) changed.
 Third, the use of heavyweight components caused some frustrating restrictions.
For example, a heavyweight component was always opaque.
It became apparent that the limitations and restrictions present in the
AWT were sufficiently serious that a better approach was needed. The
solution was Swing.
SWING
 Introduced in 1997, Swing was included as part of the Java Foundation Classes
(JFC).
 It is used to create window-based applications.
 However, beginning with Java 1.2, Swing was fully integrated into Java.
 Although Swing eliminates a number of the limitations inherent in the AWT, Swing
does not replace it.
 Instead, Swing is built on the foundation of the AWT. This is why the AWT is still a
crucial part of Java.
 Swing also uses the same event handling mechanism as the AWT.
Two Key Swing Features
1. Swing Components Are Lightweight:
This means that they are written entirely in Java and do not map directly to
platform-specific peers. Thus, lightweight components are more efficient and more
flexible.
2. Swing Supports a Pluggable Look and Feel:
Swing component is rendered by Java code rather than by native peers, the
look and feel of a component is under the control of Swing.
 Advantage:
1. It becomes possible to change the way that a component is rendered without
affecting any of its other aspects.
2. It is possible to define a look and feel that is consistent across all platforms.
Difference between AWT and Swing
S.No. Java AWT Java Swing
1) AWT components are platform- Java swing components are platform-
dependent. independent.
2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable look Swing supports pluggable look and feel.
and feel.
4) AWT provides less components than Swing provides more powerful
Swing. components such as tables, lists, scrollpanes,
colorchooser, tabbedpane etc.
5) AWT doesn't follows MVC(Model View Swing follows MVC.
Controller) where model represents data,
view represents presentation and controller
acts as an interface between model and view.
MVC Architecture
 In general, a visual component is a composite of three distinct aspects:
• The way that the component looks when rendered on the screen
• The way that the component reacts to the user
• The state information associated with the component
 No matter what architecture is used to implement a component, it must implicitly
contain these three parts.
 Over the years, one component architecture has proven itself to be exceptionally
effective: Model-View-Controller, or MVC for short.
 The MVC architecture is successful because each piece of the design corresponds
to an aspect of a component.
 In MVC terminology,
Model: Corresponds to the state information associated with the component.
Example, in the case of a check box, the model contains a field that indicates if the
box is checked or unchecked.
View: Determines how the component is displayed on the screen, including any
aspects of the view that are affected by the current state of the model.
Controller: Determines how the component reacts to the user.
Example, when the user clicks a check box, the controller reacts by changing the
model to reflect the user’s choice (checked or unchecked).
What is MVC architecture in Java?
 Model designs based on MVC architecture follow the MVC design
pattern and they separate the application logic from the user interface when
designing software.
 As the name implies MVC pattern has three layers, which are:
• Model – Represents the business layer of the application
• View – Defines the presentation of the application
• Controller – Manages the flow of the application
 In Java Programming context, the Model consists of simple Java classes,
the View displays the data and the Controller consists of servlets. This
separation results in user requests being processed as follows:
The browser on the client sends a request for a page to the
controller present on the server
The controller performs the action of invoking the model, thereby,
retrieving the data it needs in response to the request
The controller then gives the retrieved data to the view
The view is rendered and sent back to the client for the browser to
display
Advantages of MVC Architecture
 MVC has the feature of scalability that in turn helps the growth of application.
 The components are easy to maintain because there is less dependency.
 A model can be reused by multiple views that provides reusability of code.
 The developers can work with the three layers (Model, View, and Controller)
simultaneously.
 Using MVC, the application becomes more understandable.
 Using MVC, each layer is maintained separately therefore we do not require to deal
with massive code.
 The extending and testing of application is easier.
Components and Containers
 A Swing GUI consists of two key items: components and containers.
 A component is an independent visual control, such as a push button or
slider.
 A container holds a group of components. Thus, a container is a special type
of component that is designed to hold other components.
 Furthermore, in order for a component to be displayed, it must be held
within a container. Thus, all Swing GUIs will have at least one container.
Components
 Swing components are basic building blocks of an application.
 A component can be defined as a control that can be represented visually and is
usually independent. It has got a specific functionality and is represented as an
individual class in Swing API.
 In general, Swing components are derived from the JComponent class.
 JComponent provides the functionality that is common to all components.
 JComponent supports the pluggable look and feel.
 All of Swing’s components are represented by classes defined within the package
javax.swing.
CLASS UNDER SWING COMPONENTS
Containers
 Containers are an integral part of SWING GUI components. A container provides
a space where a component can be located.
 One or more components form a group and this group can be placed in a
“Container”. A container provides a space in which we can display components and
also manage their spacing, layout, etc.
 Swing defines two types of containers.
 1. The first are top-level containers: JFrame, JApplet, JWindow, and JDialog.
These containers do not inherit JComponent. They do, however, inherit the
AWT classes Component and Container.
 2. The second type of containers supported by Swing are lightweight
containers. Lightweight containers do inherit JComponent. An example of a
lightweight container is JPanel
The Swing Packages
 Swing is a very large subsystem and makes use of many packages.
 The main package is javax.swing.
 This package must be imported into any program that uses Swing.
 It contains the classes that implement the basic Swing components, such as push
buttons, labels, and check boxes.
A Simple Swing Application
import javax.swing.*; // Create a text-based label.
class SwingDemo { JLabel jlab = new JLabel(" Swing means powerful
SwingDemo() { GUIs.");

// Create a new JFrame container. // Add the label to the content pane.
JFrame jfrm = new JFrame("A Simple Swing jfrm.add(jlab);
Application"); // Display the frame.
jfrm.setVisible(true);
// Give the frame an initial size. }
jfrm.setSize(275, 100); public static void main(String args[]) {
// Create the frame on the event dispatching
// Terminate the program when the user closes thread.
the application. SwingUtilities.invokeLater(new Runnable() {
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON public void run() {
_CLOSE); new SwingDemo();
}});
}}
Event Handling
 Event handling is fundamental to Java programming because it is used to create
event driven programs.
 Example:
• Applets
• GUI based windows application
• Web Application
 Event handling mechanism have been changed significantly between the original
version of Java (1.0) and all subsequent versions of Java, beginning with version
1.1.
 The modern approach to handling events is based on the delegation event model,
Event, Event Source, Event Listener
What is an Event?
Change in the state of an object is known as event i.e. event describes the
change in state of source. Events are generated as result of user interaction with the
graphical user interface components. For example, clicking on a button, moving
the mouse, entering a character through keyboard, selecting an item from list,
scrolling the page are the activities that causes an event to happen.
 Types of Event:
The events can be broadly classified into two categories:
1. Foreground Events - Those events which require the direct interaction of user.
They are generated as consequences of a person interacting with the graphical
components in Graphical User Interface. For example, clicking on a button,
moving the mouse, entering a character through keyboard, selecting an item
from list, scrolling the page etc.
2. Background Events - Those events that are not directly caused by interactions
with a user interface are known as background events. Operating system
interrupts, hardware or software failure, timer expires, an operation completion
are the example of background events.
 What is Event Handling?
Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs. This mechanism have the code which is known as
event handler that is executed when an event occurs.
The Delegation Event Model:
Java Uses the Delegation Event Model to handle the events. This model
defines standard and consistent mechanisms to generate and process events. Its
concept is quite simple: a source generates an event and sends it to one or more
listeners. The listener simply waits until it receives an event. Once an event is
received, the listener processes the event and then returns.
The Delegation Event Model has the following key participants namely:
1.Event Source
2. Event Listener
 Event Source:
A source is an object that generates an event. This occurs when the internal
state of that object changes in some way. Sources may generate more than one
type of event. A source must register listeners in order for the listeners to
receive notifications about a specific type of event.
 Event Listeners:
A listener is an object that is notified when an event occurs. It has two major
requirements. First, it must have been registered with one or more sources to
receive notifications about specific types of events. Second, it must implement
methods to receive and process these notifications.
Sources of Events
 Following table lists some of the user interface components that can generate the
events described in the previous section.
Event Listener Interfaces
 As explained, the delegation event model has two parts: sources and listeners.
 Listeners are created by implementing one or more of the interfaces defined by
the java.awt.event package.
 When an event occurs, the event source invokes the appropriate method
defined by the listener and provides an event object as its argument.
 Following Table lists several commonly used listener interfaces and provides a
brief description of the methods that they define.
Event Classes in Java:
 Writing event driven program is a two step process-
• Implement the appropriate interface in the listener so that it can receive the
type of event desired.
• Implement code to register and unregister (if necessary) the listener as a
recipient for the event notifications.
 The class AWTEvent, defined within the java.awt package, is a subclass of
EventObject.
 It is the superclass (either directly or indirectly) of all AWT-based events used by
the delegation event model.
Handling Mouse and Keyboard Events: Keyboard
Events:
The KeyEvent Class:
 A KeyEvent is generated when keyboard input occurs.
 There are three types of key events, which are identified by these integer constants:
1. KEY_PRESSED
2. KEY_RELEASED
3. KEY_TYPED.
The first two events are generated when any key is pressed or released. The
last event occurs only when a character is generated.
Class declaration:
 Following is the declaration for java.awt.event.KeyEvent class:
public class KeyEvent extends InputEvent
 KeyEvent is a subclass of InputEvent.
 Here is one of its constructors:
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
 There are many integer constants that are defined by KeyEvent. Some of them
are,

 The VK constants specify virtual key codes and are independent of any modifiers,
such as control, shift, or alt.
 The KeyEvent class defines several methods, but probably the most commonly used
ones are getKeyChar( ), which returns the character that was entered, and
getKeyCode( ), which returns the key code.
 Their general forms are shown here:
char getKeyChar( )
int getKeyCode( )
Handling Keyboard Events
Which listener interface needs to be implemented by Applet?
 KeyListener Interface
What are the methods defined by KeyListener Interface?
 keyPressed(KeyEvent e)
 keyReleased(KeyEvent e)
 keyTyped(KeyEvent e)
Example Program
// importing awt libraries // creating the text area
import java.awt.*; area = new TextArea();
import java.awt.event.*; // setting the location of text area
// class which inherits Frame class and implements KeyLi area.setBounds (20, 80, 300, 300);
stener interface // adding the KeyListener to the text area
public class KeyListenerExample extends Frame imp area.addKeyListener(this);
lements KeyListener { // adding the label and text area to the frame
// creating object of Label class and TextArea class add(l);
Label l; add(area);
TextArea area; // setting the size, layout and visibility of frame
// class constructor setSize (400, 400);
KeyListenerExample() { setLayout (null);
// creating the label setVisible (true);
l = new Label(); }
// setting the location of the label in frame
l.setBounds (20, 50, 100, 20);
// overriding the keyPressed() method of KeyListener in // main method
terface where we set the text of the label when key is pre public static void main(String[] args) {
ssed new KeyListenerExample();
public void keyPressed (KeyEvent e) { }
l.setText ("Key Pressed"); }
} OUTPUT:
// overriding the keyReleased() method of KeyListener i
nterface where we set the text of the label when key is re
leased
public void keyReleased (KeyEvent e) {
l.setText ("Key Released");
}
// overriding the keyTyped() method of KeyListener int
erface where we set the text of the label when a key is ty
ped
public void keyTyped (KeyEvent e) {
l.setText ("Key Typed");
}
Handling Mouse Events
 To handle mouse events, we must implement the MouseListener and the
MouseMotionListener interfaces.
 MouseListener and MouseMotionListener is an interface in java.awt.event package.
 Mouse events are of two types.
1. MouseListener handles the events when the mouse is not in motion.
2. MouseMotionListener handles the events when mouse is in motion.
MouseListener Interface
 There are five types of events that MouseListener can generate. There are five
abstract functions that represent these five events.
 The abstract functions are :
1. void mouseReleased(MouseEvent e) : Mouse key is released
2. void mouseClicked(MouseEvent e) : Mouse key is pressed/released
3. void mouseExited(MouseEvent e) : Mouse exited the component
4. void mouseEntered(MouseEvent e) : Mouse entered the component
5.void mousepressed(MouseEvent e) : Mouse key is pressed
MouseMotionListener Interface
 There are two types of events that MouseMotionListener can generate. There are
two abstract functions that represent these five events.
 The abstract functions are :
1. void mouseDragged(MouseEvent e) : Invoked when a mouse button
is pressed in the component and dragged. Events are passed until the user releases
the mouse button.
2. void mouseMoved(MouseEvent e) : invoked when the mouse cursor
is moved from one point to another within the component, without pressing any
mouse buttons.
Example 1: Program using Mouse Listener Interface
import java.awt.*; public void mouseClicked(MouseEvent e) {
import java.awt.event.*; l.setText("Mouse Clicked");
public class MouseListenerExample extends }
Frame implements MouseListener{ public void mouseEntered(MouseEvent e) {
Label l; l.setText("Mouse Entered");
MouseListenerExample(){ }
addMouseListener(this); public void mouseExited(MouseEvent e) {
l=new Label(); l.setText("Mouse Exited");
l.setBounds(20,50,100,20); }
add(l); public void mousePressed(MouseEvent e) {
setSize(300,300); l.setText("Mouse Pressed");
setLayout(null); }
setVisible(true); public void mouseReleased(MouseEvent e) {
} l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}

OUTPUT:
Example 2: Program using Mouse Listener Interface
import java.awt.*; public static void main(String[] args) {
import java.awt.event.*; new MouseListenerExample2();
public class MouseListenerExample2 extends Frame }
implements MouseListener{ }
MouseListenerExample2(){
addMouseListener(this); OUTPUT:
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
Example 3: Program using MouseMotionListener Interface
import java.awt.*; public static void main(String[] args) {
import java.awt.event.*; new MouseMotionListenerExample();
public class MouseMotionListenerExample extends Frame }
implements MouseMotionListener{ }
MouseMotionListenerExample(){
addMouseMotionListener(this); OUTPUT:

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) {}
Exploring Swing
Applet
 In computing, an applet is any small application that performs one specific task that runs
within the scope of a dedicated widget engine or a larger program, often as a plug-in.
 Applets are not stand-alone programs. Instead, they run within either a web browser or an
applet viewer
 Types of Applets:
1. Applets use the Abstract Window Toolkit (AWT) to provide the graphical
user interface (or use no GUI at all). This style of applet has been available since Java was
first created.
2. The second type of applets are those based on the Swing class JApplet,
which inherits Applet. Swing applets use the Swing classes to provide the GUI. Swing
offers a richer and often easier-to-use user interface than does the AWT. Thus, Swing-
based applets are now the most popular.
 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.
Applet Life Cycle
 As shown in the above diagram, the life cycle of an applet starts with init() method
and ends with destroy() method. Other life cycle methods are start(), stop() and
paint(). The methods to execute only once in the applet life cycle are init() and
destroy(). Other methods execute multiple times.
 Below is the description of each applet life cycle method:
 init(): The init() method is the first method to execute when the applet is
executed. Variable declaration and initialization operations are performed in this
method.
 start(): The start() method contains the actual code of the applet that should run.
The start() method executes immediately after the init() method. It also executes
whenever the applet is restored, maximized or moving from one tab to another tab
in the browser.
 stop(): The stop() method stops the execution of the applet. The stop() method
executes when the applet is minimized or when moving from one tab to another in the
browser.
 destroy(): The destroy() method executes when the applet window is closed or when
the tab containing the webpage is closed. stop() method executes just before when
destroy() method is invoked. The destroy() method removes the applet object from
memory.
 paint(): The paint() method is used to redraw the output on the applet display area.
The paint() method executes after the execution of start() method and whenever the
applet or browser is resized.
 The method execution sequence when an applet is executed is:
• init()
• start()
• paint()

 The method execution sequence when an applet is closed is:


• stop()
• destroy()
Applet HTML tag
 The <applet> tag embeds a Java applet (mini Java applications) on the page. An
applet is a program written in the Java programming language that can be included
in an HTML page, much in the same way an image is included in a page.
 Example:
<applet code = demo.class width = 400 height = 200>
</applet>
 Applet tag having three attribute
1. code – specifies name of the applet (.class file)
2. width – specifies width of the applet (in pixel )
3. height – specifies height of the applet ( in pixel )
Example:
HelloWorld.java public void paint(Graphics g)
import java.awt.*; {
import java.applet.*; g.drawString(msg,20,20);
public class HelloWorld extends Applet }
{ }
String msg="";

public void init()


{
msg="Hello";
}

public void start()


{
msg=msg+"World";
}
HelloWorld.html
<!DOCTYPE html>
<html>
<head>
<title>HTML applet Tag</title>
</head>
<body>
<applet code = “HelloWorld.class" width = "300" height = "200"></applet>
</body>
</html>
 To run an applet we require one of the following tools :
1. java enabled web browser
2. Java appletviewer
JApplet
 The JApplet class extends the Applet class.
 JApplet is generally in the form of Java bytecode that runs with the help of a Java virtual
machine (JVM) or Applet viewer from Sun Microsystems. It was first introduced in
1995.
 Swing-based applets are similar to AWT-based applets, but with an important difference:
1. A Swing applet extends JApplet rather than Applet. JApplet is derived from
Applet. Thus, JApplet includes all of the functionality found in Applet and adds support
for Swing.
2. JApplet is a top-level Swing container, which means that it is not derived from
JComponent. Because JApplet is a toplevel container, it includes the various. This means
that all components are added to JApplet’s content pane in the same way that
components are added to JFrame’s content pane.
 Swing applets use the same four life-cycle methods as Applet - init( ), start( ),
stop( ), and destroy( ).
 Painting is accomplished differently in Swing than it is in the AWT, and a Swing
applet will not normally override the paint( ) method.
 All interaction with components in a Swing applet must take place on the event
dispatching thread
 java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
javax.swing.JApplet
 All Implemented Interfaces:
ImageObserver, MenuContainer, Serializable, Accessible, RootPaneContainer
Example Program for JApplet
// A simple Swing-based applet private void makeGUI() {
import javax.swing.*; setLayout(new FlowLayout());
import java.awt.*; jbtnAlpha = new JButton("Alpha");
import java.awt.event.*; jbtnBeta = new JButton("Beta");
public class MySwingApplet extends JApplet { jbtnAlpha.addActionListener(new ActionListener() {
JButton jbtnAlpha; public void actionPerformed(ActionEvent le) {
JButton jbtnBeta; jlab.setText("Alpha was pressed.");
JLabel jlab; }
public void init() { });
try { jbtnBeta.addActionListener(new ActionListener() {
SwingUtilities.invokeAndWait(new Runnable () { public void actionPerformed(ActionEvent le) {
public void run() { jlab.setText("Beta was pressed.");
makeGUI(); // initialize the GUI }
} });
}); add(jbtnAlpha);
} catch(Exception exc) { add(jbtnBeta);
System.out.println("Can’t create because of "+ exc); jlab = new JLabel("Press a button.");
} add(jlab);
} }
}
 HTML CODE:
<!DOCTYPE html>
<html>
<head>
<title>HTML applet Tag</title>
</head>
<body>
<applet code = “MySwingApplet" width = "300" height = "200"></applet>
</body>
</html>
OUTPUT:
Difference between Japplet, JFrame and
JComponent
 JFrame and JApplet are top level containers. If we wish to create a desktop
application, we can use JFrame and if we plan to host our application in browser
we will use JApplet.
 JComponent is an abstract class for all Swing components and we can use it as the
base class for our new component.
JFrame
 JFrame is the top-level container that is commonly used for Swing
applications.
 The javax.swing.JFrame class is a type of container which inherits the
java.awt.Frame class. JFrame works like the main window where
components like labels, buttons, textfields are added to create a GUI.
 Unlike Frame, JFrame has the option to hide or close the window with the
help of setDefaultCloseOperation(int) method.
JFrame - Top-level containers
 JFrame, JApplet,JWindow, and JDialog.
 As the name implies, a top-level container must be at the top of a containment
hierarchy.
 A top-level container is not contained within any other container. Furthermore,
every containment hierarchy must begin with a top-level container.
 The one most commonly used for applications are JFrame and JApplet.
 Unlike Swing’s other components, the top-level containers are heavyweight.
Because they inherit AWT classes Component and Container.
 Whenever we create a top level container four sub-level containers are
automatically created:
 Glass pane (JGlass)
 Root pane (JRootPane)
 Layered pane (JLayeredPane)
 Content pane
 Glass pane: This is the first pane and is very close to the monitor’s screen. Any
components to be displayed in the foreground are attached to this glass pane. To reach
this glass pane we use getGlassPane() method of JFrame class, which return
Component class object.
 Root Pane: This pane is below the glass pane. Any components to be displayed in the
background are displayed in this frame. To go to the root pane, we can use
getRootPane() method of JFrame class, which returns JRootPane object.
 Layered pane: This pane is below the root pane. When we want to take several
components as a group, we attach them in the layered pane. We can reach this pane by
calling getLayeredPane() method of JFrame class which returns JLayeredPane class
object.
 Conent pane: This is bottom most of all, Individual components are attached to this
pane. To reach this pane, we can call getContentPane() method of JFrame class which
returns Container class object.
 Frame represents a window with a title bar and borders.
 Frame becomes the basis for creating the GUIs for an application because all the
components go into the frame.
 To create a frame, we have to create an object to JFrame class in swing as
JFrame jf=new JFrame(); // create a frame without title
JFrame jf=new JFrame(“title”); // create a frame with title
 To close the frame, use setDefaultCloseOperation() method of JFrame class
setDefaultCloseOperation(constant) where constant values are
Example Program for JFrame
import javax.swing.*;
class FrameDemo
{
public static void main(String arg[])
{
JFrame jf=new JFrame(“New Frame");
jf.setSize(200,200);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE );
}
}
JComponent
 The JComponent class is the base class of all Swing components except top-level
containers.
 Swing components whose names begin with "J" are descendants of the JComponent
class. For example, JButton, JScrollPane, JPanel, JTable etc. But, JFrame and JDialog
don't inherit JComponent class because they are the child of top-level containers.
 The JComponent class extends the Container class which itself extends Component.
The Container class has support for adding components to the container.
 To use a component that inherits from JComponent, you must place the component in
a containment hierarchy whose root is a top-level SWING container.
 Constructor: JComponent();
 The following are the JComponent class's methods to manipulate the appearance of the
component.
Example Program using JComponent
import java.awt.Color; frame.setSize(300,200);
import java.awt.Graphics; frame.setDefaultCloseOperation(JFrame.EXIT_ON_CL
import javax.swing.JComponent; OSE);
import javax.swing.JFrame; // add the JComponent to main frame
class MyJComponent extends JComponent { frame.add(com);
public void paint(Graphics g) { frame.setVisible(true);
g.setColor(Color.green); }
g.fillRect(30, 30, 100, 100); }
}
} OUTPUT:
public class JComponentExample {
public static void main(String[] arguments) {
MyJComponent com = new MyJComponent();
// create a basic JFrame
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JComponent Example
");
Icons and Labels
 JLabel:
Swing allows you to create labels that can contain text, images, or both.
 JLabel is Swing’s easiest-to-use component. It creates a label.
 JLabel can be used to display text and/or an icon. It is a passive component in that it does
not respond to user input.
 JLabel defines several constructors. Here are three of them:
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)
 Here, str and icon are the text and icon used for the label.
 The align argument specifies the horizontal alignment of the text and/or icon within the
dimensions of the label. It must be one of the following values: LEFT, RIGHT, CENTER,
LEADING, or TRAILING.
 Icon – is an interface
– The easiest way to obtain icon is to use ImageIcon class. ImageIcon implements Icon and
encapsulates an image. Thus, an object of type ImageIcon can be passed as an argument to the Icon
parameter of JLabel’s constructor.
There are several ways to provide the image, including reading it from a file or downloading it from a URL.
Here is the ImageIcon constructor used by the example in this section:
ImageIcon(String filename)
 It obtains the image in the file named filename.
 The icon and text associated with the label can be obtained by the following methods:
Icon getIcon( )
String getText( )
 The icon and text associated with a label can be set by these methods:
void setIcon(Icon icon)
void setText(String str)
 Here, icon and str are the icon and text, respectively. Therefore, using setText( ) it is possible to change
the text inside a label during program execution.
Example program:
import java.awt.event.*;
import java.awt.*; JPanel p = new JPanel();
import javax.swing.*;
class text extends JFrame { p.add(l);
static JFrame f; f.add(p);
static JLabel l; f.setSize(600, 500);
text() f.show();
{ }
} }
public static void main(String[] args)
{
f = new JFrame("label");
ImageIcon i = new ImageIcon("f:/image.png");
l = new JLabel("new image text ", i,
SwingConstants.HORIZONTAL);
Text fields
 JTextField is the simplest Swing text component. Most widely used text component.
 JTextField allows you to edit one line of text.
 It is derived from JTextComponent, which provides the basic functionality common to Swing text
components.
 JTextField uses the Document interface for its model.
 Three of JTextField’s constructors are shown here:
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
 Here, str is the string to be initially presented, and cols is the number of columns in the text field.
If no string is specified, the text field is initially empty. If the number of columns is not specified,
the text field is sized to fit the specified string.
 JTextField generates events in response to user interaction.
PROGRAM: f.setSize(400,400);
f.setLayout(null);
import javax.swing.*; f.setVisible(true);
classTextFieldExample }
{ }
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");

t1.setBounds(50,100, 200,30);
t2=new JTextField("AWTTutorial");
t2.setBounds(50,150, 200,30);
f.add(t1);
f.add(t2);
The Swing Buttons
 Swing defines four types of buttons: JButton, JToggleButton, JCheckBox, and
JRadioButton.
 All are subclasses of the AbstractButton class, which extends JComponent.
 Thus, all buttons share a set of common traits.
 AbstractButton contains many methods that allow you to control the behavior of
buttons.
Buttons – The JButton class
 The JButton class provides the functionality of a push button.
 JButton allows an icon, a string, or both to be associated with the push button.
 Three of its constructors are shown here:
JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)
Here, str and icon are the string and icon used for the button.
 When the button is pressed, an ActionEvent is generated. Using the ActionEvent object passed to the
actionPerformed( ) method of the registered ActionListener, you can obtain the action command string
associated with the button. By default, this is the string displayed inside the button.
 However, you can set the action command by calling setActionCommand( ) on the button. You can obtain the
action command by calling getActionCommand( ) on the event object.
 It is declared like this:
String getActionCommand( )
 The action command identifies the button. Thus, when using two or more buttons within the same
application, the action command gives you an easy way to determine which buttonwas pressed.
Radio buttons
 Radio buttons are a group of mutually exclusive buttons, in which only one button can be
selected at any one time.
 They are supported by the JRadioButton class, which extends JToggleButton.
 JRadioButton provides several constructors.The one of them is shown here:
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
 Here, s is the label for the button.
 Other constructors let you specify the initial selection state of the button and specify an
icon.
 In order for their mutually exclusive nature to be activated, radio buttons must be
configured into a group. Only one of the buttons in the group can be selected at any time.
 For example, if a user presses a radio button that is in a group, any previously selected
button in that group is automatically deselected.
 A button group is created by the ButtonGroup class. Its default constructor is invoked for
this purpose. Elements are then added to the button group via the following method:
void add(AbstractButton ab)
 Here, ab is a reference to the button to be added to the group.
 A JRadioButton generates action events, item events, and change events each time the
button selection changes.
 Most often, it is the action event that is handled, which means that you will normally
implement the ActionListener interface.
 The only method defined by ActionListener is actionPerformed( ).
 Inside this method, you can use a number of different ways to determine which button was
selected.
 First, you can check its action command by calling getActionCommand( ). By default, the
action command is the sameas the button label, but you can set the action command to
something else by calling setActionCommand( ) on the radio button.
 Second, you can call getSource( ) on the ActionEvent object and check that reference against
the buttons.
 Third, you can check each radio button to find out which one is currently selected by calling
isSelected( ) on each button.
 Finally, each button could use its own action event handler implemented as either an
anonymous inner class or a lambda expression.
Example program using Jbutton & Radio button
Program: add(rb1);add(rb2);add(b);
import javax.swing.*; setSize(300,300);
import java.awt.event.*; setLayout(null);
class RadioButtonExample extends JFrame implements setVisible(true);
ActionListener{ }
JRadioButton rb1,rb2; public void actionPerformed(ActionEvent e){
JButton b; if(rb1.isSelected()){
RadioButtonExample(){ JOptionPane.showMessageDialog(this,"You are Male.");
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30); }
rb2=new JRadioButton("Female"); if(rb2.isSelected()){
rb2.setBounds(100,100,100,30); JOptionPane.showMessageDialog(this,"You are Female.");
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2); }
b=new JButton("click"); }
b.setBounds(100,150,80,30); public static void main(String args[]){
b.addActionListener(this); new RadioButtonExample();
}}
Output:
Check Boxes
 The JCheckBox class provides the functionality of a check box. Its immediate superclass is
JToggleButton.
 JCheckBox defines several constructors.The one of the constructor is
JCheckBox(String str)
JCheckBox(Icon i)
JCheckBox(Icon i, boolean state)
JCheckBox(String str, boolean state)
JCheckBox(String str, Icon i)
JCheckBox(String str, Icon i, boolean state)
 It creates a check box that has the text specified by str as a label.
 Other constructors let you specify the initial selection state of the button and specify an icon.
 When the user selects or deselects a check box, an ItemEvent is generated. You can
obtain a reference to the JCheckBox that generated the event by calling getItem( )
on the ItemEvent passed to the itemStateChanged( ) method defined by
ItemListener.
 The getText( ) method gets the text for that check box and uses it to set the text
inside the text field.
 The easiest way to determine the selected state of a check box is to call
isSelected( ) on the JCheckBox instance.
Combo boxes
 Swing provides a combo box (a combination of a text field and a drop-down list) through
the JComboBox class.
 A combo box normally displays one entry, but it will also display a dropdown list that allows
a user to select a different entry.
 The JComboBox constructor:
JComboBox(E[ ] items)
 Here, items is an array that initializes the combo box.
 Two of JComboBox’s constructors are shown here:
 JComboBox( )
 JComboBox(Vector v)
 Here, v is a vector that initializes the combo box.
 JComboBox uses the ComboBoxModel. Mutable combo boxes (those whose entries can
be changed) use the MutableComboBoxModel.
 In addition to passing an array of items to be displayed in the drop-down list, items can
be dynamically added to the list of choices via the addItem( ) method, shown here:
void addItem(E obj)
 Here, obj is the object to be added to the combo box. This method must be used only
with mutable combo boxes.
 JComboBox generates an action event when the user selects an item from the list.
 JComboBox also generates an item event when the state of selection changes, which
occurs when an item is selected or deselected.
 Thus, changing a selection means that two item events will occur: one for the deselected
item and another for the selected item.
Scroll Panes
 A JscrollPane is a lightweight container that automatically handles the scrolling of another
component.
 It is used to make scrollable view of a component. When screen size is limited, we use a
scroll pane to display a large component or a component whose size can change
dynamically.
 The component being scrolled can be either an individual component, such as a table, or a
group of components contained within another lightweight container, such as a Jpanel.
 The viewable area of a scroll pane is called the viewport. It is a window in which the component
being scrolled is displayed. Thus, the viewport displays the visible portion of the component
being scrolled.The scroll bars scroll the component through the viewport.
 A scroll pane is a component that presents a rectangular area in which a component may be viewed. Horizontal
and/or vertical scroll bars may be provided if necessary.
 Scroll panes are implemented in Swing by the JScrollPane class, which extends JComponent. Some of its
constructors are :
JScrollPane(Component comp)
JScrollPane(int vsb, int hsb)
JScrollPane(Component comp, int vsb, int hsb)
 Here, comp is the component to be added to the scroll pane. vsb and hsb are int constants that define when vertical
and horizontal scroll bars for this scroll pane areshown.
 These constants are defined by the ScrollPaneConstants interface.
1. HORIZONTAL_SCROLLBAR_ALWAYS
2. HORIZONTAL_SCROLLBAR_AS_NEEDED
3. VERTICAL_SCROLLBAR_ALWAYS
4. VERTICAL_SCROLLBAR_AS_NEEDED
 Here are the steps to follow to use a scroll pane in an applet:
1. Create a JComponent object.
2. Create a JScrollPane object. (The arguments to the constructor specify thecomponent and the policies
for vertical and horizontal scroll bars.)
3. Add the scroll pane to the content pane of the applet.
Example program for JScrollpane
import java.awt.FlowLayout; JTextArea textArea = new JTextArea(20, 20);
import javax.swing.JFrame; JScrollPane scrollableTextArea = new JScrollPane(textArea);
import javax.swing.JScrollPane;
import javax.swing.JtextArea; scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.
HORIZONTAL_SCROLLBAR_ALWAYS);
public class JScrollPaneExample { scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VER
private static final long serialVersionUID = 1L; TICAL_SCROLLBAR_ALWAYS);

private static void createAndShowGUI() { frame.getContentPane().add(scrollableTextArea);


}
// Create and set up the window. public static void main(String[] args) {
final JFrame frame = new JFrame("Scroll Pane Example");

// Display the window. javax.swing.SwingUtilities.invokeLater(new Runnable() {


frame.setSize(500, 500);
frame.setVisible(true); public void run() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) createAndShowGUI();
; // set flow layout for the frame }
frame.getContentPane().setLayout(new FlowLayout()); }); } }
Tabbed Panes
 A tabbed pane is a component that appears as a group of folders in a file cabinet.
 Each folder has a title. When a user selects a folder, its contents become visible. Only one
of the folders may be selected at a time.
 Tabbed panes are commonly used for setting configuration options.
 Tabbed panes are encapsulated by the JTabbedPane class, which extends JComponent.
We will use its default constructor. Tabs are defined via the following method:
void addTab(String str, Component comp)
 Here, str is the title for the tab, and comp is the component that should be added to the tab.
Typically, a JPanel or a subclass of it is added.
 The general procedure to use a tabbed pane in an applet is outlined here:
1. Create a JTabbedPane object.
2. Call addTab( ) to add a tab to the pane. (The arguments to this method define the
title of the tab and the component it contains.)
3. Repeat step 2 for each tab.
4. Add the tabbed pane to the content pane of the applet.
Program – Tabbed Pane
import javax.swing.*; f.setSize(400,400);
public class TabbedPaneExample { f.setLayout(null);
JFrame f; f.setVisible(true);
}
TabbedPaneExample(){
public static void main(String[] args) {
f=new JFrame();
new TabbedPaneExample();
JTextArea ta=new JTextArea(200,200); }}
JPanel p1=new JPanel(); Output:
p1.add(ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
tp.setBounds(50,50,200,200);
tp.add("main",p1);
tp.add("visit",p2);
tp.add("help",p3);
f.add(tp);
Tables
 A table is a component that displays rows and columns of data.You can drag the cursor on column
boundaries to resize columns.You can also drag a column to a new position.
 Tables are implemented by the JTable class, which extends JComponent.
 One of its constructors is :
JTable(Object data[ ][ ], Object colHeads[ ])
 Here, data is a two-dimensional array of the information to be presented, and colHeads is a one-
dimensional array with the column headings.
 Here are the steps for using a table in an applet:
1. Create a JTable object.
2. Create a JScrollPane object. (The arguments to the constructor specify the table and
the policies for vertical and horizontal scroll bars.)
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane of the applet.
Trees
 A tree is a component that presents a hierarchical view of data.The user has the ability to expand or
collapse individual subtrees in this display. Trees are implemented in Swing by the JTree class.
 A sampling of its constructors is shown here:
JTree(Object obj [ ])
JTree(Vector<?> v)
JTree(TreeNode tn)
 In the first form, the tree is constructed from the elements in the array obj.The second form
constructs the tree from the elements of vector v. In the third form, the tree whose root node is
specified by tn specifies the tree.
 Although JTree is packaged in javax.swing, its support classes and interfaces are
packaged in javax.swing.tree. This is because the number of classes and interfaces
needed to support JTree is quite large.
 JTree relies on two models: TreeModel and TreeSelectionModel.
 A JTree generates a variety of events, but three relate specifically to trees:
TreeExpansionEvent, TreeSelectionEvent, and TreeModelEvent.
 TreeExpansionEvent events occur when a node is expanded or collapsed.
 A TreeSelectionEvent is generated when the user selects or deselects a node within the
tree.
 A TreeModelEvent is fired when the data or structure of the tree changes.
 The listeners for these events are TreeExpansionListener, TreeSelectionListener, and
TreeModelListener, respectively.
 The tree event classes and listener interfaces are packaged in javax.swing.event.
Program
import javax.swing.*; DefaultMutableTreeNode red=new DefaultMutableTreeNode("
import javax.swing.tree.DefaultMutableTreeNode; red");
public class TreeExample { DefaultMutableTreeNode blue=new DefaultMutableTreeNo
JFrame f; de("blue");
TreeExample(){ DefaultMutableTreeNode black=new DefaultMutableTreeNo
f=new JFrame(); de("black");
DefaultMutableTreeNode style=new DefaultMutableTreeNo DefaultMutableTreeNode green=new DefaultMutableTreeN
de("Style"); ode("green");
DefaultMutableTreeNode color=new DefaultMutableTreeNo color.add(red); color.add(blue); color.add(black); color.add(g
de("color"); reen);
DefaultMutableTreeNode font=new DefaultMutableTreeNo JTree jt=new JTree(style);
de("font"); f.add(jt);
style.add(color); f.setSize(200,200);
style.add(font); f.setVisible(true);
}
public static void main(String[] args) {
new TreeExample();
}}
 Output:
JDBC
What is JDBC?
 JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language, and a wide range of
databases.
 JDBC makes it possible to write a single database application that can run on different
platforms and interact with different Database Management Systems.
 The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.
 Making a connection to a database.
 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database.
 Viewing & Modifying the resulting records.
 Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows
for portable access to an underlying database. Java can be used to write different types of
executables, such as:
 Java Applications
 Java Applets
 Java Servlets
 Java ServerPages (JSPs)
 Enterprise JavaBeans (EJBs).

 All of these different executables are able to use a JDBC driver to access a database, and take
advantage of the stored data.
 Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used
for accessing and managing database, but the difference is that JDBC is designed specifically
for Java programs, whereas ODBC is not dependent upon any language.
JDBC Architecture
 The JDBC API supports both two-tier and three-tier processing models for database
access but in general, JDBC Architecture consists of two layers:
 JDBC API: This provides the application-to-JDBC Manager connection.
 JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

 The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
 The JDBC driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent drivers
connected to multiple heterogeneous databases.
 Following is the architectural diagram, which shows the location of the driver manager
with respect to the JDBC drivers and the Java application:
JDBC ─ ENVIRONMENT

 Install Java
 Install Database
MySQL DB
PostgreSQL DB
Oracle DB
Install Database Drivers
Set Database Credential
Create Database
JDBC Classes for DB Connection
 java.sql.Driver
 Unless creating custom JDBC implementation, never have to deal with it. It gives JDBC
a launching point for DB connectivity by responding to DriverManager
connection requests
 java.sql.DriverManager
 Maintains a list of Driver implementations and presents an application with one that
matches a requested URL.
 getConnection(url, uid, password)
 getDrivers(), registerDriver()
 java.sql.Connection
 Represents a single logical DB connection; used for sending SQL statements
JDBC – Making the Connection
 Register the Driver implementation of the DB. JDBC requires a Driver class
to register itself with DriverManager when it is instantiated.
 Explicitly call new to load the driver (needs to be hardcoded)
 Or, use Class.forName(“DriverClass”)
 Establish a connection with the DB
Connection c = DriverManager.getConnection(url, uid, password);
 DM searches the registered Drivers until it finds the match.
 The Driver class then establishes the connection, returns a connection object
to DM, which in turn returns it back.
Steps required for accessing a database using JDBC:
Program: JDBC Update Records
import java.sql.Connection; String sql = "UPDATE Registration " +
import java.sql.DriverManager; "SET age = 30 WHERE id in (100, 101)";
import java.sql.ResultSet; stmt.executeUpdate(sql);
import java.sql.SQLException; ResultSet rs = stmt.executeQuery(QUERY);
import java.sql.Statement; while(rs.next())
public class JDBCExample { //Display values
{ System.out.print("ID: " + rs.getInt("id"));
static final String DB_URL = System.out.print(", Age: " + rs.getInt("age"));
"jdbc:mysql://localhost//"; System.out.print(", First: " + rs.getString("first"));
static final String USER = "guest"; System.out.println(", Last: " + rs.getString("last"));
static final String PASS = "guest123"; }
static final String QUERY = "SELECT id, first, last, age rs.close();
FROM Registration"; }
public static void main(String[] args) catch (SQLException e)
{ // Open a connection {
try(Connection conn = e.printStackTrace();
DriverManager.getConnection(DB_URL, USER, PASS); }
Statement stmt = conn.createStatement(); ) }
{ }

You might also like