0% found this document useful (0 votes)
65 views23 pages

2-1 Lab Manual Oop

Uploaded by

mudassir awan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views23 pages

2-1 Lab Manual Oop

Uploaded by

mudassir awan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

LAB MANUAL

OBJECT ORIENTED PROGRAMMING


CSOO-142

DEPARTMENT OF COMPUTER SCIENCE


FACULTY OF ENGINEERING & COMPUTER SCIENCES
NATIONAL UNIVERSITY OF MODERN LANGUAGES
H-9, ISLAMABAD
PAKISTAN
BS (Computer Science) 2023

Preface
Object-oriented programming (OOP) is a programming paradigm that uses abstraction to create models based
on the real world. It utilizes several techniques from previously established paradigms, including modularity,
polymorphism, and encapsulation. In OOP, each object is capable of receiving messages, processing data, and
sending messages to other objects. Each object can be viewed as an independent little machine with a distinct
role or responsibility. Object-oriented programming is intended to promote greater flexibility and
maintainability in programming, and is widely popular in large-scale software engineering. By virtue of its
strong emphasis on modularity, object oriented code is intended to be simpler to develop and easier to
understand later on, lending itself to more direct analysis, coding, and understanding of complex situations
and procedures than less modular programming methods. There are principles that work in OOP, such as
encapsulation, inheritance, polymorphism and Abstraction.

This lab will enable students to learn basic OOP concepts with the help of Java Language i.e., class-based
modeling, Inheritance, Polymorphism, Abstraction interface, exceptional handling and GUI.

Objective
 To strengthen problem solving ability by using the characteristics of an object-oriented approach.
 To design applications using object-oriented principles and features
 To differentiate OOP and Procedural programming
 To handle Exceptions in programs.
 To Handle and Debug Errors and Bugs in a program
 To learn about latest software development tools and IDEs

Tools/ Technologies
1. Java, JDK, Net beans
2. MS Access, M-SQL, Ucanaccess

Effectiveness
The student will acquire required skills and knowledge to develop applications using object-oriented concepts.
They will gain the ability to analyze given problems from object-oriented programming dimensions and select
appropriate OOP principles to implement it. The students will demonstrated satisfactory skills for including
OOP concepts in general software systems.

2
BS (Computer Science) 2023

Weekly Breakdown

Week # Title of the Lab/ TASKS TO BE COVERED


1.  Create, compile and run java files using command prompt.
 Create a class Calculator with two variables, a constructor with no parameter and two
functions for add and multiply.
 Create a class TestApp with a main function and create object of Calculator class to call
functions.

2.  Error correction in above java files.


 Add functionality for overloading sum and multiply.
 Overview of math class and call functions using Math class.

3.  Create an overloaded constructor for Calculator and create object using both
constructors
 Create an Interface CalcIntf, implement its functions in CalculatorImpl and finally
create the object CalcIntf object in TestApp.
 Differentiate between the accessibility of functions using objects of CalcIntf and
CalculatorImpl.
 Implement multiple interfaces in a single class.
4.  Create a parent class “Account” with three variables num, title and bal with two
functions withdraw and deposit.
 Create a child class “SavingAccount” with a function calculateProfit (that applies
7.5%
profit on current balance).
 Finally create the class “TestApp” that creates the object of Saving account and call
withdraw, deposit functions.
 Override withdraw function in SavingAccount to deduct Rs. 250 if the balance after
withdrawal of amount is less than 10000.
5.  Use of this, super, protected and finally keywords.
 Creating multiple objects of the same class.
 Use of netbeans to create window forms, get values from text fields and action on
button.
6.  Design a calculator in netbeans with two text boxes and implement the functionality of
+, -, * and /.
 Similarly modify the logic to use single text field for calculations.
 Call the functions of Calculator class to provide the functionality.
7.  Implementaion of Layout Manger in order to set layout of different Containers
i.e. JFrame etc.
 Use of BorderLayout for JPanel and JFrame
 GridLayout to used to generate Gradient display

3
BS (Computer Science) 2023

8.  Creating and importing packages using netbeans and console based apps.
 Catch the Arithmetic Exception for divide function in above calculator.
9.  Create a new database in MSAccess2007 and then create a student table with its basic
attributes.
 Design a Form in netbeans to insert information of a student.
 Write code behind the button to connect with database, write query and then execute
it.
 Code Overview of used functions, classes and interfaces from javadoc.
10.  Create new class DbConn containing a connection string and a single function to
insert,
update and delete records. It takes query as input and return boolean.
 Error correction in search and update records.
 Create another function in DbConn to search records that returns the ResultSet.
11.  Get a list of products from table and display it in Combo box in Sales Form.
 Also add menus with menu items and handle the click events using netbeans.
 Add a combo box and add values using properties.
12.  Create a package containing interface and classes and the import to call functions in
TestApp class.
 Get details of products and display it in JTable,
 Opening multiple forms from main page and login form creation.
 Validation of input fields and use regular expressions.

4
BS (Computer Science) 2023

TABLE OF CONTENTS

Preface ............................................................................................................................................................... 2
Objective ........................................................................................................................................................... 2
Tools/ Technologies .......................................................................................................................................... 2
Effectiveness ..................................................................................................................................................... 2
Weekly Breakdown .......................................................................................................................................... 3
LAB 1: Class, Object, Constructor ................................................................................................................ 6
LAB 2: Overloading, import Header Files .................................................................................................... 7
LAB 3: Inheritance .......................................................................................................................................... 8
LAB 4: Interfaces and polymorphism............................................................................................................ 9
LAB 5: GUI Components .............................................................................................................................. 10
LAB 6: GUI Components .............................................................................................................................. 11
LAB 7: Layout Managers .............................................................................................................................. 12
LAB 8: Database Connectivity->insert Query ............................................................................................ 15
LAB 9: Database Connectivity, SQL Update and Select query................................................................. 16
LAB 10: GUI/Database Connectivity using layered Architecture ............................................................ 18
LAB 11: GUI/Database Connectivity using layered Architecture ............................................................ 20
LAB 12: GUI/ layered Architecture/JTable ................................................................................................ 23

5
BS (Computer Science) 2023

LAB 1: Class, Object, Constructor

Objectives:
 To learn how to implement class, object, constructor
 Create, compile and run java files using command prompt

Theoretical Description:

Create a class Calculator with two variables, a constructor with no parameter and two functions for add and
multiply. Create a class TestApp with a main function and create object of Calculator class to call functions.

Lab Task(s):

Calculator.java TestApp.java
public class Calculator public class TestApp
{ {
int x, y;
public TestApp() {
public Calculator() { }
}
public static void main(String args[])
int sum(int a, int b) {
{ Calculator obj=new Calculator();
return a+b; int n = obj.sum(10,20);
} System.out.println("Sum=" + n);
int mul(int a, int b) int m=obj.mul(5,6);
{ System.out.println("mul="+m);
return a*b; }
} }
}

Set Java Path:


Set path=C:\Program Files\Java\jdk1.6.0_26\bin
Set Path to Source Code Directory:
Cd D:\OOPLAB\YourName
Compile File:
Javac TestApp.java
Run File:
Java TestApp

6
BS (Computer Science) 2023

LAB 2: Overloading, import Header Files

Objectives:
 To learn how to implement overloading
 To learn how to import Header Files

Theoretical Description:

Create a class Calculator with two variables, a constructor with no parameter and two functions for add and
multiply. Add functionality for overloading sum and multiply. Also call scientific functions using Math class.
Create a class TestApp with a main function and create object of Calculator class to call functions.

Lab Task(s):
Calculator.java TestApp.java
public class Calculator public class TestApp
{ {
int x, y;
public TestApp() {
public Calculator() { }
}
public static void main(String args[])
int sum(int a, int b) {
{
return a+b; Calculator obj=new Calculator();
}
int s = obj.sum(10,20);
int sum(int a, int b, int c) System.out.println("Sum=" + s);
{ double s1 = obj.sum(15.5,56.7);
return a+b+c; System.out.println("Sum=" + s1);
} s = obj.sum(15,25,10);
System.out.println("Sum=" + s);
double sum(double a, double b)
{ int m=obj.mul(5,6);
return a+b; System.out.println("mul="+m);
} double m1=obj.mul(59.7,66.6);
System.out.println("mul="+m1);
int mul(int a, int b)
{ System.out.println("sin="+Math.sin(55.6));
return a*b; System.out.println("sin="+Math.pow(5,3));
}
}
double mul(double a, double b) }
{
return a*b;
}

7
BS (Computer Science) 2023

LAB 3: Inheritance

Objectives:
 To learn how to implement overloading
 To learn how to import Header Files

Theoretical Description:

Create a parent class “Account” with three variables num, title and bal with two functions withdraw and
deposit. Create a child class “SavingAccount” with a function calculateProfit (that applies 7.5% profit on
current balance). Finally create the class “TestApp” that creates the object of Saving account and call
withdraw, deposit functions. Override withdraw function in SavingAccount to deduct Rs. 250 if the balance
after withdrawal of amount is less than 10000.
.
Lab Task(s):
Account.java SavingAccount.java TestApp.java
public class Account public class SavingAccount public class TestApp
{ extends Account { {
public String acct_num; public SavingAccount(){ public TestApp() {
public String acct_title; } }
public double acct_bal; public static void main(String args[])
public void withdraw (double {
public Account(){ amt) SavingAccount s = new
} { SavingAccount ();
public void withdraw if (acct_bal > amt)
(double amt) acct_bal -= amt; s.acct_num = “01-01-999888”;
{ if (acct_bal < 10000) s.acct_title = “MyAcctTitle”
if (acct_bal > amt) acct_bal -= 250; s.acct_bal = 10000.0;
acct_bal -= amt; }
} public double calculateProfit () s.withdraw (2000.0);
{ System.out.println
public void deposit (double double profit = acct_bal * ("Balance="+s.acct_bal);
amt) 0.075; }
{ acct_bal += profit; }
acct_bal += amt; return profit;
} }
} }

8
BS (Computer Science) 2023

LAB 4: Interfaces and polymorphism

Objectives:
 To learn how to implement interfaces and polymorphism

Theoretical Description:

Create an interface for two functions for add and multiply. Create a class Calculator with two class level
variables, a parameterized overloaded constructor and four functions for add, subtract, divide and multiply.
Create a class TestApp with a main function and create object of Calculator interface to call functions.

Lab Task(s):
CalcIntf.java CalculatorImpl.java TestApp.java
public interface CalcIntf public class Calculator public class TestApp
{ { {
public int sum(int a,int b); int x, y; public TestApp() {
public int mul(int a,int b); }
} public Calculator() { public static void main(String args[])
} {
CalcIntf obj=new CalculatorImpl();
int sum(int a, int b) int n = obj.sum(10,20);
{ System.out.println("Sum=" + n);
return a+b; int m=obj.mul(5,6);
} System.out.println("mul="+m);
int mul(int a, int b)
{ //Not accessible to call
return a*b; //int m=obj.div(5,6);
}
int div(int a, int b) CalculatorImpl calc=new CalculatorImpl();
{ int result = calc.sum(10,20);
return a/b; System.out.println("Sum=" + result);
} result = calc.mul(5,6);
int sub(int a, int b) System.out.println("Product="+ result);
{ result = calc.div(20,4);
return a-b; System.out.println("Division="+ result);
} result = calc.sub(9,3);
System.out.println("Difference="+ result);
} }
}

9
BS (Computer Science) 2023

LAB 5: GUI Components

Objectives:
 To start with GUI components i.e. JFrame, JTextField, JButton, JLabael, Event Handling

Theoretical Description:

Create a class Calculator with two variables, a constructor with no parameter and two functions for add and
multiply. Use netbeans to create window forms with two text fields and two buttons for plus and multiply.
Write code behind button to take values from text fields and create object of Calculator class to call functions
by passing parameters.

Lab Task(s):
Calculator.java CalculatorForm.java
public class Calculator public class CalculatorForm extends JFrame
{ {
int x, y;
public CalculatorForm() {
public Calculator() { }
}
public void btnPlusActionPerformed(ActionEvent e)
int sum(int a, int b) {
{ int v1=Integer.parseInt(txtval1.getText());
return a+b; int v2=Integer.parseInt(txtval2.getText());
}
int mul(int a, int b) Calculator obj=new Calculator();
{ int s = obj.sum(v1,v2);
return a*b; lblOutput.setText(“Sum = ” +s);
} }
} }

Output:

10
BS (Computer Science) 2023

LAB 6: GUI Components

Objectives:
 To start with GUI components i.e. JFrame, JTextField, JButton, JLabael, Event Handling

Theoretical Description:
Create a Simple Calculator e.g. Windows Calculator. Use netbeans to create window forms with single text
fields and provide functionality for plus, minus multiply C, 1,2, MR, M+, MC. Write code behind buttons to
take values from text field and implement the intended functionality.

Lab Task(s):
CalculatorForm.java
public class SimpleCalculator extends JFrame public void btnEqualsActionPerformed(ActionEvent e){
{ int r=0;
int v1, v2, opt=0, mem; v2= Integer.parseInt(txtval1.getText());

public void btnOneActionPerformed(ActionEvent switch(opt)


e){ {
txtval.setText(txtval.getText() + “1”); case 1:
} r = v1+v2;
break;
public void btnTwoActionPerformed(ActionEvent case 2:
e){ r = v1*v2;
txtval.setText(txtval.getText() + “2”); break;
} }
}
public void btnClearActionPerformed(ActionEvent public void btnMCActionPerformed(ActionEvent e){
e){ mem=0;
txtval.setText(“”); }
v2=0;
} public void btnMPlusActionPerformed(ActionEvent e){
mem=mem+ Integer.parseInt(txtval1.getText());
public void btnPlusActionPerformed(ActionEvent }
e){
v1= Integer.parseInt(txtval1.getText()); public void btnMRActionPerformed(ActionEvent e){
opt = 1; txtval1.setText(“”+mem);
} }

public void btnMulActionPerformed(ActionEvent


e){
v1= Integer.parseInt(txtval1.getText());
opt = 2;
}

Output:

11
BS (Computer Science) 2023

LAB 7: Layout Managers


Objectives:
 To understand the Layout Manger in order to set layout of different Containers i.e. JFrame etc.

Theoretical Description:
1. Use of FlowLayout to load JButtons dynamically .
2. Use of BorderLayout
3. Use of Gridlayout for gradient display

Lab Task(s):
//FlowLayout
import javax.swing.*;
import java.awt.*;
public class Statics1 {
public static void main(String[] args) {
new S1GUI();
}
}
class S1GUI {
private JFrame f;
public S1GUI() {
f = new JFrame("Statics1");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500, 200);
f.setLayout(new FlowLayout(FlowLayout.LEFT));
for (int b = 1; b < 9; b++)
f.add(new JButton("Button " + b));
f.setVisible(true);
}
}

//Border Layout
import javax.swing.*;
import java.awt.*;
12
BS (Computer Science) 2023

public class Statics2 {


public static void main(String[] args) { new S2GUI(); }
}
class ColoredJPanel extends JPanel {
Color color;
ColoredJPanel(Color color) {
this.color = color;
}
public void paintComponent(Graphics g) {
g.setColor(color);
g.fillRect(0, 0, 400, 400);
}
}
class S2GUI extends JFrame {
public S2GUI() {
setTitle("Statics2");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
add(new ColoredJPanel(Color.RED), BorderLayout.NORTH);
add(new ColoredJPanel(Color.GREEN), BorderLayout.SOUTH);
add(new ColoredJPanel(Color.BLUE), BorderLayout.WEST);
add(new ColoredJPanel(Color.YELLOW), BorderLayout.EAST);
add(new ColoredJPanel(Color.BLACK), BorderLayout.CENTER);
setVisible(true);
}
}

13
BS (Computer Science) 2023

//Grid Layout Manager


import javax.swing.*;
import java.awt.*;
public class Statics3 {
public static void main(String[] args) { new S3GUI(); }
}
class S3GUI extends JFrame {
static final int DIM = 25;
static final int SIZE = 12;
static final int GAP = 1;
public S3GUI() {
setTitle("Statics3");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(DIM, DIM, GAP, GAP));
for (int i = 0; i < DIM * DIM; i++) add(new MyPanel());
pack();
setVisible(true);
}

class MyPanel extends JPanel {


MyPanel() { setPreferredSize(new Dimension(SIZE, SIZE)); }
public void paintComponent(Graphics g) {
float gradient =
1f - ((float)Math.abs(getX() - getY()))/(float)((SIZE + GAP) * DIM);
g.setColor(new Color(0f, 0f, gradient));
g.fillRect(0, 0, getWidth(), getHeight());
}
}
}

14
BS (Computer Science) 2023

LAB 8: Database Connectivity->insert Query


Objectives:

 To Learn Database Connectivity, SQL Insert query

Theoretical Description:
Design a Form in netbeans to insert information of a student. Write code behind the button to connect with
database, write query and then execute it.
Lab Task(s):
StudentForm.java
public void btnInsertActionPerformed(ActionEvent e)
{
String reg_num = tfregNum.getText();
String name = tfName.getText();
String cell_num = tfCellNum.getText();
String adrs = tfAdrs.getText();

String query ="INSERT INTO Student VALUES('"+reg_num+"','"+name+"','"+cell_num+"','"+ adrs+"')";

try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:Driver={MicroSoft Access Driver
(*.mdb)};DBQ=C:\\JavaProjects\\dbName");
Statement stmt = conn.createStatement();
stmt.execute(query);
conn.close();
JOptionPane.showMessageDialog(null,"INSERTED SUCCESSFULLY");
}
catch(java.lang.ClassNotFoundException ex)
{
JOptionPane.showMessageDialog(null,"Exception Occured"+ex.getMessage());
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"Exception Occured"+ex.getMessage());
}
}

Output:

15
BS (Computer Science) 2023

LAB 9: Database Connectivity, SQL Update and Select query


Objectives:
 To Learn Database Connectivity, SQL Update and Select query

Theoretical Description:
Design a Form in netbeans to Search on the basis of registration number and fill remaining information of a
student. Also provide functionality to update record Write code behind the button to connect with database,
write query and then execute it.
Lab Task(s):
StudentForm.java

public void btnSearchActionPerformed(ActionEvent e)


{
String reg_num = tfregNum.getText();
String query = "SELECT * FROM Student WHERE stdRegNum='"+reg_num+"'";
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:Driver={MicroSoft Access Driver
(*.mdb)};DBQ=C:\\JavaProjects\\dbName");
Statement stmt = conn.createStatement();
stmt.execute(sql);
ResultSet rs = stmt.getResultSet();
boolean recordfound = rs.next();
if (recordfound){
tfregNum.setText(rs.getString("stdRegNum"));
tfName.setText(rs.getString("stdName"));
tfCellNum.setText(rs.getString("stdCellNum"));
tfAdrs.setText(rs.getString("stdAdrs"));
}
else{
JOptionPane.showMessageDialog(null,"Record Not Found");
}
conn.close();
} catch(java.lang.ClassNotFoundException ex){
JOptionPane.showMessageDialog(null, ex.getMessage() }
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage() }
}

// Update Student Records

public void btnUpdateActionPerformed(ActionEvent e)


{
String reg_num = tfregNum.getText();
String name = tfName.getText();
String cell_num = tfCellNum.getText();
String adrs = tfAdrs.getText();

String query ="UPDATE Student set stdname='"+name+"', stdCellNum='"+cell_num+"', stdAdrs='"+ adrs+"'


WHERE stdRegNum='"+reg_num+"'";

try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

16
BS (Computer Science) 2023

Connection conn = DriverManager.getConnection("jdbc:odbc:Driver={MicroSoft Access Driver


(*.mdb)};DBQ=C:\\JavaProjects\\dbName");
Statement stmt = conn.createStatement();
stmt.execute(query);
conn.close();
JOptionPane.showMessageDialog(null,"UPDATED SUCCESSFULLY");
}
catch(java.lang.ClassNotFoundException ex)
{
JOptionPane.showMessageDialog(null,"Exception Occured"+ex.getMessage());
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"Exception Occured"+ex.getMessage());
}
}

Output:

17
BS (Computer Science) 2023

LAB 10: GUI/Database Connectivity using layered Architecture


Objectives:

 To Learn Database Connectivity using separate class/ layered Architecture, SQL insert, Update and Selec
query

Theoretical Description:
Create new class DbConn containing a connection string and a single function to insert, update and delete
records. It takes query as input and return boolean. Create another function in DbConn to search records that
returns the ResultSet.Design a Form in netbeans to Search on the basis of registration number and fill
remaining information of a student. Also provide functionality to update record Write code behind the button
to connect with database, write query and then execute it.
Lab Task(s):
DbConn.java
import java.sql.*;
public class DbConn {
public static String connString="jdbc:odbc:Driver={MicroSoft Access Driver
(*.mdb)};DBQ=C:\\JavaProjects\\dbName";

public boolean UDI(String query) {


try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection(DbConn.connString);
Statement stmt = conn.createStatement();
stmt.execute(query);
conn.close();
return true;
}
catch(java.lang.ClassNotFoundException ex) {
return false;}
catch(Exception ex){
return false; }
}

public ResultSet Search(String query)


{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection(DbConn.connString);
Statement stmt = conn.createStatement();
stmt.execute(query);
ResultSet rs=stmt.getResultSet();
return rs;
} catch(java.lang.ClassNotFoundException ex){
JOptionPane.showMessageDialog(null, "Exception Occured"+ex.getMessage());}
catch(Exception ex){
JOptionPane.showMessageDialog(null, "Exception Occured"+ex.getMessage());
}
return null;
}
}
StudentForm.java

18
BS (Computer Science) 2023

public void btnSearchActionPerformed(ActionEvent e)


{
String reg_num = tfregNum.getText();
String query = "SELECT * FROM Student WHERE stdRegNum='"+reg_num+"'";
DbConn obj = new DbConn();
try{
ResultSet rs = obj.Search(query);
boolean recordfound = rs.next();
if (recordfound){
tfregNum.setText(rs.getString("stdRegNum"));
tfName.setText(rs.getString("stdName"));
tfCellNum.setText(rs.getString("stdCellNum"));
tfAdrs.setText(rs.getString("stdAdrs"));
}
else{
JOptionPane.showMessageDialog(null,"Record Not Found");
}
conn.close();
}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage() }
}

public void btnUpdateActionPerformed(ActionEvent e)


{
String reg_num = tfregNum.getText();
String name = tfName.getText();
String cell_num = tfCellNum.getText();
String adrs = tfAdrs.getText();

String query ="UPDATE Student set stdname='"+name+"', stdCellNum='"+cell_num+"', stdAdrs='"+ adrs+"'


WHERE stdRegNum='"+reg_num+"'";

DbConn obj = new DbConn();


boolean r=obj.UDI(query);
if (r==true)
JOptionPane.showMessageDialog(null, "Updated Successfuly");
else
JOptionPane.showMessageDialog(null, "Could Not Update");
}
Output:

19
BS (Computer Science) 2023

LAB 11: GUI/Database Connectivity using layered Architecture


Objectives:

 To Learn Database Connectivity using separate class/ layered Architecture, SQL insert, Update and Selec
query
 JCombobox, JTextField, JButton etc.

Theoretical Description:
Create DbConn class like in task 8. Get a list of products from database table and display it in Combo box in
Sales Form on Window Opened Event. Provide the functionality to select the product from combo box and
display the stock and unit price from Product table in database. Subtract the number of items sold from the
stock and then update the stock in Product table. Finally insert sales record in Sales table.
Lab Task(s):
DbConn.java
import java.sql.*;
public class DbConn {
public static String connString="jdbc:odbc:Driver={MicroSoft Access Driver
(*.mdb)};DBQ=C:\\JavaProjects\\dbName";

public boolean UDI(String query) {


try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection(DbConn.connString);
Statement stmt = conn.createStatement();
stmt.execute(query);
conn.close();
return true;
}
catch(java.lang.ClassNotFoundException ex) {
return false;}
catch(Exception ex){
return false; }
}

public ResultSet Search(String query)


{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection(DbConn.connString);
Statement stmt = conn.createStatement();
stmt.execute(query);
ResultSet rs=stmt.getResultSet();
return rs;
} catch(java.lang.ClassNotFoundException ex){
JOptionPane.showMessageDialog(null, "Exception Occured"+ex.getMessage());}
catch(Exception ex){
JOptionPane.showMessageDialog(null, "Exception Occured"+ex.getMessage());
}
return null;
}
}
SalesForm.java
DbConn obj = new DbConn();
20
BS (Computer Science) 2023

private void formWindowOpened(java.awt.event.WindowEvent evt)


{
String query ="SELECT prdTitle FROM product";
try{
rs = obj.Search(query);
while (rs.next())
{
cmbtitle.addItem(rs.getString("prdTitle").toString());
}
}catch(Exception ex){
JOptionPane.showMessageDialog(null,"Exception Occured"+ex.getMessage());}
}

private void cmbtitleActionPerformed(java.awt.event.ActionEvent evt) {


String query = "SELECT * FROM product WHERE prdTitle = '"+cmbtitle.getSelectedItem().toString()+"'";
ResultSet rs = obj.Search(query);
try {
while (rs.next())
{
tfprice.setText(rs.getString("unitprice"));
tfstock.setText(rs.getString("stock"));
}
}
catch (SQLException ex ) {
JOptionPane.showMessageDialog(null, "Exception Occured"+ex.getMessage());
}
}

public void btnSalesActionPerformed(ActionEvent e)


{
int stock = Integer.parseInt(tfstock.getText());
int qty = Integer.parseInt(tfqnt.getText());
if (qty<=stock)
{
int id = Integer.parseInt(tfid.getText());
String title = cmbtitle.getSelectedItem().toString();
int quantity = Integer.parseInt(tfqnt.getText());
float price = Float.parseFloat(tfprice.getText());
String soldby = cmbsold.getSelectedItem().toString();
String date = tfdate.getText();
float total = price*quantity;

int NewStock = stock - qty;


String query2 = "UPDATE product SET stock="+NewStock+" WHERE title= '"+ title +"'";
if (obj.UDI(query2) == true)
{
String query = "INSERT INTO Sales VALUES('"+id+"', '"+title+"', "+quantity+", '"+soldby+"',
"+total+", '"+date+"')";
if (obj.UDI(query) == true)
JOptionPane.showMessageDialog ("Successful Transaction");
else
JOptionPane.showMessageDialog(null, "Exception Occured"+ex.getMessage());
}
else
JOptionPane.showMessageDialog(null, "Exception Occured"+ex.getMessage());
}
}

21
BS (Computer Science) 2023

Output:

22
BS (Computer Science) 2023

LAB 12: GUI/ layered Architecture/JTable


Objectives:

 JTable, ResultSet

Theoretical Description:
Create a class DbConn. Design a Form in netbeans to view all records from database table and fill data in
JTable on Product form.
Lab Task(s):
DbConn.java

ProductForm.java
Private void btnShowAllActionPerformed(java.awt.event.ActionEvent evt) {
String title=cmbtitle.getSelectedItem().toString();
String query = "Select * from Product Where prdTitle='" + title + "'";
try {
ResultSet rs = obj.Search(query);
while(rs.next()) {
for(int j=1; j<=8;j++)
{
prdTable.setValueAt(rs.getString(j).toString(),i, j-1);
}
i++;
}
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Exception Occured" + ex.getMessage());
}
}

Output:

23

You might also like