Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
18 kB
4
Indexable
Never
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
 */
package com.mycompany.mavenproject9;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author noah
 */
public class Assignment2 extends javax.swing.JFrame {

    /**
     * Creates new form Assignment2
     */
    public Assignment2() {
        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">                          
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        NICtxt = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        Agetxt = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        Nametxt = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        Addbtn = new javax.swing.JButton();
        Clearbtn = new javax.swing.JButton();
        searchtxt = new javax.swing.JTextField();
        Searchbtn = new javax.swing.JButton();
        showtable = new javax.swing.JButton();

        jTextField1.setText("jTextField1");
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Staff NIC");

        jLabel2.setText("Age");

        jLabel3.setText("Full Name");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Staff NIC", "Full Name", "Age"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        Addbtn.setText("Add");
        Addbtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddbtnActionPerformed(evt);
            }
        });

        Clearbtn.setText("Clear");
        Clearbtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ClearbtnActionPerformed(evt);
            }
        });

        Searchbtn.setText("Search");
        Searchbtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SearchbtnActionPerformed(evt);
            }
        });

        showtable.setText("Show Table");
        showtable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showtableActionPerformed(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()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(NICtxt, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(Nametxt, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE)
                                    .addComponent(Agetxt)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 378, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(47, 47, 47)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(searchtxt, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(showtable))
                                .addGap(34, 34, 34)
                                .addComponent(Searchbtn))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(36, 36, 36)
                        .addComponent(Addbtn)
                        .addGap(82, 82, 82)
                        .addComponent(Clearbtn)))
                .addContainerGap(56, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(35, 35, 35)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(73, 73, 73)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(searchtxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(Searchbtn))
                        .addGap(62, 62, 62)
                        .addComponent(showtable)))
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(NICtxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Nametxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Agetxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 73, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Addbtn)
                    .addComponent(Clearbtn))
                .addGap(44, 44, 44))
        );

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

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    private void AddbtnActionPerformed(java.awt.event.ActionEvent evt) {                                       
String NIC = NICtxt.getText();
        String name = Nametxt.getText();
        String Age = Agetxt.getText();
        
         
    FileWriter fw=null;

    
        
        
        if (name.isEmpty() || NIC.isEmpty() || NIC.isEmpty() ) {
            JOptionPane.showMessageDialog(this,
                                    "Please enter all fields",
                                    "Try again",
                                    JOptionPane.ERROR_MESSAGE);
        } else {
            DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
            model.addRow(new Object[]{NIC, name, Age});
            
            NICtxt.setText("");
            Nametxt.setText("");
            Agetxt.setText("");
            
             String Staff = NIC + " " + name  +" " +  Age  ;
             
          try {
            //create a write stream to the names.txt file
            BufferedWriter bw = new BufferedWriter(new FileWriter("names.txt", true));                     //loop through each new name entered in the text area line by line
            for (String line : Staff.split("\\n")) {                         //write the name to the names.txt file
                bw.write(line);                         //come to the next line
                bw.newLine();                     }                       //display an appropriate message after the action is completed
                                //close the write stream
            bw.close();
        }catch(IOException ex) {
            ex.printStackTrace();
        } 
        
    }          // TODO add your handling code here:
    }                                      

    private void ClearbtnActionPerformed(java.awt.event.ActionEvent evt) {                                         
   NICtxt.setText("");
        Nametxt.setText("");
        Agetxt.setText("");
          // TODO add your handling code here:
    }                                        

    private void SearchbtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
       NICtxt.setText("");
        Nametxt.setText("");
        Agetxt.setText("");
        
               
        for(int i = 0; i < model.getRowCount(); i++){//For each row
    for(int j = 0; j < model.getColumnCount(); j++){//For each column in that row
  
        //Print if found string
         if ((jTable1.getModel().getValueAt(i,1)).equals(searchtxt.getText())){//Search the model
               NICtxt.setText(jTable1.getValueAt(i,0).toString());
               Nametxt.setText(jTable1.getValueAt(i,1).toString());
               Agetxt.setText(jTable1.getValueAt(i,2).toString());
            
                 
       
              JOptionPane.showMessageDialog(this,"data found");
         break; }
          
             
                

      
        
    }//For loop inner
}//For loop outer       
        if ((Nametxt.getText().isEmpty())){ 
            JOptionPane.showMessageDialog(this,"data not found");
        }// TODO add your handling code here:
    }                                         

    private void showtableActionPerformed(java.awt.event.ActionEvent evt) {                                          
     DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
     model.setRowCount(0);
        try {
            Object rowData[] = new Object[3];

            BufferedReader br = new BufferedReader(new FileReader("names.txt"));                     //create an arraylist to store the names read from the file
            ArrayList<String> names = new ArrayList<String>();
            String line;                                          //read the names in the directory one by one
            while((line = br.readLine())!=null) {                         //add each name to the arraylist
                names.add(line);                     }                     //close the read stream
            br.close();                                          //bubble sort the names in the arraylist
            for (int j = 0; j < names.size(); j++) {
                for (int i = j + 1; i < names.size(); i++) {                             //comparing adjacent names
                    if (names.get(i).compareTo(names.get(j)) < 0) {                                 //swap the names if the former is greater than the latter name
                        String temp = names.get(j);
                        names.set(j,names.get(i));
                        names.set(i,temp);
                    }
                }                     }

                        //append the sorted names to the tables
                for(int i=0; i<names.size(); i++){
                    String fullname=names.get(i);
                    int index=fullname.lastIndexOf(" ");
                    if (index==-1)throw new IllegalArgumentException("Please enter Surname and First Name,here there is Only a single name: " + fullname);

                    rowData[0] = fullname.substring(0, index-1);
                    rowData[1] = fullname.substring(index-1,index);
                     rowData[2] = fullname.substring(index+1);

                    model.addRow(rowData);                        }
            }catch(IOException ex) {
            }         // TODO add your handling code here:
    }                                         

    /**
     * @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(Assignment2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Assignment2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Assignment2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Assignment2.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 Assignment2().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton Addbtn;
    private javax.swing.JTextField Agetxt;
    private javax.swing.JButton Clearbtn;
    private javax.swing.JTextField NICtxt;
    private javax.swing.JTextField Nametxt;
    private javax.swing.JButton Searchbtn;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField searchtxt;
    private javax.swing.JButton showtable;
    // End of variables declaration                   
}