• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
projectsgeek

ProjectsGeek

Download Mini projects with Source Code, Java projects with Source Codes

  • Home
  • Java Projects
  • C++ Projects
  • VB Projects
  • PHP projects
  • .Net Projects
  • NodeJs Projects
  • Android Projects
    • Project Ideas
      • Final Year Project Ideas
      • JSP Projects
  • Assignment Codes
    • Fundamentals of Programming Language
    • Software Design Laboratory
    • Data Structure and Files Lab
    • Computer Graphics Lab
    • Object Oriented Programming Lab
    • Assembly Codes
  • School Projects
  • Forum

Java Assignments

Creating a PDF file using Java code

August 2, 2015 by ProjectsGeek Leave a Comment

Creating a PDF file using Java code

 

We will use the iText API for creating a pdf file using java code. Its a open source java API for creating pdf files, But if you are planning to use this iText API for commercial purpose you need to buy a licence for it. You can download this iText API from below link.

Download iText API

You can create pdf documents, XML files, HTML as well as RTF documents using this API. Lots of customization are there in this iText API which allows users create paragraphs, applying different fonts, adding images to pdf files, adding watermarks to pdf documents etc.

Steps to be followed for creating a PDF Document

  • Create a document using com.itextpdf.text.Document class of iText API.
  • Now create a PdfWriter using com.itextpdf.text.pdf.PdfWriter.
  • Open the document and start writing text to it.
  • After writing content to it, close the document as well as writer.

Below is the Snapshots for Application using Java swings:

create a pdf using java

Here user will enter the details on the UI form of member application. We have one button also which will be used to create pdf file in the location we have provided.

create a pdf file

In this snapshots you can see the user has entered all the details. [Note] We are considering date field as the string only.


 

Now moving on to source code of this small application:

 

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.projectsgeek;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 *
 * @author Projectsgeek
 */
public class MainWindow extends javax.swing.JFrame implements ActionListener{

    /**
     * Creates new form MainWindow
     */
    public MainWindow() {
        initComponents();
        this.setTitle("Create a PDF File Demo");
        jButton1.addActionListener(this);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jTextField5 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(500, 500));

        jLabel1.setText("Name");

        jLabel2.setText("Create a PDF Application");

        jLabel3.setText("Gender");

        jLabel4.setText("Date of Birth");

        jLabel5.setText("Fathers Name");

        jLabel6.setText("Address");

        jButton1.setText("Create a PDF File");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)
                            .addComponent(jLabel5)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(99, 99, 99)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE)
                                .addComponent(jTextField3)
                                .addComponent(jTextField4)
                                .addComponent(jTextField5)))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 250, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jButton1)
                                .addGap(187, 187, 187))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(162, 162, 162))))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 49, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(42, 42, 42))
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see https://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainWindow().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    // End of variables declaration                   

    @Override
    public void actionPerformed(ActionEvent e) {
        
      Document document = new Document();
      try
      {
         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("d://MemberDetails.pdf"));
         document.open();
         document.add(new Paragraph("This is registration Page"));
         document.add(new Paragraph("Member Name:"+this.jTextField1.getText()));
         document.add(new Paragraph("Member Gender:"+this.jTextField2.getText()));
         document.add(new Paragraph("Member DOB:"+this.jTextField3.getText()));
         document.add(new Paragraph("Member Fathers:"+this.jTextField4.getText()));
         document.add(new Paragraph("Member Address:"+this.jTextField5.getText()));
         document.close();
         writer.close();
      } catch (DocumentException e2)
      {
         e2.printStackTrace();
      } catch (FileNotFoundException e1)
      {
         e1.printStackTrace();
      }
        
    }
}

Download the Source Code
Creating a PDF file using Java Code

Other Projects to Try:

  1. Copying Files using Java Code
  2. Communication between applet and servlet Java Code
  3. Creating SDI, MDI, Dialog Based Application
  4. Implement Conflation Algorithm using File Handling in Java
  5. To Perform File Handling in Java

Filed Under: Java Assignments, Java Tutorials Tagged With: java tutorial

Write a program in Java for student details (Roll No, Name etc) to Access as a database and write the application in JDBC. (AWT or JFame).

July 1, 2012 by ProjectsGeek Leave a Comment


Assignment No 05


AIM:


Write a program in Java that enters student details (Roll No, Name etc) and retrieves information. Use Access as a database and write the application in JDBC. (AWT or JFame)


THEORY:


JDBC stands for Java Database connectivity’s. It is a software layer that allows developers to write real client-server projects in Java. JDBC is based on the X/OPEN call level interface (CLI) for SQL. JDBC was designed to be a very compact, simple interface focusing on the execution of raw SQL statements and retrieving the results. The components of JDBC are Application, Driver manager and Driver.


JDBC   Vs ODBC


  • ODBC cannot be directly used with Java because it uses a C interface.

  • ODBC makes use of pointers which have been totally removed from Java.

  • ODBC mixes simple and advanced features together and has complex options for simple queries.

  • ODBC requires manual installation of the ODBC driver manager and driver on all client machines. JDBC drivers are written in Java and JDBC code is automatically installable, secure and portable on all java platforms from network computers to mainframes.


The JDBC API defines a set of interfaces and classes to be used for communications with a database. These interfaces and classes are found in the java.sql package. The results of the SQL statements are stored in ResultSet object and getXXX method used to retrieve the data from ResultSet. A transaction is set of one or more statements that are executed together as a unit, so either all of the statements are executed or none of the statement is executed.


DSN: Types of DSN


  • File DSN –  Accessibility is very low
  • System DSN – Easy to access and by all users.
  • User DSN –  Specific to a user but not portable.



Steps for using JDBC:


//step 1- import the java.sql package

import java.sql.*;

Class Customer {

public static void main(String arg[ ]) throws SQLException {


//step 2-register the driver

class.forName (”sun.jdbc.odbc.JdbcOdbcDriver”);


//step 3-connect to a database

Connection c= DriverManager.getConnection(“Jdbc.odbc:DSN”,”username”,”password”);


//step 4- create a statement

Statement s = c.createStatement( );


//step 5-execute the statement

Resultset rs = s.executeQuery (“ SQL statement”);


s.executeUpdate( ): This is used for all DDL command present in a database (ALTER, DROP, INSERT and CREATE ). This does not returns anything but executes the query and update the database.


s.execute( ): This method is used to execute an SQL statement that may return multiple returns The return value is a Boolean. Which is true if the next result is a Resultset and false if it is an update count or there are no more results.


//step 6- for displaying the column name

ResultSetMetaData rsmd =rs.getMetaData( );

int i =rsmd.getColumnCount( );

for(int j=i; j<=i; j++)

{

System.out.println( rsmd.getColumnName( j)+”\t”);

System.out.println(” ”);

}


//step 7-retrieve the results

while(rs.next( ) );

{

for(int j=i; j<=i; j++)

{

System.out.println( rs.getString( j)+”\t”);

}

System.out.println(” ”);

}


//step 8-close the statement and connection

s.close( );

c.close( );

}

}

A batch update is a set of multiple update statements that is a submitted to the database for processing as a batch. AddBatch, clearBatch and executeBatch are some of the methods that are used for batch updates. Two types of exceptions are thrown during batch updates and they include SQLException and BatchUpdateException.


 CONCLUSION


JDBC is successfully implemented. 

Other Projects to Try:

  1. Database connectivity in Java with MYSQL
  2. Program for taking Student details and storing in a database using Servlets and JSP.
  3. Multiple Inheritance in java program
  4. SQL and JDBC(Java Database Connectivity) in Java
  5. Write an Applet that crease a Working Version of Fifteen Puzzle in Java

Filed Under: Java Assignments

Write an Applet that crease a Working Version of Fifteen Puzzle in Java

July 1, 2012 by ProjectsGeek Leave a Comment

Assignment No 04


AIM:


Write an Applet that crease a working version of “fifteen puzzle”. The puzzle contains a grid with 4 rows and 4 columns. The cells are filled with 1 to 15 leaving one cell empty. On clicking the mouse on a cell adjacent to the empty cell, the number in the cell moves to the empty cell. The puzzle is completed when the user arranges the numbers in the cells in ascending order. (AWT and Applet)


 THEORY:

Steps:

1)    Draw 4 rows and columns in the puzzle. Also stores the width and height in pixels of each cell. Design an array of integers which represents the puzzle internally.

2)    This two dimensional array is filled with numbers between 1 to 15 randomly selected. One cell is left blank.

3)    On MousePressed() event, check whether the mouse was pressed inside the puzzle (grid), then the mouse co-ordinates are translated into rows and columns of the grid. Use swap() method which contains swapping code which is get called only and only when the cells adjacent to the cell in which mouse was clicked is blank.  


CONCLUSION


Applet containing puzzle is successfully implemented.



PROGRAM CODE

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class FifteenPuzzle implements ActionListener {

/* Dimension of the Board */
private static final int DIM = 4; // For N * N board DIM = N
/* Total number of cells in the board */
private static final int SIZE = DIM * DIM;
/* Win state */
final String[] WIN = new String[SIZE-1];
/* Initial Height of the board*/
private static final int HEIGHT = 400;
/* Initial Width of the board*/
private static final int WIDTH = 400;
/* Initial empty cell in the board*/
private int emptyCell = DIM * DIM;
/* 15 puzzle Board, of size (4 X 4)*/
private JButton[][] board = new JButton[DIM][DIM];
private JFrame frame;
private JPanel panel = new JPanel();

// Suppresses default constructor, ensuring non-instantiability.
public FifteenPuzzle() {

// Initialize the win state
for (int i = 1; i < SIZE; i++) {
WIN[i-1] = Integer.toString(i);
}

System.out.println("Win State:" + Arrays.asList(WIN) );
}

public static void main(String[] args) {
FifteenPuzzle game = new FifteenPuzzle();
game.initializeBoard(); /* Initializes the 15-puzzle game board */

}

/**
* Gives index value corresponding to [row,col] of a square
* @param i, row
* @param j, column
* @return the index of the corresponding to the row and column
*/
private int getIndex(int i, int j) {
return ((i * DIM) + j); // i * 4 + j

}

/**
* Generates the random initial state for the game.
* Assigns unique random number to each square
*/
private void initializeBoard() {
ArrayList intialList = new ArrayList(SIZE);

// Repeat until creation of solvable initial board
for (boolean isSolvable = false; isSolvable == false;) {

// create ordered list
intialList = new ArrayList(SIZE);
for (int i = 0; i < SIZE; i++) {
intialList.add(i, i);
}

// Shuffle the list
Collections.shuffle(intialList);

// Check list can be solvable or not
isSolvable = isSolvable(intialList);
}
System.out.println("Initial Board state:" + intialList);

// Assigns unique random number to each square
for (int index = 0; index < SIZE; index++) {
final int ROW = index / DIM; // row number from index
final int COL = index % DIM; // column number from index
board[ROW][COL] = new JButton(String.valueOf(intialList.get(index)));
// Initializes the empty square and hide it
if (intialList.get(index) == 0) {
emptyCell = index;
board[ROW][COL].setVisible(false);
}

// Decorating each square
board[ROW][COL].setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
board[ROW][COL].setBackground(Color.BLACK);
board[ROW][COL].setForeground(Color.GREEN);
board[ROW][COL].addActionListener(this);
panel.add(board[ROW][COL]);
}

// Initializes the Frame
frame = new JFrame("Shuffle Game");
frame.setLocation(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(HEIGHT, WIDTH);

// Initializes the panel
panel.setLayout(new GridLayout(DIM, DIM));
panel.setBackground(Color.GRAY);

// Initializes the content pane
java.awt.Container content = frame.getContentPane();
content.add(panel, BorderLayout.CENTER);
content.setBackground(Color.GRAY);
frame.setVisible(true);
}

/**
* Verifies the board for solvability.
* For more details of solvability goto URL:
* https://mathworld.wolfram.com/15Puzzle.html
* @param list, 16 elements from 0-15, no repetition of elements
* @return true, if the initial board can be solvable
* false, if the initial board can't be solvable
*/
private boolean isSolvable(ArrayList list) {

if(list.size() != 16)
{
System.err.println("isSolvable function works only" +
"with a list having 0-16 as values");
}

int inversionSum = 0; // If this sum is even it is solvable
for (int i = 0; i < list.size(); i++) {
// For empty square add row number to inversionSum
if (list.get(i) == 0) {
inversionSum += ((i / DIM) + 1); //add Row number
continue;
}

int count = 0;
for (int j = i + 1; j < list.size(); j++) {
// No need need to count for empty square
if (list.get(j) == 0) {
continue;
} else if (list.get(i) > list.get(j)) { // If any element greater
count++; // than seed increse the
} // inversionSum
}
inversionSum += count;
}

// if inversionSum is even return true, otherwise false
return ((inversionSum & 1) == 0) ? true : false;
}

/**
* If any button in the board is pressed, it will perform the
* required actions associated with the button. Actions like
* checking isAdjacent(), swapping using swapWithEmpty() and also
* checks to see whether the game is finished or not.
*
* @param event, event performed by the player
* @throws IllegalArgumentException, if the index = -1
*/
public void actionPerformed(ActionEvent event) throws IllegalArgumentException {
JButton buttonPressed = (JButton) event.getSource();
int index = indexOf(buttonPressed.getText());
if (index == -1) {
throw (new IllegalArgumentException("Index should be between 0-15"));
}
int row = index / DIM;
int column = index % DIM;

// If pressed button in same row or same column
makeMove(row, column);

// If the game is finished, "You Win the Game" dialog will appear
if (isFinished()) {
JOptionPane.showMessageDialog(null, "You Win The Game.");
}
}

/**
* Gives the index by processing the text on square
* @param cellNum, number on the button
* @return the index of the button
*/
private int indexOf(String cellNum) {

for (int ROW = 0; ROW < board.length; ROW++) {
for (int COL = 0; COL < board[ROW].length; COL++) {
if (board[ROW][COL].getText().equals(cellNum)) {
return (getIndex(ROW, COL));
}
}
}
return -1; // Wrong input returns -1

}

/**
* Checks the row or column with empty square
* @return true, if we pressed the button in same row or column
* as empty square
* false, otherwise
*/
private boolean makeMove(int row, int col) {
final int emptyRow = emptyCell / DIM; // Empty cell row number
final int emptyCol = emptyCell % DIM; // Empty cell column number
int rowDiff = emptyRow - row;
int colDiff = emptyCol - col;
boolean isInRow = (row == emptyRow);
boolean isInCol = (col == emptyCol);
boolean isNotDiagonal = (isInRow || isInCol);

if (isNotDiagonal) {
int diff = Math.abs(colDiff);

// -ve diff, move row left
if (colDiff < 0 & isInRow) {
for (int i = 0; i < diff; i++) {
board[emptyRow][emptyCol + i].setText(
board[emptyRow][emptyCol + (i + 1)].getText());
}

} // + ve Diff, move row right
else if (colDiff > 0 & isInRow) {
for (int i = 0; i < diff; i++) {
board[emptyRow][emptyCol - i].setText(
board[emptyRow][emptyCol - (i + 1)].getText());
}
}

diff = Math.abs(rowDiff);

// -ve diff, move column up
if (rowDiff < 0 & isInCol) {
for (int i = 0; i < diff; i++) {
board[emptyRow + i][emptyCol].setText(
board[emptyRow + (i + 1)][emptyCol].getText());
}

} // + ve Diff, move column down
else if (rowDiff > 0 & isInCol) {
for (int i = 0; i < diff; i++) {
board[emptyRow - i][emptyCol].setText(
board[emptyRow - (i + 1)][emptyCol].getText());
}
}

// Swap the empty square with the given square
board[emptyRow][emptyCol].setVisible(true);
board[row][col].setText(Integer.toString(0));
board[row][col].setVisible(false);
emptyCell = getIndex(row, col);
}

return true;
}

/**
* Checks where game is finished or not
* @return true, if the board is in final state
* false, if the board is not in final state
*/
private boolean isFinished() {
// Check 1-15 elements whether they are in right position or not
for (int index = WIN.length - 1; index >= 0; index--) {
String number = board[index / DIM][index % DIM].getText();
if (!number.equals(WIN[index])) {
return false; // If any of the index is not aligned

}
}
return true;
}
}
Write an Applet that crease a Working Version of Fifteen Puzzle in Java 1
Download Code Here

Other Projects to Try:

  1. Design and Develop features of Paint Brush application
  2. Text or Screen Editor in C++ Language
  3. Write a program in Java for student details (Roll No, Name etc) to Access as a database and write the application in JDBC. (AWT or JFame).
  4. Puzzle Game Project in Java
  5. Java Applet Tutorial for Beginners

Filed Under: Java Assignments

Design an applet that displays the string “Hello College Name” moving from left to right. When it reaches to right, it scrolls back to left.

July 1, 2012 by ProjectsGeek Leave a Comment

Assignment No 03


AIM:


A) Design an applet that displays the string “Hello AIT” moving from left to right. When it reaches to right, it scrolls back to left.


B) Design an applet that displays circle which grows outwards  (up to certain value) and finally it reduces to 0.


THEORY:


The abstract Windowing toolkit(AWT) is an API that is responsible for building the GUI. It is a part of JFC. Java programs are classified into two groups namely applications and applets. An applet is a dynamic and interactive program that can run inside a web page displayed by Java capable browser. This can be also executed using applet viewer application.

Some of the important tags used inside an applet .html file are


Major Applet activities are :


init() method gets called as soon as applet is started. Initialization of all variables, creation of objects, setting of parameters can be done in this method.  start() method is executed  after the init() method where the applet is started. stop() method is used to halt the running of an applet. destroy() method is used to free the memory occupied by the variables and objects initialized in the applet. Any cleaning up activity that needs to be performed can be done in this method. paint() method helps in drawing, writing and creating a colored background or an image onto the applet. It takes an argument, which is an instance of Graphics class. repaint() method is used in case an applet is to be repainted. The repaint() calls the update() method to clear the screen of any existing contents. The update() method in turn calls paint() method that then draws the contents of the current frame.


Methods in Graphics class are


g.drawBytes(byte[ ] data, int offset, int length, int x, int y)

g.drawChars(char[ ] data, int offset, int length, int x, int y)

g.drawString(String str, int x, int y)

g.drawLine( int x1, int y1, int x2, int y2)

g.drawRect( int x1, int y2, int width, int height)

g.fillRect( int x1, int y2, int width, int height)

g.drawRoundRect( int x1, int y2, int width, int height, int width1, int height1)

g.fillRoundRect( int x1, int y2, int width, int height, int width1, int height1)

g.drawOval( int x1, int y2, int width, int height)

g.fillOval( int x1, int y2, int width, int height)

g.draw3DRect( int x1, int y2, int width, int height, true/false)

g.drawPolygon( int xs[ ], int ys [ ] )

g.fillPolygon( int xs[ ], int ys [ ] )

g.drawArc(int x1, int y1, int width, int height, angle1, angle2)

g.fillArc(int x1, int y1, int width, int height, angle1, angle2)

g.drawImage(image img, int x, int y, int width, int height,  imageObserver)


Font class represents Fonts. Text can be written inside an applet using different fonts.

Constructor:

          Font f = new Font (string name, int style, int size);


Name: The logical name of the font.

Style: The style of the font as Font.BOLD, Font.ITALIC, Font.PLAIN

Size: The size of the font

For setting the font setFont(f) method present in a graphics class can be used.


Color class represents color. Color is represented as a combination of red, blue and green. Each component can have a number between 0 and 255. 0,0,0 is black and 255,255,255 is white.

Constructor:         

Color c = new Color(0,0,0);

Method:      

                   g.setColor( c)                 //can be used present in Graphics class.


Animation is the technique by which an object is moved on the screen. The object to be moved can be simple drawing or a complex image loaded from an image file. This object, in animation region is called a frame of animation.


CONCLUSION


Both applets are successfully implemented. 


PROGRAM CODE


import java.awt.*;
import java.applet.Applet;
public classmovingBall extends Applet implements Runnable {
Thread mythread = null;
int position =0;

public void start( )
{
mythread =new mythread (this); // this refers to current object
mythread.start( );
}

public void run( )
{
while(true)
{
for(position=o; position {
repaint();
try{ mythread.sleep(100); }
catch(InterruptedException e) { };
}
}
}

public void stop( )
{
mythread.stop( );
mythread=null;
}

public void paint(graphics g)
{
g.setColor(Color.gray);
g.fillOval(position,50,30,30);
g.setColor(Color.black);
g.fillOval(position+6,58,5,5);
g.drawLine(position,58,10,12);
}
}


Design an applet that displays the string “Hello College Name” moving from left to right. When it reaches to right, it scrolls back to left. 2

Download Code Here

Other Projects to Try:

  1. Java Applet Tutorial for Beginners
  2. Communication between applet and servlet Java Code
  3. How to convert String to int using Java
  4. To Perform various String Operation in Java
  5. Moving Balls mini project using Java Applet

Filed Under: Java Assignments

To Perform File Handling in Java

July 1, 2012 by ProjectsGeek Leave a Comment

                                      Assignment No 02

AIM: 


To perform file handling in Java. Take two filenames from user, check the file is present in c:\java folder, if not present, display the message “file not present” , else display the size and file name. Also display the file contents.

THEORY: 


Objects of the File class can be created using File Constructors.

Constructors:

File f1=new File(“c:/java/temp.txt “);
File f1 = new File( “c:/java”, “temp.txt “);
File f1 = new File( “java”, “temp.txt “);

Methods are : f.getName( );f.getPath( );f.getAbsolutPath( );f.getParent( );f.exists( ); f.isFile( ); f.isDirectory( );f.canRead( );f.canWrite( );f.lastModified( );f.length( );f.delete( ); f.renameTo(f1); f.list( ); f.mkdir( );

A stream is a path of communication between the source of information and the destination. Methods of InputStream/Reader are : read( );skip( );available( );close( );mark( );reset( ); Methods of OutputStream/ Writer are : write( );flush( );close( );

ByteArrayInputStream class uses a byte array as its input source.
ByteArrayInputStream b = new ByteArrayInputStream(buf [ ]);
ByteArrayOutputStream class implements a buffer, which can be used as an OutputStream
ByteArrayOutputStream o =new ByteArrayOutputStream( );

This creates a buffer of 32 bytes to store the data.
ByteArrayOutputStream o =new ByteArrayOutputStream( int );


RandomAccessFile class can be used for both input and output to a single file.

// rw for read & write mode while r for read only mode.

RandomAccessFile    rd = new RandomAccessFile (“      “,”rw”);

The seek ( ) method specifies the byte-offset from the beginning of the file.

Reader and write classes are used to read/write characters instead of bytes.

CONCLUSION:

File handling is successfully done in Java.



PROGRAM CODE



import java.io.*;
class prg {
public static void main( String arg [ ] ) throws IOException {
FileInputStream fi = new FileInputStream(“ “);
FileOutputStream fo = new FileOutputStream (“ “);
int size = fi.available( );
for( int i =0; i < size; i++ )
{
int m =fi.read( );
System.out.println( (char) m);
fo.write( m );
}
fo.close( );
fi.close( );
}

// using BuffredInputstream and BuffredOutputstream.
BuffredInputstream bi = new BuffredInputstream (fi);
BuffredOutputstream bo = new BuffredOutputStream( fo);
bo.flush( );

//using DataInputStream and DataOutputStream.
DataInputStream di = new DataInputStream( fi );
DataOutputStream do = new DataOutputStream( fo );

String line;
while( line =di.readLine( ) != null )
{
System.out.println(line);
do.writeBytes(line);
}

//using BufferedReader and BufferdWriter
BufferedReader br =new BufferedReader (new InputStreamReader (fi));
BufferedWriter bw =new BuffredOutputStream (new OutputStreamWriter (fo));

// using BuffredInputstream and BuffredOutputstream.
while (int a = System.in.read ()! = 13)
{
fo.write (a);
}

//using BufferedReader and DataOutputStream.
while (line=br.readLine! = null)
{
if (line. equals (“end”))
break;
else
{
String z;
do.writeBytes (z);
}
}

To Perform File Handling in Java 3

Download Code Here

Other Projects to Try:

  1. Socket programming in Java
  2. File Handling and IO Handling in Java Programming
  3. File Handling program using Java
  4. Implement Conflation Algorithm using File Handling in Java
  5. To Perform various String Operation in Java

Filed Under: Java Assignments

Socket programming in Java

September 9, 2011 by ProjectsGeek Leave a Comment

Socket programming in Java
Client Code

import java.io.*;
import java.net.*;
class Client_1
{
    public static void main (String[] args)
    {
        int port =6543;
        String add=”localhost”;
        try
        {
            InetAddress ia=InetAddress.getByName(add);
            Socket socket =new Socket(add,port);
            InputStream input=socket.getInputStream();
            OutputStream output=socket.getOutputStream();
            DataInputStream in=new DataInputStream(input);
            DataOutputStream out=new DataOutputStream(output);
            BufferedReader enter=new BufferedReader(new InputStreamReader(System.in));
            String line=null;
            while(true)
            {
                System.out.print(“Message to server : “);
                line=enter.readLine();
                out.writeUTF(line);
                out.flush();
                line=in.readUTF();
                System.out.println(“Message from server : ” + line);
            }
        }
        catch (Exception ex)
        {
        }
    }
}
 Server Code
import java.net.*;
import java.io.*;
class ser2 im
{

}
class Server_1
{
    public static void main (String[] args)
    {
        int port = 6543;
        try
        {
            ServerSocket ss = new ServerSocket(port);
            System.out.println(“Waiting for client:: “);
            Socket socket=ss.accept();
            System.out.println(“Client found… “);
            InputStream input=socket.getInputStream();
            OutputStream output=socket.getOutputStream();
            DataInputStream in=new DataInputStream(input);
            DataOutputStream out=new DataOutputStream(output);
            BufferedReader enter=new BufferedReader(new InputStreamReader(System.in));
            String line=null;
            while(true)
            {
                line=in.readUTF();
                System.out.println(“Message From Client::  “+line);
                System.out.print(“Message to Client : “);
                line=enter.readLine();
                out.writeUTF(line);
                out.flush();
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
}   

Other Projects to Try:

  1. To Perform File Handling in Java
  2. Implement Conflation Algorithm using File Handling in Java
  3. Exception Handling In java
  4. Implement using Socket Programming (TCP/UDP) in Java
  5. Java Programming from program analysis to program Design By -DS Malik

Filed Under: Java Assignments

  • Page 1
  • Page 2
  • Go to Next Page »

Primary Sidebar

Tags

.Net Projects Download Android Project Ideas Android Projects Angular 2 Assembly Codes C # Projects C & C++ Projects C++ Projects Class Diagrams Computer Graphics Database Project Data Mining Projects DataScience Projects Datastructure Assignments Download Visual Basic Projects Electronics project Hadoop Projects Installation Guides Internet of Things Project IOS Projects Java Java Interview Questions Java Projects JavaScript JavaScript Projects java tutorial JSON JSP Projects Mechanical Projects Mongodb Networking Projects Node JS Projects OS Problems php Projects Placement Papers Project Ideas Python Projects seminar and presentation Struts

Search this Website


Footer

Download Java Project
Download Visual Basic Projects
Download .Net Projects
Download VB Projects
Download C++ Projects
Download NodeJs Projects
Download School Projects
Download School Projects
Ask Questions - Forum
Latest Projects Ideas
Assembly Codes
Datastructure Assignments
Computer Graphics Lab
Operating system Lab
australia-and-India-flag
  • Home
  • About me
  • Contact Form
  • Submit Your Work
  • Site Map
  • Privacy Policy