Project 22-3: Manage customer data (GUI) Operation · This application begins by
ID: 3705341 • Letter: P
Question
Project 22-3: Manage customer data (GUI)
Operation
· This application begins by displaying a table of customer data.
· If the user clicks the Add button, the application allows the user to add customer data to the table (and the underlying database).
· If the user selects a customer row and clicks the Edit button, the application allows the user to update the data for the selected customer row in the table (and the database).
· If the user selects a customer row and clicks the Delete button, the application deletes the selected customer row from the table (and the database).
Specifications
· Create a table in the mma database described in chapter 19 to store the necessary data. To do that, you can use the SQL script stored in the create_customer_table.sql file that’s supplied. If this script isn’t supplied, you can create your own SQL script.
· Create a class named Customer that stores data for the user’s id, email address, first name, and last name.
· Create a class named CustomerDB that contains the methods necessary to get an array list of Customer objects, to get a Customer object for the customer with the specified id, and to add, update, or delete the specified customer.
· Create a CustomerManagerFrame class like the one shown above. This frame should display a table of customer data as well as the Add, Edit, and Delete buttons. This class should use the Customer and CustomerDB classes to work with the customer data.
· Create a CustomerForm class that allows the user to add or edit customer data.
141 Customer Manager Email frankjo johnsmith@hotmail.com seagreen@levi.com wendyk@warners.com First Name Frank John Cynthia Wendy Last Name ones Smith Green Kowolski nes@yahoo.com Add Edit DeleteExplanation / Answer
1.Create a new Project and select Java App
2.Rename Project Name to Customer
3.Delete file Customer.java
4.Add New JFrame Form under package Customer and change class Name to GUI
5.Drag and drop java Swing controller into frame. check the code in GUI given below and you can change the position of button based on your requirement.
6.Add new JFrame Form under package customer and change class name to AddEdit.
7.Drag and drop java swing controller into frame.
8.please create two Java Classes. Customer.java and CustomerUtility.java.
9.Copy and paste the code behind of each java class and java frame.
GUI code :
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/*
* 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.
*/
/**
*
* @author dd
*/
public class MainUserInterface extends javax.swing.JFrame {
/**
* Creates new form MainGUIInterface
*/
public MainUserInterface() {
initComponents();
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.addWindowListener(getWindowAdapter());
jTable1.getTableHeader().setFont(new java.awt.Font("Verdana", 0, 11));
//load customers into ArrayList
CustomerUtility.readCustomerCustomer();
//bind into JTable
BindIntoJTable();
}
//make public and for enable to access from another class
public static void BindIntoJTable() {
//clear jTable First
jTable1.removeAll();
List<Customer> AllCustomer = CustomerUtility.getAllCustomer();
if (AllCustomer != null) {
int index = 1;
String colNames[] = {"No","Name", "Customer No", "Email Address"};
DefaultTableModel dtm = new DefaultTableModel(null, colNames);
for (int i = 0; i < AllCustomer.size(); i++) {
dtm.addRow(new String[4]);
}
jTable1.setModel(dtm);
if (AllCustomer.size() > 0) {
int row = 0;
for (Customer c : AllCustomer) {
jTable1.setValueAt(Integer.toString(index), row, 0);
jTable1.setValueAt(c.getName(), row, 1);
jTable1.setValueAt(c.getPhoneNo(), row, 2);
jTable1.setValueAt(c.getEmailAddress(), row, 3);
index++;
row++;
}
jTable1.getColumn("No").setMaxWidth(30);
jTable1.getColumn("Name").setMaxWidth(130);
jTable1.getColumn("Customer No").setMaxWidth(110);
jTable1.getColumn("Email Address").setMaxWidth(110);
jTextStatus.setText("Finish Load Customer," + Integer.toString(AllCustomer.size())
+ " records found");
}else{
jTextStatus.setText("Finish Load Customer, No record Found");
}
}
}
private WindowAdapter getWindowAdapter() {
return new WindowAdapter() {
@Override
public void windowClosing(WindowEvent we) {//override to show message
super.windowClosing(we);
if (JOptionPane.showConfirmDialog(null, "Are you sure to close this application?",
"Confirmation Box", JOptionPane.OK_CANCEL_OPTION) == 0) { //clicked ok
CloseApp();
}
}
};
}
public void CloseApp() {
this.dispose();
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jTextStatus = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jTextSearch = new javax.swing.JTextField();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Phone Customer - Group");
setResizable(false);
jScrollPane1.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
jTable1.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null},
{null, null, null},
{null, null, null},
{null, null, null}
},
new String [] {
"Name", "Customer No", "Email Address"
}
));
jScrollPane1.setViewportView(jTable1);
jButton1.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
jButton1.setText("Add Customer");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
jButton2.setText("Edit");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
jButton3.setText("Delete");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jTextStatus.setBackground(new java.awt.Color(153, 153, 153));
jTextStatus.setFont(new java.awt.Font("Verdana", 3, 11)); // NOI18N
jTextStatus.setToolTipText("This is a Application Status");
jTextStatus.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jTextStatus.setDisabledTextColor(new java.awt.Color(255, 255, 255));
jTextStatus.setEnabled(false);
jLabel1.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
jLabel1.setForeground(new java.awt.Color(0, 102, 102));
jLabel1.setText("Search Customer");
jTextSearch.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
jButton4.setText("Search");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton5.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
jButton5.setText("Reload Customer");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jMenu1.setText("About Application");
jMenu1.addMenuListener(new javax.swing.event.MenuListener() {
public void menuCanceled(javax.swing.event.MenuEvent evt) {
}
public void menuDeselected(javax.swing.event.MenuEvent evt) {
}
public void menuSelected(javax.swing.event.MenuEvent evt) {
jMenu1MenuSelected(evt);
}
});
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextStatus)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jTextSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 303, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton4))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton5)))
.addGap(0, 3, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(17, 17, 17)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton3)
.addComponent(jButton5)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jTextStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//Add Customer
AddEdit Form = new AddEdit();
Form.setFormMode(true);//true for add mode
Form.UpdateStatus();
Form.setVisible(true);
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
int row = jTable1.getSelectedRow();
//if row is -1 mean user have not select any row yet
if(row != -1){
String nama = (String)jTable1.getValueAt(row,1);//cast object to string
String PhoneNo = (String)jTable1.getValueAt(row,2);//cast object to string
String email = (String)jTable1.getValueAt(row,3);//cast object to string
Customer C = new Customer();
C.setEmailAddress(email);
C.setName(nama);
C.setPhoneNo(PhoneNo);
AddEdit dlg = new AddEdit();
dlg.setFormMode(false);//true for add mode
dlg.MapTextBox(C);
dlg.UpdateStatus();
dlg.setVisible(true);
}
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
int row = jTable1.getSelectedRow();
//if row is -1 mean user have not select any row yet
if(row != -1){
String nama = (String)jTable1.getValueAt(row,1);//cast object to string
String PhoneNo = (String)jTable1.getValueAt(row,2);//cast object to string
String email = (String)jTable1.getValueAt(row,3);//cast object to string
Customer C = new Customer();
C.setEmailAddress(email);
C.setName(nama);
C.setPhoneNo(PhoneNo);
if (JOptionPane.showConfirmDialog(null, "Are you sure to delete Customer : " + nama + "?",
"Confirmation Box", JOptionPane.OK_CANCEL_OPTION) == 0) { //clicked ok
CustomerUtility.deleteCustomer(C);
}
}
}
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
//reload Customer
CustomerUtility.readCustomerCustomer();
BindIntoJTable();
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
String searchValue = jTextSearch.getText();
List<Customer> Customer = CustomerUtility.searchCustomer(searchValue);
CustomerUtility.setAllCustomer(Customer);
BindIntoJTable();
}
private void jMenu1MenuSelected(javax.swing.event.MenuEvent evt) {
// do nothing
}
/**
* @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 http://download.oracle.com/javase/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainUserInterface.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 MainUserInterface().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JLabel jLabel1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JScrollPane jScrollPane1;
private static javax.swing.JTable jTable1;
private javax.swing.JTextField jTextSearch;
private static javax.swing.JTextField jTextStatus;
// End of variables declaration
}
AddEdit code :
import javax.swing.JOptionPane;
/*
* 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.
*/
/**
*
* @author developersnote
*/
public class AddEdit extends javax.swing.JFrame {
private boolean formMode;// true for add, false for edit
private Customer editCustomerDetails;
/**
* Creates new form AddEdit
*/
public AddEdit() {
initComponents();
}
public void UpdateStatus(){
if(formMode){
jTextStatus.setText("Add Customer Mode");
jButton1.setText(formMode ? "Save" : "Update");
}else{
jTextStatus.setText("Edit Customer Mode");
jButton1.setText(formMode ? "Save" : "Update");
}
}
public void MapTextBox(Customer c){
if(c != null){
JTextName.setText(c.getName());
JTextPhone.setText(c.getPhoneNo());
jTextEmail.setText(c.getEmailAddress());
editCustomerDetails = c;
}
}
protected void CloseDialog()
{
this.dispose();
}
/**
* 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();
JTextName = new javax.swing.JTextField();
JTextPhone = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jTextEmail = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jTextStatus = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
jLabel1.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
jLabel1.setForeground(new java.awt.Color(0, 102, 102));
jLabel1.setText("Customer Information");
jLabel2.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
jLabel2.setText("Name");
JTextName.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
JTextPhone.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
JTextPhone.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
JTextPhoneKeyPressed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
jLabel3.setText("Customer No");
jTextEmail.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
jLabel4.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
jLabel4.setText("Email Address");
jButton1.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
jButton1.setText("Save");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
jButton2.setText("Cancel");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jTextStatus.setBackground(new java.awt.Color(153, 153, 153));
jTextStatus.setFont(new java.awt.Font("Verdana", 3, 11)); // NOI18N
jTextStatus.setForeground(new java.awt.Color(255, 255, 255));
jTextStatus.setToolTipText("This is a Customer Information Status");
jTextStatus.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jTextStatus.setDisabledTextColor(new java.awt.Color(255, 255, 255));
jTextStatus.setEnabled(false);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jTextEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(JTextPhone, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(jLabel1)
.addComponent(JTextName, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(23, Short.MAX_VALUE))
.addComponent(jTextStatus)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(JTextName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(JTextPhone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextEmail, 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(jButton1)
.addComponent(jButton2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
.addComponent(jTextStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
CloseDialog();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String Name = JTextName.getText();
String Phone = JTextPhone.getText();
String Email = jTextEmail.getText();
String buildCustomer = "";
if(!Name.isEmpty()){
buildCustomer += Name + ",";
}else {
buildCustomer += "NULL" + ",";
}
if(!Phone.isEmpty()){
buildCustomer += Phone + ",";
}else {
buildCustomer += "NULL" + ",";
}
if(!Email.isEmpty()){
buildCustomer += Email + ",";
}else {
buildCustomer += "NULL" + ",";
}
buildCustomer = buildCustomer.substring(0,buildCustomer.length() -1);
if(formMode){
if(CustomersUtility.appendTextCustomer(buildCustomer + " ")){
JOptionPane.showMessageDialog(null,"Successfully add Customer : " + Name);
CustomersUtility.readPhoneCustomers(); // re read Customer file to reload arrayList
MainUserInterface.BindIntoJTable();
CloseDialog();
}else{
JOptionPane.showMessageDialog(null,"Failed to add Customer : " + Name);
}
}else{
if(CustomersUtility.updateCustomer(editCustomerDetails.getName(),
editCustomerDetails.getPhoneNo(),
editCustomerDetails.getEmailAddress(), buildCustomer)){
JOptionPane.showMessageDialog(null,"Successfully update Customer : " + Name);
CustomersUtility.readPhoneCustomers(); // re read Customer file to reload arrayList
MainUserInterface.BindIntoJTable();
CloseDialog();
}else{
JOptionPane.showMessageDialog(null,"Failed to update Customer : " + Name);
}
}
}
private void JTextPhoneKeyPressed(java.awt.event.KeyEvent evt) {
if(JTextPhone.getText().length() == 12){
JTextPhone.setText(JTextPhone.getText().substring(0,JTextPhone.getText().length() -1));
}
}
/**
* @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 http://download.oracle.com/javase/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AddEdit.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 AddEdit().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField JTextName;
private javax.swing.JTextField JTextPhone;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JTextField jTextEmail;
private javax.swing.JTextField jTextStatus;
// End of variables declaration
/**
* @return the formMode
*/
public boolean isFormMode() {
return formMode;
}
/**
* @param formMode the formMode to set
*/
public void setFormMode(boolean formMode) {
this.formMode = formMode;
}
/**
* @return the editCustomerDetails
*/
public Customer getEditCustomerDetails() {
return editCustomerDetails;
}
/**
* @param editCustomerDetails the editCustomerDetails to set
*/
public void setEditCustomerDetails(Customer editCustomerDetails) {
this.editCustomerDetails = editCustomerDetails;
}
}
Customer.java
public class Customer {
private String Name;
private String PhoneNo;
private String EmailAddress;
public Customer()
{
Name = "";
PhoneNo = "";
EmailAddress = "";
}
/**
* @return the Name
*/
public String getName() {
return Name;
}
/**
* @param Name the Name to set
*/
public void setName(String Name) {
this.Name = Name;
}
/**
* @return the PhoneNo
*/
public String getPhoneNo() {
return PhoneNo;
}
/**
* @param PhoneNo the PhoneNo to set
*/
public void setPhoneNo(String PhoneNo) {
this.PhoneNo = PhoneNo;
}
/**
* @return the EmailAddress
*/
public String getEmailAddress() {
return EmailAddress;
}
/**
* @param EmailAddress the EmailAddress to set
*/
public void setEmailAddress(String EmailAddress) {
this.EmailAddress = EmailAddress;
}
}
CustomerUtility.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/*
* 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.
*/
/**
*
* @author developersnote
*/
public class CustomersUtility {
private static List<Customer> AllCustomers;
private static String MessageStatus;
public static final String CustomerFileName = "Customers.txt";
/**
* @return the MessageStatus
*/
public static String getMessageStatus() {
return MessageStatus;
}
/**
* @param aMessageStatus the MessageStatus to set
*/
public static void setMessageStatus(String aMessageStatus) {
MessageStatus = aMessageStatus;
}
public CustomersUtility() {
AllCustomers = new ArrayList<Customer>();
}
public static boolean updateCustomer(String name, String PhoneNo, String emailAdd, String NewStringLine) {
BufferedReader br = null;
String ReWrite = "";
boolean success = false;
try {
if (new File(CustomerFileName).exists()) {
br = new BufferedReader(new FileReader(CustomerFileName));
String line = "";
while ((line = br.readLine()) != null) {
if (!"".equals(line)) {
String[] _temp = line.split(",");
if (_temp[0].equalsIgnoreCase(name) && _temp[1].equalsIgnoreCase(PhoneNo)
&& _temp[2].equalsIgnoreCase(emailAdd)) {
ReWrite += NewStringLine + " ";
} else {
ReWrite += line + " ";
}
}
}
br.close();
if (writeFile(ReWrite)) {
success = true;
} else {
success = false;
}
//update ArrayList with new Customer List
readPhoneCustomers();
} else {
new File(CustomerFileName).createNewFile();
readPhoneCustomers();
success = false;
}
} catch (FileNotFoundException ex) {
MessageStatus = ex.getMessage();
success = false;
} catch (IOException ex) {
MessageStatus = ex.getMessage();
success = false;
}
return success;
}
public static List<Customer> searchCustomer(String searchValue) {
List<Customer> cnt = new ArrayList<>();
BufferedReader br = null;
try {
if (new File(CustomerFileName).exists()) {
br = new BufferedReader(new FileReader(CustomerFileName));
String line = "";
while ((line = br.readLine()) != null) {
if (!"".equals(line)) {
String[] _temp = line.split(",");
if (_temp[0].equalsIgnoreCase(searchValue) || _temp[1].equalsIgnoreCase(searchValue)
|| _temp[2].equalsIgnoreCase(searchValue)) {
Customer c = new Customer();
c.setName(_temp[0]);
c.setPhoneNo(_temp[1]);
c.setEmailAddress(_temp[2]);
cnt.add(c);
}
}
}
} else {
new File(CustomerFileName).createNewFile();
cnt = searchCustomer(searchValue);
}
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
} finally {
try {
br.close();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
return cnt;
}
protected static boolean writeFile(String TextToWrite) {
FileWriter writer = null;
boolean successfulWrite = false;
try {
writer = new FileWriter(CustomerFileName);
writer.write(TextToWrite);
writer.close();
successfulWrite = true;
} catch (IOException ex) {
successfulWrite = false;
MessageStatus = ex.getMessage();
} finally {
try {
writer.close();
} catch (IOException ex) {
MessageStatus = ex.getMessage();
}
}
return successfulWrite;
}
public static void deleteCustomers(Customer C) {
BufferedReader br = null;
String ReWrite = "";
try {
if (new File(CustomerFileName).exists()) {
br = new BufferedReader(new FileReader(CustomerFileName));
String line = "";
while ((line = br.readLine()) != null) {
String[] _temp = line.split(",");
if (_temp[0].equalsIgnoreCase(C.getName()) && _temp[1].equalsIgnoreCase(C.getPhoneNo())
&& _temp[2].equalsIgnoreCase(C.getEmailAddress())) {
//ignore line to delete this Customer
} else {
ReWrite += line + " ";
}
}
br.close();
if (writeFile(ReWrite)) {
JOptionPane.showMessageDialog(null, "Successfully delete Customer " + C.getName());
} else {
JOptionPane.showMessageDialog(null, "Failed to delete Customer " + C.getName());
}
CustomersUtility.readPhoneCustomers();
MainUserInterface.BindIntoJTable();
} else {
new File(CustomerFileName).createNewFile();
readPhoneCustomers();
}
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
public static void readPhoneCustomers() {
//read Customers file and store into arraylist of Object(Customer)
BufferedReader br = null;
try {
if (new File(CustomerFileName).exists()) {
if (AllCustomers == null) {
AllCustomers = new ArrayList<>();
} else {
AllCustomers.clear();
}
br = new BufferedReader(new FileReader(CustomerFileName));
StringBuilder sb = new StringBuilder();
String line = "";
Customer CustomerClass = null;
while ((line = br.readLine()) != null) {
if (!line.equalsIgnoreCase("")) {
CustomerClass = new Customer();
String[] _temp = line.split(",");
String _tempValue = _temp[0];
if (_tempValue.equalsIgnoreCase("NULL")) {
_tempValue = "";
}
CustomerClass.setName(_tempValue);
_tempValue = _temp[1];
if (_tempValue.equalsIgnoreCase("NULL")) {
_tempValue = "";
}
CustomerClass.setPhoneNo(_tempValue);
_tempValue = _temp[2];
if (_tempValue.equalsIgnoreCase("NULL")) {
_tempValue = "";
}
CustomerClass.setEmailAddress(_tempValue);
AllCustomers.add(CustomerClass);
}
}
} else {
new File(CustomerFileName).createNewFile();
readPhoneCustomers();
}
} catch (NullPointerException | IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
Logger.getLogger(CustomersUtility.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static boolean appendTextCustomer(String appendValue) {
boolean success = false;
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(CustomerFileName, true)));
out.println(appendValue);
out.close();
success = true;
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return success;
}
/**
* @return the AllCustomers
*/
public static List<Customer> getAllCustomers() {
return AllCustomers;
}
/**
* @param aAllCustomers the AllCustomers to set
*/
public static void setAllCustomers(List<Customer> aAllCustomers) {
AllCustomers = aAllCustomers;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.