Interface.MainJFrame.java Source code

Java tutorial

Introduction

Here is the source code for Interface.MainJFrame.java

Source

/*
 * 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 Interface;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.events.Attribute;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONWriter;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/*
 *
 * @author apple
 */
public class MainJFrame extends javax.swing.JFrame {

    /**
     * Creates new form MainJFrame
     */
    public MainJFrame() {
        initComponents();
    }

    /**
     * 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">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtFullName = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtEmployeeID = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtPhoneNumber = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtAddress = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtEmployeeType = new javax.swing.JTextField();
        txtPayCategory = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        txtSalary = new javax.swing.JTextField();
        txtHours = new javax.swing.JTextField();
        txtBonuses = new javax.swing.JTextField();
        txtTotal = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        btnTXT = new javax.swing.JButton();
        btnCSV = new javax.swing.JButton();
        btnXML = new javax.swing.JButton();
        btnPaymentInfo = new javax.swing.JButton();
        btnJSON = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Full Name");

        jLabel2.setText("Employee ID");

        txtEmployeeID.setText(" ");

        jLabel3.setText("Phone Number");

        jLabel4.setText("Address");

        jLabel5.setText("Title");

        jLabel6.setText("Pay Category");

        txtEmployeeType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtEmployeeTypeActionPerformed(evt);
            }
        });

        jLabel7.setText("Salary/Wage");

        jLabel8.setText("Hours");

        jLabel9.setText("Bonuses");

        jLabel10.setText("Total");

        jButton1.setText("Exit");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        btnTXT.setText("txt");
        btnTXT.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTXTActionPerformed(evt);
            }
        });

        btnCSV.setText("csv");
        btnCSV.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCSVActionPerformed(evt);
            }
        });

        btnXML.setText("xml");
        btnXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnXMLActionPerformed(evt);
            }
        });

        btnPaymentInfo.setText("Payment Info");

        btnJSON.setText("JSON");
        btnJSON.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnJSONActionPerformed(evt);
            }
        });

        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.LEADING)
                        .addGroup(layout.createSequentialGroup().addGap(16, 16, 16)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel2).addComponent(jLabel1).addComponent(jLabel3)
                                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 54,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel6).addComponent(jLabel5).addComponent(jLabel10)
                                        .addComponent(jLabel9).addComponent(jLabel8).addComponent(jLabel7)))
                        .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jButton1)))
                        .addGap(42, 42, 42).addGroup(
                                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup().addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(txtFullName).addComponent(txtEmployeeID)
                                                .addComponent(txtPhoneNumber).addComponent(txtAddress)
                                                .addComponent(txtEmployeeType).addComponent(txtPayCategory)
                                                .addComponent(txtSalary).addComponent(txtHours)
                                                .addComponent(txtBonuses).addComponent(txtTotal)).addContainerGap())
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(btnTXT, javax.swing.GroupLayout.PREFERRED_SIZE, 45,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(btnCSV, javax.swing.GroupLayout.PREFERRED_SIZE, 49,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(btnXML, javax.swing.GroupLayout.PREFERRED_SIZE, 49,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .addComponent(btnJSON, javax.swing.GroupLayout.PREFERRED_SIZE, 58,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(57, 57, 57).addComponent(btnPaymentInfo)))));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addComponent(txtFullName, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtEmployeeID, 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(txtPhoneNumber, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel3)))
                        .addGroup(layout.createSequentialGroup().addComponent(jLabel1).addGap(30, 30, 30)
                                .addComponent(jLabel2)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel4))
                        .addGap(14, 14, 14)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel5).addComponent(txtEmployeeType,
                                        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(jLabel6).addComponent(txtPayCategory,
                                        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(jLabel7).addComponent(txtSalary,
                                        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(jLabel8).addComponent(txtHours,
                                        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(jLabel9).addComponent(txtBonuses,
                                        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(jLabel10)
                                .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jButton1).addComponent(btnTXT).addComponent(btnCSV)
                                .addComponent(btnXML).addComponent(btnPaymentInfo).addComponent(btnJSON))
                        .addGap(16, 16, 16)));

        jLabel1.getAccessibleContext().setAccessibleName("lbFullName");
        txtFullName.getAccessibleContext().setAccessibleName("");
        jLabel2.getAccessibleContext().setAccessibleName("lblEmployeeID");
        txtEmployeeID.getAccessibleContext().setAccessibleName("");
        txtPhoneNumber.getAccessibleContext().setAccessibleName("");
        txtAddress.getAccessibleContext().setAccessibleName("");
        txtEmployeeType.getAccessibleContext().setAccessibleName("");
        txtPayCategory.getAccessibleContext().setAccessibleName("");
        txtSalary.getAccessibleContext().setAccessibleName("");
        txtHours.getAccessibleContext().setAccessibleName("");
        txtBonuses.getAccessibleContext().setAccessibleName("");
        txtTotal.getAccessibleContext().setAccessibleName("");
        jButton1.getAccessibleContext().setAccessibleName("btnExit");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtEmployeeTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtEmployeeTypeActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtEmployeeTypeActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        System.exit(0); // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btnXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXMLActionPerformed
        // TODO add your handling code here:
        try {

            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            // root elements
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("Employees");
            doc.appendChild(rootElement);

            // staff elements
            String empTitle = txtEmployeeType.getText().trim();
            empTitle = empTitle.replace(" ", "");
            Element staff = doc.createElement(empTitle);
            rootElement.appendChild(staff);

            // set attribute to staff element
            Attr attr = doc.createAttribute("ID");
            attr.setValue(txtEmployeeID.getText().trim());
            staff.setAttributeNode(attr);

            // shorten way
            // staff.setAttribute("id", "1");

            // FullName elements
            Element FulllName = doc.createElement("FulllName");
            FulllName.appendChild(doc.createTextNode(txtFullName.getText().trim()));
            staff.appendChild(FulllName);

            // Phone elements
            Element Phone = doc.createElement("PhoneNumber");
            Phone.appendChild(doc.createTextNode(txtPhoneNumber.getText().trim()));
            staff.appendChild(Phone);

            // Address elements
            Element Address = doc.createElement("Address");
            Address.appendChild(doc.createTextNode(txtAddress.getText().trim()));
            staff.appendChild(Address);

            // Title elements
            Element Title = doc.createElement("Tile");
            Title.appendChild(doc.createTextNode(txtEmployeeType.getText().trim()));
            staff.appendChild(Title);

            // PayCategory elements
            Element PayCategory = doc.createElement("PayCategory");
            PayCategory.appendChild(doc.createTextNode(txtPayCategory.getText().trim()));
            staff.appendChild(PayCategory);

            // Salary elements
            Element Salary = doc.createElement("Salary");
            Salary.appendChild(doc.createTextNode(txtSalary.getText().trim()));
            staff.appendChild(Salary);

            // Hours elements

            String hours = txtHours.getText().trim();
            if (txtHours.getText().equalsIgnoreCase("") || hours == null) {
                hours = "null";
            }
            Element Hours = doc.createElement("Hours");
            Hours.appendChild(doc.createTextNode(hours));
            staff.appendChild(Hours);

            // Bonus elements
            Element Bonus = doc.createElement("Bonus");
            Bonus.appendChild(doc.createTextNode(txtBonuses.getText().trim()));
            staff.appendChild(Bonus);

            // Total elements
            Element Total = doc.createElement("Total");
            Total.appendChild(doc.createTextNode(txtTotal.getText().trim()));
            staff.appendChild(Total);

            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File("XMLOutput"));

            // Output to console for testing
            // StreamResult result = new StreamResult(System.out);

            transformer.transform(source, result);

        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        }

    }//GEN-LAST:event_btnXMLActionPerformed

    private void btnTXTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTXTActionPerformed
        // TODO add your handling code here:

        BufferedWriter output = null;
        try {
            File file = new File("output.txt");
            output = new BufferedWriter(new FileWriter(file));
            output.write("Name:" + txtFullName.getText());
            output.newLine();
            output.write("ID:" + txtEmployeeID.getText());
            output.newLine();
            output.write("Phone:" + txtPhoneNumber.getText());
            output.newLine();
            output.write("Address:" + txtAddress.getText());
            output.newLine();
            output.write("Employee Type:" + txtEmployeeType.getText());
            output.newLine();
            output.write("PayCategory:" + txtPayCategory.getText());
            output.newLine();
            output.write("Salary:" + txtSalary.getText());
            output.newLine();
            output.write("Hours:" + txtHours.getText());
            output.newLine();
            output.write("Bonus:" + txtBonuses.getText());
            output.newLine();
            output.write("Total:" + txtTotal.getText());
            output.newLine();

            output.flush();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }//GEN-LAST:event_btnTXTActionPerformed

    private void btnCSVActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCSVActionPerformed
        // TODO add your handling code here:
        FileWriter writer;
        try {
            writer = new FileWriter("output.csv");
            writer.append("Name");
            writer.append(',');
            writer.append("ID");
            writer.append(',');
            writer.append("Phone");
            writer.append(',');
            writer.append("Address");
            writer.append(',');
            writer.append("Employee Type");
            writer.append(',');
            writer.append("Pay Category");
            writer.append(',');
            writer.append("Salary");
            writer.append(',');
            writer.append("Hours");
            writer.append(',');
            writer.append("Bonus");
            writer.append(',');
            writer.append("Total");
            writer.append('\n');

            writer.append(txtFullName.getText());
            writer.append(',');
            writer.append(txtEmployeeID.getText());
            writer.append(',');
            writer.append(txtPhoneNumber.getText());
            writer.append(',');
            writer.append(txtAddress.getText());
            writer.append(',');
            writer.append(txtEmployeeType.getText());
            writer.append(',');
            writer.append(txtPayCategory.getText());
            writer.append(',');
            writer.append(txtSalary.getText());
            writer.append(',');
            writer.append(txtHours.getText());
            writer.append(',');
            writer.append(txtBonuses.getText());
            writer.append(',');
            writer.append(txtTotal.getText());
            writer.append('\n');

        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }//GEN-LAST:event_btnCSVActionPerformed

    private void btnJSONActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnJSONActionPerformed
        // TODO add your handling code here:

        JSONWriter jsonWriter = null;

        JSONObject obj = new JSONObject();
        try {
            obj.put("Name", txtFullName.getText().trim());
            obj.put("ID", txtEmployeeID.getText().trim());
            obj.put("Phone", txtPhoneNumber.getText().trim());
            obj.put("Address", txtAddress.getText().trim());
            obj.put("Title", txtEmployeeType.getText().trim());
            obj.put("PayCategory", txtPayCategory.getText().trim());
            obj.put("Salary", txtSalary.getText().trim());
            obj.put("Hours", txtHours.getText().trim());
            obj.put("Bonuses", txtBonuses.getText().trim());
            obj.put("Total", txtTotal.getText().trim());
        } catch (Exception e) {
        }

        // try-with-resources statement based on post comment below :)
        try {
            FileWriter file = new FileWriter("JSONoutput");
            file.write(obj.toString());
            file.flush();
            file.close();
        } catch (Exception e) {
        }

    }//GEN-LAST:event_btnJSONActionPerformed

    /**
     * @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/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(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        }
        //</editor-fold>
        EmployeeJFrame empForm = new EmployeeJFrame();
        empForm.setVisible(true);
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCSV;
    private javax.swing.JButton btnJSON;
    private javax.swing.JButton btnPaymentInfo;
    private javax.swing.JButton btnTXT;
    private javax.swing.JButton btnXML;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    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.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    public static javax.swing.JTextField txtAddress;
    public static javax.swing.JTextField txtBonuses;
    public static javax.swing.JTextField txtEmployeeID;
    public static javax.swing.JTextField txtEmployeeType;
    public static javax.swing.JTextField txtFullName;
    public static javax.swing.JTextField txtHours;
    public static javax.swing.JTextField txtPayCategory;
    public static javax.swing.JTextField txtPhoneNumber;
    public static javax.swing.JTextField txtSalary;
    public static javax.swing.JTextField txtTotal;
    // End of variables declaration//GEN-END:variables
}