UNIT 6 — INTRODUCING SWING AND JDBC
6.1 Design Philosophy of Swing
Swing
Swing is a Java GUI toolkit used to create desktop applications.
Features of Swing
- Platform independent
- Lightweight components
- Rich GUI components
- Event driven
- Customizable
AWT vs Swing
| AWT | Swing |
|---|---|
| heavyweight | lightweight |
| less components | more components |
| platform dependent | platform independent |
| uses native OS controls | pure Java components |
Importing Swing Package
import javax.swing.*;
6.2 Components and Containers
Component
GUI element used in application.
Examples
- JButton
- JTextField
- JLabel
- JCheckBox
- JList
Container
Container holds components.
Examples
- JFrame
- JPanel
- JDialog
JFrame
Main window of Swing application.
Creating JFrame
import javax.swing.*;
class Test{
public static void main(String args[]){
JFrame f =
new JFrame("My Frame");
f.setSize(400,300);
f.setVisible(true);
}
}
Important JFrame Methods
| Method | Purpose |
|---|---|
| setSize() | sets frame size |
| setVisible() | shows frame |
| setTitle() | sets title |
| setLayout() | sets layout |
| add() | adds component |
| setDefaultCloseOperation() | closes frame properly |
6.3 Layout Managers
Layout Manager
Controls arrangement of components.
Types of Layout Managers
| Layout | Description |
|---|---|
| FlowLayout | left to right arrangement |
| BorderLayout | north, south, east, west, center |
| GridLayout | rows and columns |
| CardLayout | multiple screens/cards |
| BoxLayout | horizontal/vertical layout |
FlowLayout Example
import javax.swing.*;
import java.awt.*;
class Test{
public static void main(String args[]){
JFrame f = new JFrame();
f.setLayout(new FlowLayout());
f.add(new JButton("One"));
f.add(new JButton("Two"));
f.setSize(300,300);
f.setVisible(true);
}
}
BorderLayout Example
f.setLayout(new BorderLayout());
f.add(new JButton("North"),
BorderLayout.NORTH);
f.add(new JButton("South"),
BorderLayout.SOUTH);
GridLayout Example
f.setLayout(new GridLayout(2,2));
6.4 Swing Event Handling
Event
An event is an action performed by user.
Examples
- Button click
- Mouse click
- Keyboard press
Event Handling Process
User Action
↓
Event Generated
↓
Listener Handles Event
Event Listener
Object that handles events.
ActionListener Interface
import java.awt.event.*;
actionPerformed() Method
public void actionPerformed(
ActionEvent e){
}
Button Event Example
import javax.swing.*;
import java.awt.event.*;
class Test implements ActionListener{
JFrame f;
JButton b;
Test(){
f = new JFrame();
b = new JButton("Click");
b.setBounds(100,100,100,40);
b.addActionListener(this);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(
ActionEvent e){
System.out.println("Button Clicked");
}
public static void main(
String args[]){
new Test();
}
}
Important Event Classes
| Event | Listener |
|---|---|
| ActionEvent | ActionListener |
| MouseEvent | MouseListener |
| KeyEvent | KeyListener |
| WindowEvent | WindowListener |
6.5 Basic Swing Components
JButton
Creates button.
JButton b =
new JButton("Save");
JTextField
Single line text input.
JTextField t =
new JTextField();
JCheckBox
Creates checkbox.
JCheckBox c =
new JCheckBox("Java");
JList
Displays list items.
String data[] =
{"C","Java","Python"};
JList l =
new JList(data);
JLabel
Displays text label.
JLabel l =
new JLabel("Name");
Simple Form Example
import javax.swing.*;
class Test{
public static void main(
String args[]){
JFrame f = new JFrame();
JLabel l =
new JLabel("Name");
JTextField t =
new JTextField();
JButton b =
new JButton("Submit");
l.setBounds(50,50,100,30);
t.setBounds(150,50,100,30);
b.setBounds(100,100,100,30);
f.add(l);
f.add(t);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
6.6 Anonymous Inner Classes to Handle Events
Anonymous Inner Class
Class without name.
Button Event Using Anonymous Class
import javax.swing.*;
import java.awt.event.*;
class Test{
public static void main(
String args[]){
JFrame f = new JFrame();
JButton b =
new JButton("Click");
b.setBounds(100,100,100,40);
b.addActionListener(
new ActionListener(){
public void actionPerformed(
ActionEvent e){
System.out.println(
"Button Clicked");
}
});
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Advantages of Anonymous Inner Class
- Less code
- Easy event handling
- No separate class needed
6.7 The Design of JDBC
JDBC
JDBC stands for Java Database Connectivity.
Purpose of JDBC
- Connect Java with database
- Execute SQL queries
- Perform CRUD operations
JDBC Architecture
Java Application
↓
JDBC API
↓
JDBC Driver
↓
Database
Important JDBC Classes and Interfaces
| Class/Interface | Purpose |
|---|---|
| DriverManager | manages drivers |
| Connection | database connection |
| Statement | execute SQL query |
| PreparedStatement | parameterized query |
| ResultSet | stores query result |
Steps to Connect Database
- Import package
- Load driver
- Create connection
- Create statement
- Execute query
- Close connection
Import JDBC Package
import java.sql.*;
Loading Driver
Class.forName(
"com.mysql.jdbc.Driver");
Creating Connection
Connection con =
DriverManager.getConnection(
"jdbc:mysql://localhost/test",
"root",
"");
6.8 Executing SQL Statements
Creating Statement
Statement st =
con.createStatement();
executeUpdate()
Used for INSERT, UPDATE, DELETE.
Insert Example
st.executeUpdate(
"insert into student values
(1,'Ram')");
Update Example
st.executeUpdate(
"update student set name='Hari'
where id=1");
Delete Example
st.executeUpdate(
"delete from student
where id=1");
PreparedStatement
Used for dynamic and secure query.
PreparedStatement Example
PreparedStatement ps =
con.prepareStatement(
"insert into student values(?,?)");
ps.setInt(1,1);
ps.setString(2,"Ram");
ps.executeUpdate();
Advantages of PreparedStatement
- Faster execution
- Secure against SQL injection
- Dynamic query support
6.9 Query Execution
executeQuery()
Used for SELECT query.
SELECT Example
ResultSet rs =
st.executeQuery(
"select * from student");
while(rs.next()){
System.out.println(
rs.getInt(1)+" "+
rs.getString(2));
}
ResultSet Methods
| Method | Purpose |
|---|---|
| next() | moves next row |
| getInt() | gets integer value |
| getString() | gets string value |
| getDouble() | gets double value |
Closing Connection
con.close();
Complete JDBC CRUD Example
import java.sql.*;
class Test{
public static void main(
String args[])throws Exception{
Class.forName(
"com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection(
"jdbc:mysql://localhost/test",
"root","");
Statement st =
con.createStatement();
st.executeUpdate(
"insert into student values
(1,'Ram')");
ResultSet rs =
st.executeQuery(
"select * from student");
while(rs.next()){
System.out.println(
rs.getInt(1)+" "+
rs.getString(2));
}
con.close();
}
}
Most Important Practical Programs
- Simple JFrame program
- FlowLayout program
- GridLayout program
- Button click event handling
- Anonymous inner class event handling
- JTextField form program
- JCheckBox program
- Database connection program
- Insert query using JDBC
- Select query using ResultSet
- CRUD operations using JDBC
Most Important Theory Questions
- What is Swing?
- Difference between AWT and Swing.
- Explain layout managers.
- Explain event handling.
- What is ActionListener?
- Explain anonymous inner class.
- What is JDBC?
- Explain JDBC architecture.
- Explain steps to connect database.
- Difference between Statement and PreparedStatement.
- Explain ResultSet.
Important Viva Questions
Which package is used for Swing?
javax.swing
Which package is used for JDBC?
java.sql
Which class creates main window?
JFrame
Which layout arranges components left to right?
FlowLayout
Which method handles button click event?
actionPerformed()
Which interface handles button event?
ActionListener
Which method executes SELECT query?
executeQuery()
Which method executes INSERT query?
executeUpdate()
Which object stores SELECT query result?
ResultSet
0 comments:
Post a Comment