Java tutorial
/* * 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 javaapplication1; import java.awt.Color; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; /** * * @author OB */ public class AttendancePayment extends javax.swing.JFrame { /** * Creates new form AttendancePayment */ private static String filePath, chooseError, addingName; private static boolean fileChosen; private static int idNum; private static final int ID_COL = 0, NAMEFIRST_COL = 2, NAMELAST_COL = 1, PAIDSTATUS_COL = 4, GRADE_COL = 3; private static FileInputStream file1; private static HSSFWorkbook workbook; private static HSSFSheet sheet; public AttendancePayment() { 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() { jInputField = new javax.swing.JTextField(); jInputLabel = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jDisplayArea = new javax.swing.JTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); jInputField.setToolTipText(""); jInputField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jInputFieldActionPerformed(evt); } }); jInputLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jInputLabel.setText("Scan ID Below"); jDisplayArea.setColumns(20); jDisplayArea.setRows(5); jScrollPane1.setViewportView(jDisplayArea); 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) .addComponent(jInputField).addComponent(jInputLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jInputLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jInputField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))); pack(); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String args[]) throws IOException { /* 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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AttendancePayment.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> int newOrOld = newOrExisting(); //System.out.println(newOrOld); //exit is -1 //new roster is 0 //existing roster is 1 if (newOrOld != -1) { //</editor-fold> //if new roster is selected, overwrites the paidstatus column with N if (newOrOld == 0) { Object[] options = { "Yes I'm Sure", "No, Use an existing roster" }; //Yes I'm sure = 0 //No, use existing = 1 int newOldChoice = JOptionPane.showOptionDialog(null, "Only do this if this is the first time this is being run for the event", "", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]); //System.out.println(newOldChoice); if (newOldChoice == -1) { confirmChoice(); } fileImport(); if (newOldChoice == 0) { for (Row row : sheet) { Cell paymentCell = row.createCell(PAIDSTATUS_COL); paymentCell.setCellValue("N"); } } } else fileImport(); /* Create and display the form */ java.awt.EventQueue.invokeLater(() -> { new AttendancePayment().setVisible(true); }); } else System.exit(0); } private void jInputFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jInputFieldActionPerformed // TODO add your handling code here: try { checkName(); } catch (IOException ex) { Logger.getLogger(AttendancePayment.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jInputFieldActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing // TODO add your handling code here: int result = JOptionPane.showConfirmDialog(null, "Exit the application?"); if (result == JOptionPane.OK_OPTION) { System.exit(0); } }//GEN-LAST:event_formWindowClosing private static void fileImport() throws IOException { //variable assignment fileChosen = true; chooseError = ""; //creates filechooser with desktop as default directory String userhome = System.getProperty("user.home"); JFileChooser chooser = new JFileChooser(userhome + "\\Desktop"); //opens filechooser, assigns choice to status int status = chooser.showOpenDialog(null); File file = chooser.getSelectedFile(); //if they don't click approve, assume no file chosen if (status != JFileChooser.APPROVE_OPTION) { //System.out.println("No File Chosen"); fileChosen = false; chooseError = "No File Chosen"; confirmChoice(); } //if a file is chosen but not ending in .xls, restart if (fileChosen) { filePath = file.getAbsolutePath(); if (!filePath.endsWith(".xls")) { chooseError = "File Doesn't End with .xls"; confirmChoice(); } } //creates excel objects file1 = new FileInputStream(new File(filePath)); workbook = new HSSFWorkbook(file1); sheet = workbook.getSheetAt(0); } private static void confirmChoice() { int choice = JOptionPane.showConfirmDialog(null, "Do You want to quit?", chooseError, JOptionPane.YES_NO_OPTION); //only tries filechooser again if they explicitly say they don't want to quit if (choice == JOptionPane.NO_OPTION) { try { fileImport(); } catch (IOException ex) { } } else System.exit(0); } private static int newOrExisting() { Object[] options = { "New Roster", "Existing Roster" }; return JOptionPane.showOptionDialog(null, "New Roster or Existing?", "", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); } private static void checkName() throws FileNotFoundException, IOException { //stores the input from the formatted text field idNum = Integer.parseInt(jInputField.getText()); //clears the input field jInputField.setText(""); //System.out.println(idNum); for (Row row : sheet) { Cell cell1 = row.getCell(ID_COL); if ((int) cell1.getNumericCellValue() == idNum) { String paidStatus = null; //foundID = true; Cell lastName = row.getCell(NAMELAST_COL); Cell firstName = row.getCell(NAMEFIRST_COL); Cell grade = row.getCell(GRADE_COL); addingName = (int) grade.getNumericCellValue() + " " + lastName.getStringCellValue() + " " + firstName.getStringCellValue(); try { paidStatus = row.getCell(PAIDSTATUS_COL).toString(); } catch (Exception e) { e.printStackTrace(); } //System.out.println(paidStatus); if ("Y".equals(paidStatus)) { jDisplayArea.setText(addingName + "\n \n" + "Is already paid for"); jDisplayArea.setBackground(Color.red); } else { row.getCell(PAIDSTATUS_COL).setCellValue("Y"); jDisplayArea.setText("Everything Worked"); jDisplayArea.setBackground(Color.green); } try (FileOutputStream fileOut = new FileOutputStream(filePath)) { workbook.write(fileOut); } } } } // Variables declaration - do not modify//GEN-BEGIN:variables private static javax.swing.JTextArea jDisplayArea; private static javax.swing.JTextField jInputField; private static javax.swing.JLabel jInputLabel; private javax.swing.JScrollPane jScrollPane1; // End of variables declaration//GEN-END:variables }