Java Programming II - Lab Report (Hari Rijal)
Java Programming II - Lab Report (Hari Rijal)
com
1. Write a Simple Applet program to print "Welcome to Applet".
//AppletBook.java
import java.applet.Applet;
import java.awt.Graphics;
public class AppletBook extends Applet{
public void paint (Graphics g){
g.drawString("Welcome to Applet", 150, 150);
}
}
Output:
2. Create an applet that reads the parameter supplied from the <param> tag and display the
parameter value. Also create a suitable HTML file.
//MyApplet.java
import javax.swing.*;
public class MyApplet extends JApplet {
JPanel panel;
JButton b1;
JLabel label;
public void init(){
panel=new JPanel();
getContentPane().add(panel);
b1=new JButton("Click Me");
setVisible(true);
setSize(200,200);
panel.add(b1);
}
public void start(){
String str =getParameter("city");
label=new JLabel(str);
panel.add(label);
}
public void stop(){
}
public void destroy(){
System.out.println("Appplet Destroying...");
}
}
1|Page
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
//MyApplet.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<applet code="MyApplet.class" height="400" width="200">
<param name="city" value="Kathmandu">
</applet>
</body>
</html>
Output:
add(lab);
setSize(300,300);
setLayout(new GridLayout(2,1));
}
public void start(){
t1.addKeyListener(this);
}
public void keyTyped(KeyEvent e){}
public void keyPressed(KeyEvent e){}
2|Page
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
public void keyReleased(KeyEvent e){
String a=t1.getText();
if(a.length()==5){
lab.setText(a+" is of length 5");
}
else{
lab.setText(a+" is not of length 5");
}
}
}
Output:
public FileDialogDemo(){
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("File");
menuBar.add(menu);
JFrame frame = new JFrame();
JPanel panel = new JPanel();
// Image icon =
Toolkit.getDefaultToolkit().getImage("D:\\JavaProject\\JavaApplication1\\src\\notepad.jpg");
JTextArea txtArea = new JTextArea(DEFAULT_HEIGHT, DEFAULT_WIDTH);
frame.add(panel);
panel.add(txtArea);
3|Page
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
menu.add(newItem);
menu.add(openItem);
menu.add(saveItem);
menu.add(exitItem);
while(true){
String line = br.readLine();
if(line != null){
System.out.println(line);
4|Page
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
} else{
br.close();
break;
}
}
} catch(FileNotFoundException ex){
System.out.println("Error: " + ex.getMessage());
} catch(IOException ex){
System.out.println("Error: " + ex.getMessage());
}
}
});
while(true){
String line = br.readLine();
if(line != null){
System.out.println(line);
} else{
br.close();
break;
}
}
} catch(FileNotFoundException ex){
System.out.println("Error: " + ex.getMessage());
} catch(IOException ex){
System.out.println("Error: " + ex.getMessage());
}
}
});
newItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JTextArea txtArea = new JTextArea(DEFAULT_HEIGHT, DEFAULT_WIDTH);
panel.add(txtArea);
throw new UnsupportedOperationException("Not supported yet."); //To change body of
generated methods, choose Tools | Templates.
}
});
newItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tx.setText("");
}
});
//code for save item
saveItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showConfirmDialog(rootPane, "Do you want to save ?");
chooser.setCurrentDirectory(new File("/home"));
int result = chooser.showSaveDialog(FileDialogDemo.this);
if(result==JFileChooser.APPROVE_OPTION){
File fileToSave =chooser.getSelectedFile();
try{
FileWriter fw = new FileWriter(fileToSave);
fw.write(tx.getText());
fw.flush();
}
catch(Exception ex){
ex.printStackTrace();
}
}
System.out.println("Result"+result);
}
});
//code for cut
cutItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cutItem.addActionListener(this);
if(e.getSource()==cutItem)
tx.cut();
throw new UnsupportedOperationException("Not supported yet."); //To change body of
generated methods, choose Tools | Templates.
}
});
//code for copy
6|Page
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
copyItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
copyItem.addActionListener(this);
if(e.getSource()==copyItem)
tx.copy();
throw new UnsupportedOperationException("Not supported yet."); //To change body of
generated methods, choose Tools | Templates.
}
});
try{
7|Page
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
FileWriter fw = new FileWriter(fileToSave);
fw.write(tx.getText());
fw.flush();
}
catch(Exception ex){
ex.printStackTrace();
}
}
System.out.println("Result"+result);
}
});
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
setVisible(true);
setTitle("Note Pad");
Output:
System.out.println("Input value:"+inputValue);
int selection;
8|Page
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
selection = JOptionPane.showConfirmDialog(null, "Message", "Title",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
if(selection == JOptionPane.OK_OPTION){
System.out.println("Ok.....");
}
else{
System.out.print("Cancel...");
}
Object[]possibleValues={"First", "Second", "Third"};
Object selectedValue = JOptionPane.showInputDialog(null, "Choose One", "inputValue",
JOptionPane.INFORMATION_MESSAGE,null,possibleValues,possibleValues[0]);
System.out.println("Selected value:"+selectedValue.toString());
setSize(300,300);
setVisible(true);
}
public static void main(String args[]){
new SwingDialogDemo();
}
Output:
9|Page
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
//ComponentDemo.java
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class ComponentDemo {
public ComponentDemo(){
System.out.println("Sport is Checked:"+sportChk.getState());
System.out.println("Music is Checked:"+musicChk.getState());
courseChoice.addItem("BIM");
courseChoice.addItem("BSC.CSIT");
courseChoice.addItem("BBA");
courseChoice.addItem("BBM");
courseChoice.select(0);
panel.add(semList);
panel.add(scrollbar);
System.out.println("Selected Course:"+courseChoice.getSelectedItem());
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
frame.dispose();
10 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
}
});
}
public static void main(String args[]){
new ComponentDemo();
}
}
Output:
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new FlowLayout());
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new FlowLayoutDemo();
}
11 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
}
Output:
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
Output:
12 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
import javax.swing.*;
public class GridBagLayoutExample extends JFrame{
public static void main(String[] args) {
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample() {
GridBagLayout grid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
13 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Output:
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);
c.add("b",b2);
c.add("c",b3);
}
public void actionPerformed(ActionEvent e){
card.next(c);
}
public static void main(String[] args) {
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
14 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output:
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener {
Button b1;
Label l;
MouseListenerExample(){
b1 = new Button ("Click Me");
b1.setBounds(50,50,80,50);
l = new Label();
l.setBounds(60,80,100,100);
b1.addMouseListener(this);
add(b1);
add(l);
setLayout(null);
setSize(300,300);
setVisible(true);
@Override
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
@Override
15 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
public void mousePressed(MouseEvent e) {
l.setText("Mouse pressed");
}
@Override
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
@Override
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
@Override
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public static void main(String args[]){
new MouseListenerExample();
}
Output:
}
public void windowClosing(WindowEvent we){
16 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
JOptionPane.showMessageDialog(frame,"Good Byeeeee.........");
System.exit(1);
}
public void windowOpened(WindowEvent we){
JOptionPane.showMessageDialog(frame,"Wel-Come");
}
public void windowIconified(WindowEvent we){
JOptionPane.showMessageDialog(frame,"See You Later...........");
}
public void windowDeiconified(WindowEvent we){
JOptionPane.showMessageDialog(frame, "Wel-Come Back.........");
}
public static void main(String args[]){
new WindowEventTest();
}
}
Output:
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
17 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
Label bankName = new Label("ABC Bank");
btnSave.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
String deposit = depositValue.getText();
// int deposit_result = Integer.parseInt(deposit);
18 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
});
frame.add(panel);
}
public static void main(String[] args) {
new BankSoftwareDemo();
}
}
Output:
14. Write a Java program to insert the data in database. Make your own assumptions about
the database and table.
//InsertionDemo.java
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 100);
ps.setString(2, "Hari Rijal");
ps.setString(3, "1997-08-02");
19 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
ps.setString(4,"[email protected]");
ps.executeUpdate();
System.out.println("Insertion success.");
}
}
Output:
15. Write a Java program to display the data from table BIM. Make your own assumptions
about the database.
//Display.java
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class Display {
public static void main (String args[]) throws ClassNotFoundException, SQLException{
Statement stmt;
ResultSet rs;
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Driver loaded");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/asian?useUnicode=true&useJDBCCompliantT
imezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","");
System.out.println("connection to mysql");
stmt = con.createStatement();
String sql ="select * from bim";
rs = stmt.executeQuery(sql);
while(rs.next()){
System.out.println("ID:"+rs.getString("ID"));
System.out.println("Name"+rs.getString("Name"));
System.out.println("DOB:"+rs.getString("DOB"));
System.out.println("Email:"+rs.getString("Email"));
}
}
}
Output:
20 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
16. Write a Java program to update the data from table BIM and set the name Karan whose id
is 101. Make your own assumptions about the database.
//UpdateDemo.java
package database;
import java.sql.*;
public class UpdateDemo {
public static void main (String args[]) throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Driver loaded");
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost/asian?useUnicode=true&useJDBCCompliantT
imezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","");
System.out.println("Connecton sucess");
String sql = "update bim set NAME = ? where ID =?";
Output:
17. Write a Java program to delete the details from table BIM whose id is 2. Make your own
assumptions about the database.
//DeleteDemo.java
package database;
import java.sql.*;
public class DeleteDemo {
public static void main (String args[]) throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Driver loaded");
21 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost/asian?useUnicode=true&useJDBCCompliantT
imezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","");
preparedStatement.setInt(1,2);
preparedStatement.executeUpdate();
System.out.println("Item was droped");
}
}
Output:
//SetSession.java
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
//ReadSession.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
//web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>SetSession</servlet-name>
<servlet-class>SetSession</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SetSession</servlet-name>
<url-pattern>/SetSession</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ReadSession</servlet-name>
<servlet-class>ReadSession</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ReadSession</servlet-name>
<url-pattern>/ReadSession</url-pattern>
</servlet-mapping>
<session-config>
23 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
Output:
pw.close();
}
catch(Exception ex){
System.out.println(ex);
}
}
}
//web.xml
<servlet>
<servlet-name>SetCookie</servlet-name>
<servlet-class>SetCookie</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SetCookie</servlet-name>
<url-pattern>/SetCookie</url-pattern>
</servlet-mapping>
Output:
24 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
Output:
21. Write a JSP program to add two numbers if they are even, if numbers are not even just display
their numbers.
//CheckNumber.html
<body>
<form action="CheckNumber.jsp" method="GET">
First Number: <input type="number" name="first">
Second Number: <input type="number" name="second">
<input type="submit" value=" Add">
</form>
</body>
//CheckNumber.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
25 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
<body>
<%
int x= Integer.parseInt(request.getParameter("first"));
int y = Integer.parseInt(request.getParameter("second"));
else{
out.println("Both the number are not even and entered numbers are:"+x+"and "+y+"");
}
%>
</body>
</html>
Output:
</head>
<body>
<%
for(int i = 1; i <= 8; i++) {
out.println("Apache Tomcat <br />");
}
%>
</body>
</html>
Output:
23. Create a HTML document that contains header information of a page and include this HTML as a
header file in header.html.
//header.html
<!DOCTYPE html>
<html>
26 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
<head>
<title>Insert title here</title>
</head>
<body>
<center>
<h1>Asian School of Management and Technology</h1>
<h3>Gongabu, Kathmandu</h3>
</center>
</body>
</html>
//headerinclude.jsp
<html>
<body>
<%@include file = "header.html" %>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua.
</p></body>
</html>
Output:
24. Create a JSP that takes an integer from HTML and display its reverse.
//Reverse.html
<html>
<body>
<form action = "Reverse.jsp">
Enter a number: <input type = "number" name = "number" />
<input type = "submit" value="Go" />
</form>
</body>
</html>
//Reverse.jsp
<html>
<body>
<%
int num = Integer.parseInt(request.getParameter("number"));
int rev = 0, rem;
while(num > 0){
rem = num % 10;
rev = rem + rev * 10;
num = num / 10;
}
27 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)
www.studynotesnepal.com
out.println("Reverse is: "+rev);
%>
</body>
</html>
Output:
<html>
<head>
<title>JSP useBean</title>
</head>
<body>
<jsp:useBean id="date" class="java.util.Date"/>
<p> The Date / Time is <%=date %></p>
</body>
</html>
Output:
//error.jsp
<%@page isErrorPage="true" %>
<h3>Sorry an exception occured ! </h3>
Exception is : <%= exception.getMessage() %>
Output:
28 | P a g e
Prepared By: Hari Rijal (Study Notes Nepal)