Unit 5 Java
Unit 5 Java
https://www.javatpoint.com/event-h
andling-in-java
https://www.javatpoint.com/java-a
wt
Creating, reading, updating, and deleting data in a database is a common task in many applications, and JDBC (Java
Database Connectivity) is a Java API that allows you to connect to a database and perform these operations, the steps
of setting up a simple CRUD (create, read, update, delete) operation using JDBC.are…
The first step is to establish a connection to the database. You can do this by loading the JDBC driver and creating a
connection object.
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "username", "password");
System.out.println("Connection established.");
}
catch (Exception e) {
e.printStackTrace();
}
2. Create a new record
Once you have a connection to the database, you can use the connection object to create a new record in the
database. To do this, you will need to use an SQL INSERT statement and execute it using the connection object.
try {
String sql = "INSERT INTO mytb VALUES (333,’Girish’)";
Statement statement = con.createStatement();
statement.executeUpdate(sql);
System.out.println("Record created.");
} catch (SQLException e) {
e.printStackTrace();
}
3. Read a record
To read a record from the database, you will need to use an SQL
SELECT statement and execute it using the connection object.
The result of the query will be a ResultSet object that you can
use to access the data in the record.
try {
String sql = "SELECT * FROM mytb";
Statement statement = con.createStatement();
ResultSet result = statement.executeQuery(sql);
if (result.next()) {
int id= result.getInt(“id");
String name = result.getString(“name");
}
} catch (SQLException e) {
e.printStackTrace();
}
4. Update a record
try {
String sql = "UPDATE mytb SET name =‘T.Lavanya’ WHERE id = 111";
Statement statement = con.createStatement();
statement.executeUpdate(sql);
System.out.println("Record updated.");
} catch (SQLException e) {
e.printStackTrace();
}
5. Delete a record
try {
String sql = "DELETE FROM table_name WHERE id = 333";
Statement statement = con.createeStatement();
statement.executeUpdate(sql);
System.out.println("Record deleted.");
} catch (SQLException e) {
e.printStackTrace();
}
CRUD operations in Java can be easily performed using JDBC. With a few simple steps, you can connect to a
database, create new records, read existing records, update records, and delete records. This allows you to easily
manage your data and maintain the integrity of your application.
Create and Read Operation: // Processing the result
while (resultSet.next()) {
import jdbc.sql.*; // Assuming your table has a column named 'id' and
public class Main { 'name'
public static void main(String[] args) { int id = resultSet.getInt("id");
// Database URL, username, and password String name = resultSet.getString("name");
String url = "jdbc:mysql://localhost:3306/db"; System.out.println("ID: " + id + ", Name: " + name);
String user = "root"; // Replace with your MySQL username }
String password = ""; // Replace with your MySQL password } catch (SQLException e) {
// SQL query to be executed e.printStackTrace();
String query = "Insert into mytb values(333,'Girish')"; } finally {
String squery ="select * from mytb"; // Closing the resources
Connection connection = null; resultSet.close();
Statement statement = null; statement.close();
ResultSet resultSet = null; connection.close(); }}}
try {
// Establishing the connection
connection = DriverManager.getConnection(url, user,
password);
// Creating a Statement object OUTPUT:
statement = connection.createStatement(); ID: 111, Name: Lavanya
// Executing the query ID: 222, Name: Suja
statement.executeUpdate(query); ID: 333, Name: Girish
resultSet = statement.executeQuery(squery
Event Handling
Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event
package provides many event classes and Listener interfaces for event handling.
Two Event Handling Mechanisms
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. Java Uses the
Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the
events.Let's have a brief introduction to this model.
The Delegation Event Model has the following key participants namely:
Source - The source is an object on which event occurs. Source is responsible for providing information of the occurred
event to it's handler. Java provide as with classes for source object.
Listener - It is also known as event handler.Listener is responsible for generating response to an event. From java
implementation point of view the listener is also an object. Listener waits until it receives an event. Once the event is
received , the listener process the event and then returns.
The Delegation Event Model
Steps involved in event handling
The User clicks the button and the event is generated.
Now the object of concerned event class is created automatically and information about the source and the
event get populated with in same object.
If you do not implement the any if the predefined interfaces then your class can not act as a
listener class for a source object.
Java event handling by implementing ActionListener
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent(); } }
Working with AWT
Classes:
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or windows-based
applications in Java.
Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system.
AWT is heavy weight i.e. its components are using the resources of underlying operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label, TextArea, RadioButton, CheckBox,
Choice, List etc.
For example, an AWT GUI with components like TextField, label and button will have different look and feel for the
different platforms like Windows, MAC OS, and Unix. The reason for this is the platforms have different view for
their native components and AWT directly calls the native subroutine that creates those components.
In simple words, an AWT application will look like a windows application in Windows OS whereas it will look like
a Mac application in the MAC OS.
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.
Components
All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT, there are classes for
each component as shown in above diagram. In order to place every component in a particular position on a screen, we
need to add them to a container.
Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The
classes that extends Container class are known as container such as Frame, Dialog and Panel.
It is basically a screen where the where the components are placed at their specific locations. Thus it contains and controls
the layout of components.
Types of containers:
Window
Panel
Frame
Dialog
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or another window
for creating a window. We need to create an instance of Window class to create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic container for holding the
components. It can have other components like button, text field etc. An instance of Panel class creates a container,
in which we can add components.
Frame
The Frame is the container that contain title bar and border and can have menu bars. It can have other components
like button, text field, scrollbar etc. Frame is most widely used container while developing an AWT application.
Dialog
The Dialog control represents a top level window with a border and a title used to take some form of input from the
user. It inherits the Window class.Unlike Frame, it doesn't have maximize and minimize buttons.
Useful Methods of Component Class
Java AWT Example
To create simple AWT example, you need a frame. There are two ways to create a GUI using Frame in AWT.
AWTExample2.java’s output
AWTExample2.java’s code // frame size 300 width and 300 height
// importing Java AWT class f.setSize(400,300);
import java.awt.*;
// class AWTExample2 directly creates instance of Frame class // setting the title of frame
class AWTExample2 { f.setTitle("Employee info");
// initializing using constructor
AWTExample2() { // no layout
// creating a Frame f.setLayout(null);
Frame f = new Frame();
// creating a Label // setting visibility of frame
Label l = new Label("Employee id:"); f.setVisible(true);
// creating a Button }
Button b = new Button("Submit"); // main method
// creating a TextField public static void main(String args[]) {
TextField t = new TextField(); // creating instance of Frame class
// setting position of above components in the frame AWTExample2 awt_obj = new AWTExample2();
l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30); }
b.setBounds(100, 100, 80, 30);
// adding components into frame }
f.add(b);
f.add(l);
f.add(t);