Unit 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 56

Java Swing

Swing is a Java Foundation Classes [JFC] library and an extension of the


Abstract Window Toolkit [AWT]. Swing offers much-improved functionality over
AWT, new components, expanded components features, and excellent event
handling with drag-and-drop support.

Swing has about four times the number of User Interface [UI] components as
AWT and is part of the standard Java distribution. By today’s application GUI
requirements, AWT is a limited implementation, not quite capable of providing
the components required for developing complex GUI’s required in modern
commercial applications. The AWT component set has quite a few bugs and
really does take up a lot of system resources when compared to equivalent
Swing resources.

Prepared by : Dr. Ahmad Jamal



Swing is a Set Of API ( API- Set Of Classes and Interfaces )

Swing is Provided to Design Graphical User Interfaces

Swing is an Extension library to the AWT (Abstract Window Toolkit)

Includes New and improved Components that have been enhancing the looks
and Functionality of GUIs’

It Employs model/view design architecture

Swing is more portable and more flexible than AWT, The Swing is built on top
of the AWT

Swing is Entirely written in Java

Java Swing Components are Platform-independent And The Swing
Components are lightweight

Swing Supports a Pluggable look and feels And Swing provides more
powerful components such as tables, lists, Scrollpanes, Colourchooser,
tabbedpane, etc

Further Swing Follows MVC(Model View Controller). Prepared by : Dr. Ahmad Jamal
Creating a Swing Applet and Application
The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

JFC
Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.

Prepared by : Dr. Ahmad Jamal


Hierarchy of Java Swing classes

Prepared by : Dr. Ahmad Jamal


Commonly used Methods of Component class

Prepared by : Dr. Ahmad Jamal


Java Swing Examples
There are two ways to create a frame:

1: By creating the object of Frame class (association)


2: By extending Frame class (inheritance)

Prepared by : Dr. Ahmad Jamal


By creating the object of Frame class (association)
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();

JButton b=new JButton("click");


b.setBounds(130,100,100, 40);

f.add(b);//adding button in JFrame


f.setSize(400,500);
f.setLayout(null);
f.setVisible(true);
}
}
Prepared by : Dr. Ahmad Jamal
Prepared by : Dr. Ahmad Jamal
By extending Frame class (inheritance)

import javax.swing.*;
public class Simple2 extends JFrame{//inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click");
b.setBounds(130,100,100, 40);

add(b);
setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new Simple2();
}
}
Prepared by : Dr. Ahmad Jamal
Prepared by : Dr. Ahmad Jamal
Programming using Panes
A layered pane is a Swing container which is used to hold the various
components using the concept of layers. The components present in the upper
layer overlaps the components present in the lower layer. The layered pane is
created using the JLayeredPane class. the only constructor of this class is
JLayeredPane ().

Prepared by : Dr. Ahmad Jamal


import java.awt.*;
import javax.swing.*;
class LayerExample extends JApplet
{ LPane.add(first, new Integer(1));
JFrame jf ; LPane.add(second, new Integer(2));
JLayeredPane LPane; LPane.add(third, new Integer(3));
JButton first, second, third;
LayerExample ()
{ jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf =new JFrame("Layered Pane Example"); jf.setSize (400,300) ;
LPane =new JLayeredPane(); jf.setVisible(true);
jf.add(LPane); }
first= new JButton("First"); public static void main(String args[])
first.setBackground(Color.red); {
first.setBounds(50,30,100,100); LayerExample le= new LayerExample();
second= new JButton("Second"); }
second.setBackground(Color.yellow); }
second.setBounds(140,60,100,100);
third= new JButton("Third");
third.setBackground(Color.green);
third.setBounds(230,90,100,100);
Prepared by : Dr. Ahmad Jamal
Prepared by : Dr. Ahmad Jamal
Pluggable
Look and feel
Swing is GUI Widget Toolkit for Java. It is an API for providing Graphical User
Interface to Java Programs. Unlike AWT, Swing components are written in Java
and therefore are platform-independent. Swing provides platform specific Look
and Feel and also an option for pluggable Look and Feel, allowing application to
have Look and Feel independent of underlying platform.
Initially there were very few options for colors and other settings in Java Swing,
that made the entire application look boring and monotonous. With the growth in
Java framework, new changes were introduced to make the UI better and thus
giving developer opportunity to enhance the look of a Java Swing Application.

“Look” refers to the appearance of GUI widgets and “feel” refers to the way the
widgets behave.

Prepared by : Dr. Ahmad Jamal


Sun’s JRE provides the following L&Fs:

1 CrossPlatformLookAndFeel: this is the “Java L&F” also known as “Metal”


that looks the same on all platforms. It is part of the Java API
(javax.swing.plaf.metal) and is the default.
2 SystemLookAndFeel: here, the application uses the L&F that is default to
the system it is running on. The System L&F is determined at runtime, where
the application asks the system to return the name of the appropriate L&F.
For Linux and Solaris, the System L&Fs are “GTK+” if GTK+ 2.2 or later is
installed, “Motif” otherwise. For Windows, the System L&F is “Windows”.
3 Synth: the basis for creating your own look and feel with an XML file.
4 Multiplexing: a way to have the UI methods delegate to a number of different
look and feel implementations at the same time.

Prepared by : Dr. Ahmad Jamal


sample code to get the list of
installed Look and Feel themes

import javax.swing.UIManager;
public class MainClass { public static void main(String[] a)
{
UIManager.LookAndFeelInfo[] looks =
UIManager.getInstalledLookAndFeels();
for (UIManager.LookAndFeelInfo look : looks) {
System.out.println(look.getClassName());
}
}
}

Prepared by : Dr. Ahmad Jamal


Prepared by : Dr. Ahmad Jamal
Swing Components

Prepared by : Dr. Ahmad Jamal


Components Uses

Jlabel l = new Jlabel();

JTextField t = new JtextField();

JButton b=new JButton("Click Here");

JtoggleButton greenBtn = new JToggleButton("green");

JCheckBox checkBox1 = new JcheckBox("C++");

JRadioButton r1=new JradioButton("Male");

Prepared by : Dr. Ahmad Jamal


Jviewport : The JViewport class is used to implement scrolling.
JscrollPane: A JscrollPane is used to make scrollable view of a component.
JscrollBar: The object of JScrollbar class is used to add horizontal and vertical
scrollbar. It is an implementation of a scrollbar. It inherits JComponent class.

Prepared by : Dr. Ahmad Jamal


Jlist
Jlist: JList is a component that displays a set of Objects and allows the user to
select one or more items.

Prepared by : Dr. Ahmad Jamal


JComboBox
JcomboBox: JComboBox shows a popup menu that shows a list and the user
can select a option from that specified list . JComboBox can be editable or read-
only depending on the choice of the programmer .

Prepared by : Dr. Ahmad Jamal


JProgressBar
JProgressBar visually displays the progress of some specified task.
JProgressBar shows the percentage of completion of specified task.The
progress bar fills up as the task reaches it completion. In addition to show the
percentage of completion of task, it can also display some text .

Prepared by : Dr. Ahmad Jamal


JMenuBar, JMenu and JMenuItems
JMenuBar is an implementation of menu bar . the JMenuBar contains one or
more JMenu objects, when the JMenu objects are selected they display a
popup showing one or more JMenuItems . JMenu basically represents a menu .
It contains several JMenuItem Object . It may also contain JMenu Objects (or
submenu).

Prepared by : Dr. Ahmad Jamal


JToolBar
JToolBar is an implementation of toolbar. The JToolBar is a group of commonly
used components such as buttons or drop down menu.

Prepared by : Dr. Ahmad Jamal


JTabbedPane
JTabbedPane class is used to switch between a group of components by
clicking on a tab with a given title or icon.

Prepared by : Dr. Ahmad Jamal


JSplitPane
JSplitPane is used to divide two components. The two components are divided
based on the look and feel implementation, and they can be resized by the user.

Prepared by : Dr. Ahmad Jamal


Layouts
Layout refers to the arrangement of components within the container. In another
way, it could be said that layout is placing the components at a particular
position within the container. The task of laying out the controls is done
automatically by the Layout Manager.

The layout manager automatically positions all the components within the
container. Even if you do not use the layout manager, the components are still
positioned by the default layout manager.

Java provides various layout managers to position the controls. Properties like
size, shape, and arrangement varies from one layout manager to the other.
When the size of the application window changes, the size, shape, and
arrangement of the components also changes in response, i.e. the layout
managers adapt to the dimensions of the application window.
Prepared by : Dr. Ahmad Jamal
AWT Layout Manager Classes
commonly used controls while designing GUI using AWT
BorderLayout: The borderlayout arranges the components to fit in the five
regions: east, west, north, south, and center.

Prepared by : Dr. Ahmad Jamal


FlowLayout
FlowLayout class is used to arrange the components in a line, one
after another (in a flow).

Prepared by : Dr. Ahmad Jamal


GridLayout

GridLayout class is used to arrange the components in a rectangular grid. One


component is displayed in each rectangle.

Prepared by : Dr. Ahmad Jamal


JWindow
JWindow is a part of Java Swing and it can appear on any part of the users
desktop. It is different from JFrame in the respect that JWindow does not have a
title bar or window management buttons like minimize, maximize, and close,
which JFrame has.

Prepared by : Dr. Ahmad Jamal


JDialog
JDialog is a part Java swing package. The main purpose of the dialog is to add
components to it. JDialog can be customized according to user need .

Prepared by : Dr. Ahmad Jamal


JInternalFrame
JInternalFrame is a part of Java Swing . JInternalFrame is a container that
provides many features of a frame which includes displaying title, opening,
closing, resizing, support for menu bar, etc.

Prepared by : Dr. Ahmad Jamal


JDBC
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:


JDBC-ODBC Bridge Driver

Native Driver

Network Protocol Driver

Thin Driver

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.

Prepared by : Dr. Ahmad Jamal


java.sql package contains classes and interfaces for JDBC API

Prepared by : Dr. Ahmad Jamal


Why Should We Use 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:

1: Connect to the database


2: Execute queries and update statements to the database
3: Retrieve the result received from the database.

Prepared by : Dr. Ahmad Jamal


JDBC Driver

JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:

1: JDBC-ODBC bridge driver


2: Native-API driver (partially java driver)
3: Network Protocol driver (fully java driver)
4: Thin driver (fully java driver)

Prepared by : Dr. Ahmad Jamal


1: JDBC-ODBC bridge driver

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.

Oracle does not support the JDBC-ODBC Bridge from Java 8.


Prepared by : Dr. Ahmad Jamal
Advantages:
1: easy to use.
2: can be easily connected to any database.

Disadvantages:
1: Performance degraded because JDBC method call is converted into the ODBC function
calls.
2: The ODBC driver needs to be installed on the client machine.

Prepared by : Dr. Ahmad Jamal


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:
1: Performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:
1: The Native driver needs to be installed on the each client machine.
Prepared by : Dr. Ahmad Jamal
2: The Vendor client library needs to be installed on client machine.
3) Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.

Advantage:
1: No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.

Disadvantages:
1: Network support is required on client machine.
2: Requires database-specific coding to be done in the middle tier.
3: Maintenance of Network Protocol driver becomes costly because it requires database- specific
coding to be done in the middle tier. Prepared by : Dr. Ahmad Jamal
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:
1: Better performance than all other drivers.
2: No software is required at client side or server side.
Disadvantage:
1: Drivers depend on the Database.
Prepared by : Dr. Ahmad Jamal
Java Database Connectivity with 5 Steps

1: Register the Driver class


2: Create connection
3: Create statement
4: Execute queries
5: Close connection

Prepared by : Dr. Ahmad Jamal


1) Register the driver class

The forName() method of Class class is used to register the driver class. This method
is used to dynamically load the driver class.

Syntax of forName() method


public static void forName(String className)throws ClassNotFoundException

Note: 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.

The driver class for the mysql database is com.mysql.jdbc.Driver


Prepared by : Dr. Ahmad Jamal
2) Create the connection object
The getConnection() method of DriverManager class is used to establish connection
with the database.

Syntax of getConnection() method

public static Connection getConnection(String url)throws SQLException


public static Connection getConnection(String url,String name,String password)
throws SQLException

The connection URL for the mysql database is jdbc:mysql://localhost:3306/DB_Name where


jdbc is the API, mysql is the database, localhost is the server name on which mysql is
running, we may also use IP address, 3306 is the port number and DB_Name is the database
Name.

Note:
1. Username: The default username for the mysql database is root.
2. 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.
Prepared by : Dr. Ahmad Jamal
3) Create the Statement object

The createStatement() method of Connection interface is used to create statement.


The object of the statement is responsible to execute queries with the database.

Syntax of createStatement() method


public Statement createStatement()throws SQLException

Example:
Statement stmt=con.createStatement()

Prepared by : Dr. Ahmad Jamal


4) Execute the query

The executeQuery() method of Statement interface is used to execute queries to the


database. This method returns the object of ResultSet that can be used to get all the
records of a table.

Syntax of executeQuery() method


public ResultSet executeQuery(String sql)throws SQLException

Example:

ResultSet rs=stmt.executeQuery("select * from student");


while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

Prepared by : Dr. Ahmad Jamal


5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically.


The close() method of Connection interface is used to close the connection.

Syntax
public void close()throws SQLException

Example:
con.close();

Prepared by : Dr. Ahmad Jamal


java.sql Package
The java.sql package provides the API for accessing and processing data
stored in a data source (usually a relational database) using the Java
programming language. This API includes a framework whereby different drivers
can be installed dynamically to access different data sources. Although the
JDBC API is mainly geared to passing SQL statements to a database, it
provides for reading and writing data from any data source with a tabular format.

Prepared by : Dr. Ahmad Jamal


java.sql Package Contains
1. Making a connection with a database via the DriverManager facility
2. Sending SQL statements to a database
3. Retrieving and updating the results of a query
4. Standard mappings for SQL types to classes and interfaces in the Java
programming language
5. Custom mapping an SQL user-defined type (UDT) to a class in the Java
programming language
6. Metadata
7. Exceptions

Prepared by : Dr. Ahmad Jamal


Connectivity to remote database,
navigating through multiple rows retrieved from a database

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCExample {


static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Employees";

Prepared by : Dr. Ahmad Jamal


public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER,
PASS);
Statement stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery(QUERY);
){
// Move cursor to the last row.
System.out.println("Moving cursor to the last...");
rs.last();

// Extract data from result set


System.out.println("Displaying record...");
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first"); Prepared by : Dr. Ahmad Jamal
String last = rs.getString("last");
// Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);

// Move cursor to the first row.


System.out.println("Moving cursor to the first row...");
rs.first();

// Extract data from result set


System.out.println("Displaying record...");
// Retrieve by column name
id = rs.getInt("id");
age = rs.getInt("age");
first = rs.getString("first");
last = rs.getString("last");

Prepared by : Dr. Ahmad Jamal


// Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
// Move cursor to the first row.

System.out.println("Moving cursor to the next row...");


rs.next();
// Extract data from result set
System.out.println("Displaying record...");
id = rs.getInt("id");
age = rs.getInt("age");
first = rs.getString("first");
last = rs.getString("last");
// Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first); Prepared by : Dr. Ahmad Jamal
System.out.println(", Last: " + last);
} catch (SQLException e) {
e.printStackTrace();
}
}
} Output
C:\>java JDBCExample
Moving cursor to the last...
Displaying record...
ID: 103, Age: 30, First: Sumit, Last: Mittal
Moving cursor to the first row...
Displaying record...
ID: 100, Age: 18, First: Zara, Last: Ali
Moving cursor to the next row...
Displaying record...
ID: 101, Age: 25, First: Mehnaz, Last: Fatma
Goodbye!

Prepared by : Dr. Ahmad Jamal

You might also like