Tuesday, 20 January 2015

Contact List Application with Java Swing


Contact List Application with Java Swing


Description : Our goal is to create simple desktop application using java swing which displays a form of Add User with a few textbox and a submit button as displayed in below image. when submit button is clicked values will be stored in database table. Pop-up with operation success or failed message will be displayed. On successfully save of information Jasper Report in PDF will be displayed with the list of user information.


(welcome screen when application started)

(When clicked on Register button after filling the form)

when clicked on yes new blank form will be displayed. when clicked on No Button PDF file for user list will opens as displayed in below image.

1. First create database table named `userinfo` in MySQL with below query.
CREATE TABLE `userinfo` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `firstname` varchar(45) NOT NULL,
  `lastname` varchar(45) NOT NULL,
  `email` varchar(45) NOT NULL,
  `username` varchar(45) NOT NULL,
  `password` varchar(45) NOT NULL,
  PRIMARY KEY  (`id`)
);

2. Create a Java Application named JasperDemo in netbeans. Create a java class named JasperDemo.java which contains a main method. This main method will be starting point of our application. Use below code.

public class JasperDemo {

    public static void main(String[] args) {
       new AddUser();
    }
}


3. Create java class named AddUser. This class works as welcome screen which displays Add User form.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class AddUser extends JFrame {
        JTextField textField = new JTextField("This is some text", 20);
 JLabel firstnameLabel = new JLabel("Firstname");
        JTextField firstname = new JTextField(20);
        JLabel lastnameLabel = new JLabel("Lastname");
        JTextField lastname = new JTextField(20);
        JLabel emailLabel = new JLabel("Email");
        JTextField email = new JTextField(20);
        JLabel usernameLabel = new JLabel("Username");
        JTextField username = new JTextField(20);
        JLabel passwordLabel = new JLabel("Password");
        JTextField password = new JTextField(20);
        JButton registerButton = new JButton("Register!");
        JButton button = new JButton("OK");
        
        User user = new User();
 
 public AddUser() {
            super("Demo program for JTextField");
            setLayout(null);

        firstnameLabel.setBounds(10, 10, 80, 25);
        firstname.setBounds(100, 10, 160, 25);
        lastnameLabel.setBounds(10, 40, 80, 25);
        lastname.setBounds(100, 40, 160, 25);
        emailLabel.setBounds(10, 70, 80, 25);
        email.setBounds(100, 70, 160, 25);
        username.setBounds(100, 100, 160, 25);
        usernameLabel.setBounds(10, 100, 80, 25);
        passwordLabel.setBounds(10, 130, 80, 25);
        password.setBounds(100, 130, 160, 25);
        registerButton.setBounds(100, 160, 100, 25);

        //adds key event listener
        textField.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent event) {
                String content = firstname.getText();
                if (!content.equals("")) {
                    registerButton.setEnabled(true);
                } else {
                    registerButton.setEnabled(false);
                }
            }
        });

        // adds action listener for the button
        registerButton.addActionListener(new ActionListener() {
            //Logic for saving user
            @Override
            public void actionPerformed(ActionEvent event) {

                user.setFirstname(firstname.getText());
                user.setLastname(lastname.getText());
                user.setEmail(email.getText());
                user.setUsername(username.getText());
                user.setPassword(password.getText());
                UserDao dao = new UserDao();
                String status = dao.save(user);
                String msg = "";
                if (status.equals("success")) {
                    msg = "Successfully Saved Contact";
                    int confirmed = JOptionPane.showConfirmDialog(null,
                            msg + " Do you want to add other user?", "Exit Program Message Box",
                            JOptionPane.YES_NO_OPTION);
                    if (confirmed == JOptionPane.NO_OPTION) {
                        dispose();
                        new SimpleReport();
                    } else {
                        firstname.setText("");
                        lastname.setText("");
                        email.setText("");
                        username.setText("");
                        password.setText("");
                    }
                } else {
                    msg = "Contact Saving Failed. Try Again Later";
                    JOptionPane.showMessageDialog(AddUser.this, msg);
                }
            }
        });
        add(firstnameLabel);
        add(firstname);
        add(lastnameLabel);
        add(lastname);
        add(emailLabel);
        add(email);
        add(usernameLabel);
        add(username);
        add(passwordLabel);
        add(password);
        add(registerButton);
        setSize(350, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }
}

  • In the above code swing frame with text-boxes and Register button is displayed. On Register button listener is added. When Register button is clicked, implemented actionPerformed method will be executed which stores the values in database table `userinfo`. Code for model class User and code for DAO class UserDao for database operation are displayed below. 

  • After data stored in database table success or failed message will be displayed in pop-up dialog as displayed in image. In pop-up dialog, if 'Yes' button is clicked new empty form will be displayed. If 'No' button is clicked PDF report of all user list from database table will be displayed.

  •  Code for Jasper Report format and displaying report is displayed below.

Model class User

public class User {
    private String firstname;
    private String lastname;
    private String email;
    private String username;
    private String password;
    private int id;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

DAO Class UserDao

import java.sql.*;
import java.sql.*;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class UserDao {
    Statement stmt = null;
    public static Connection getConnection() {
        Connection con = null;
        String driver = "com.mysql.jdbc.Driver";
        String db = "jdbc:mysql://localhost:3306/test";
        String username = "root";
        String password = "root";
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(db, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return con;
    }
    public String save(User user) {
        try {
            String query = "INSERT INTO userinfo(firstname, lastname, email, username, password) VALUES(?,?,?,?,?)";
            Connection con = getConnection();
            PreparedStatement pstmt = con.prepareStatement(query);
            pstmt.setString(1, user.getFirstname());
            pstmt.setString(2, user.getLastname());
            pstmt.setString(3, user.getEmail());
            pstmt.setString(4, user.getUsername());
            pstmt.setString(5, user.getPassword());
            pstmt.execute();
            return "success";
        } catch (SQLException ex) {
            Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
            return "fail";
        }
    }
    public List getData() {
        Connection con = getConnection();
        ArrayList al = new ArrayList();
        try {
            String query = "SELECT * FROM userinfo";
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt(1));
                user.setFirstname(rs.getString(2));
                user.setLastname(rs.getString(3));
                user.setEmail(rs.getString(4));
                user.setUsername(rs.getString(5));
                user.setPassword(rs.getString(6));
                al.add(user);
            }
        } catch (SQLException ex) {
            Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        return al;
    }
}
Jasper Report Format

  • Copy below code for the jasper report format. I am using iReport to create jasper report. 




	
	
	
	
		
	
	
		
	
	
		
	
	
	
	
	
	
	
	
		
			
				
				
					
				
				
			
			
				
				
					
				
				
			
			
				
				
					
				
				
			
			
				
				
					
				
				
			
			
				
				
					
				
				
			
			
				
				
					
				
				
			
		
	
	
		
			
				
				
				
			
			
				
				
				
			
			
				
				
				
			
			
				
				
				
			
			
				
				
				
			
			
				
				
				
			
		
	
	
		
			
				
				
				
			
		
	

No comments:

Post a Comment