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 com.thelinh.gui; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Font; import com.itextpdf.text.FontFactory; import com.itextpdf.text.Paragraph; import static com.itextpdf.text.pdf.BaseFont.IDENTITY_H; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import com.thelinh.controller.Controller; import com.thelinh.controller.LoadTable; import com.thelinh.model.Subject; import java.awt.event.ItemEvent; import java.awt.print.Book; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.table.TableModel; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; /** * * @author hoangkien */ public class UpdateSubject extends javax.swing.JFrame { String sql = "SELECT * FROM Subjects ORDER BY SubjectId ASC"; private static PreparedStatement ps = null; int k = 1; /** * Creates new form UpdateSubject */ public UpdateSubject() { initComponents(); LoadTable.loadDataSubject(sql, tbSubject); } /** * 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() { btnAdd = new javax.swing.JButton(); btnEdit = new javax.swing.JButton(); btnDelete = new javax.swing.JButton(); btnExit = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tbSubject = new javax.swing.JTable(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); txtFilterSubjectCode = new javax.swing.JTextField(); txtFilterSubjectName = new javax.swing.JTextField(); btnSearch = new javax.swing.JButton(); txtSearch = new javax.swing.JTextField(); btnAddFile = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); cbSubject = new javax.swing.JComboBox<>(); jButton1 = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); btnAdd.setText("Thm"); btnAdd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddActionPerformed(evt); } }); btnEdit.setText("Sa"); btnEdit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnEditActionPerformed(evt); } }); btnDelete.setText("Xa"); btnDelete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDeleteActionPerformed(evt); } }); btnExit.setText("Thot"); btnExit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnExitActionPerformed(evt); } }); tbSubject.setModel(new javax.swing.table.DefaultTableModel( new Object[][] { { null, null }, { null, null }, { null, null }, { null, null } }, new String[] { "M mn h?c", "Tn mn h?c" }) { boolean[] canEdit = new boolean[] { true, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit[columnIndex]; } }); tbSubject.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbSubjectMouseClicked(evt); } }); jScrollPane1.setViewportView(tbSubject); jLabel2.setText("M mn h?c"); jLabel3.setText("Tn mn h?c"); btnSearch.setText("Tm kim"); btnSearch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSearchActionPerformed(evt); } }); btnAddFile.setText("Thm t file"); btnAddFile.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddFileActionPerformed(evt); } }); jLabel1.setText("Tm kim theo"); cbSubject.setModel( new javax.swing.DefaultComboBoxModel<>(new String[] { "SubjectId", "SubjectName", "None" })); cbSubject.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { cbSubjectItemStateChanged(evt); } }); jButton1.setText("Xut ra PDF"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel4.setText("Tm kim"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 581, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout .createSequentialGroup().addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addComponent( cbSubject, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnSearch)) .addComponent(txtSearch))) .addGroup(layout.createSequentialGroup().addGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4).addGroup(layout.createSequentialGroup() .addGap(10, 10, 10).addComponent(btnAdd))) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addGap(0, 0, Short.MAX_VALUE) .addComponent(btnExit).addGap(18, 18, 18)) .addGroup(layout.createSequentialGroup().addGap(4, 4, 4) .addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addComponent(jLabel3) .addGap(24, 24, 24) .addGroup(layout .createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addComponent( txtFilterSubjectCode, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtFilterSubjectName))) .addGroup(layout.createSequentialGroup().addComponent(jLabel2) .addGap(10, 10, 10) .addComponent( btnEdit, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnAddFile).addGap(18, 18, 18) .addComponent(jButton1).addGap(0, 0, Short.MAX_VALUE))))) .addContainerGap())); layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] { btnAddFile, jButton1 }); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txtFilterSubjectCode, 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).addComponent(txtFilterSubjectName, 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(btnAdd).addComponent(btnEdit).addComponent(btnDelete) .addComponent(btnAddFile).addComponent(jButton1)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(12, 12, 12).addComponent(jLabel4) .addGap(11, 11, 11).addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtSearch, 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(cbSubject, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnSearch)))) .addGap(12, 12, 12) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 193, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(btnExit) .addContainerGap())); pack(); }// </editor-fold>//GEN-END:initComponents private void tbSubjectMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbSubjectMouseClicked int row = tbSubject.getSelectedRow(); String rowId = (tbSubject.getModel().getValueAt(row, 0)).toString(); String sql1 = "SELECT * FROM Subjects WHERE SubjectId = '" + rowId + "'"; ResultSet rs = LoadTable.Display(sql1); try { if (rs.next()) { txtFilterSubjectCode.setText(rs.getString("SubjectId")); txtFilterSubjectName.setText(rs.getString("SubjectName")); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "ERROR"); } }//GEN-LAST:event_tbSubjectMouseClicked private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed String sql1 = "SELECT * FROM Subjects"; String sql2 = "SELECT * FROM Subjects WHERE SubjectId LIKE '%" + txtSearch.getText() + "%'"; String sql3 = "SELECT * FROM Subjects WHERE SubjectName LIKE '%" + txtSearch.getText() + "%'"; switch (k) { case 1: LoadTable.loadDataSubject(sql2, tbSubject); break; case 2: LoadTable.loadDataSubject(sql3, tbSubject); break; case 3: LoadTable.loadDataSubject(sql1, tbSubject); break; } }//GEN-LAST:event_btnSearchActionPerformed private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed if (txtFilterSubjectCode.getText().length() == 0) { JOptionPane.showMessageDialog(null, "You have to enter SubjectId", "Notification", JOptionPane.INFORMATION_MESSAGE); } else if (txtFilterSubjectCode.getText().length() > 10) { JOptionPane.showMessageDialog(null, "SubjectId have to less more than 10 characters", "Notification", JOptionPane.INFORMATION_MESSAGE); } else { String sql = "SELECT SubjectId FROM Subjects"; ResultSet rs = LoadTable.Display(sql); try { while (rs.next()) { if (rs.getString("SubjectId") == txtFilterSubjectCode.getText()) { JOptionPane.showMessageDialog(null, "This SubjectId already exists", "Notification", JOptionPane.INFORMATION_MESSAGE); } } // xu li chua chuan lam! :( Subject subject = new Subject(txtFilterSubjectCode.getText(), txtFilterSubjectName.getText()); Controller.insertSubject(subject); btnSearch.doClick(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "ERROR"); } } }//GEN-LAST:event_btnAddActionPerformed private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed System.exit(0); }//GEN-LAST:event_btnExitActionPerformed private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed if (txtFilterSubjectCode.getText().length() == 0) { JOptionPane.showMessageDialog(null, "You have to enter SubjectId", "Notification", JOptionPane.INFORMATION_MESSAGE); } else if (txtFilterSubjectCode.getText().length() > 10) { JOptionPane.showMessageDialog(null, "SubjectId have to less more than 10 characters", "Notification", JOptionPane.INFORMATION_MESSAGE); } else { int click = JOptionPane.showConfirmDialog(null, "Do you want to edit?"); if (click == JOptionPane.YES_OPTION) { Subject subject = new Subject(txtFilterSubjectCode.getText(), txtFilterSubjectName.getText()); if (Controller.updateSubject(subject)) { JOptionPane.showMessageDialog(null, "Edit Success", "Notification", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, "SubjectId does not exist", "ERROR", JOptionPane.ERROR_MESSAGE); } btnSearch.doClick(); } } }//GEN-LAST:event_btnEditActionPerformed private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed if (txtFilterSubjectCode.getText().length() == 0) { JOptionPane.showMessageDialog(null, "You have to enter SubjectId", "Notification", JOptionPane.INFORMATION_MESSAGE); } else if (txtFilterSubjectCode.getText().length() > 10) { JOptionPane.showMessageDialog(null, "SubjectId have to less more than 10 characters", "Notification", JOptionPane.INFORMATION_MESSAGE); } else { int click = JOptionPane.showConfirmDialog(null, "Do you want to delete?"); if (click == JOptionPane.YES_OPTION) { if (Controller.deleteSubject(txtFilterSubjectCode.getText())) { JOptionPane.showMessageDialog(null, "Delete Success", "Notification", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, "SubjectId does not exist", "ERROR", JOptionPane.ERROR_MESSAGE); } btnSearch.doClick(); } } }//GEN-LAST:event_btnDeleteActionPerformed private void btnAddFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddFileActionPerformed JFileChooser jfc = new JFileChooser(); if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { jfc.setDialogTitle("Open File"); File file = jfc.getSelectedFile(); try { Workbook wb = Workbook.getWorkbook(file); Sheet sheet = wb.getSheet(0); int rows = sheet.getRows(); int columns = sheet.getColumns(); for (int i = 0; i < rows; i++) { Subject subject = new Subject(sheet.getCell(0, i).getContents(), sheet.getCell(1, i).getContents()); Controller.insertSubject(subject); } wb.close(); btnSearch.doClick(); } catch (IOException ex) { System.out.println("File not found\n" + ex.toString()); } catch (BiffException ex) { ex.printStackTrace(); } } }//GEN-LAST:event_btnAddFileActionPerformed private void cbSubjectItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbSubjectItemStateChanged if (evt.getStateChange() == ItemEvent.SELECTED && evt.getItem().toString() == "SubjectId") { k = 1; } if (evt.getStateChange() == ItemEvent.SELECTED && evt.getItem().toString() == "SubjectName") { k = 2; } if (evt.getStateChange() == ItemEvent.SELECTED && evt.getItem().toString() == "None") { k = 3; } }//GEN-LAST:event_cbSubjectItemStateChanged private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed Document document = new Document() { }; try { JFileChooser jfc = new JFileChooser("Save File"); if (jfc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { jfc.setDialogTitle("Save File"); FileOutputStream fos = new FileOutputStream(jfc.getSelectedFile()); PdfWriter.getInstance(document, fos); document.open(); Font rfont = FontFactory.getFont("C:\\Windows\\Fonts\\Calibri.ttf", IDENTITY_H, true); document.add(new Paragraph( " TRNG ?I HC B?CH KHOA H NI", rfont)); document.add(new Paragraph( "\t\t KT QU TM KIM MN HC\n", rfont)); switch (k) { case 1: document.add(new Paragraph( " Tm kim theo m mn h?c : " + txtSearch.getText() + "\n\n", rfont)); break; case 2: document.add(new Paragraph( " Tm kim theo tn mn h?c : " + txtSearch.getText() + "\n\n", rfont)); break; } PdfPTable table = new PdfPTable(2); PdfPCell header1 = new PdfPCell(new Paragraph("SubjectId", rfont)); PdfPCell header2 = new PdfPCell(new Paragraph("SubjectName", rfont)); table.addCell(header1); table.addCell(header2); TableModel tableModel = tbSubject.getModel(); for (int i = 0; i < tableModel.getRowCount(); i++) { table.addCell(new PdfPCell(new Paragraph((String) tableModel.getValueAt(i, 0), rfont))); table.addCell(new PdfPCell(new Paragraph((String) tableModel.getValueAt(i, 1), rfont))); } document.add(table); document.add(new Paragraph( "\n Ha Noi, November 4th, 2016\n", rfont)); document.add(new Paragraph( " Teacher\n", rfont)); document.add(new Paragraph( " (Signed and Sealed)\n", rfont)); document.close(); JOptionPane.showMessageDialog(null, "Save success"); } } catch (FileNotFoundException ex) { Logger.getLogger(Statistics.class.getName()).log(Level.SEVERE, null, ex); } catch (DocumentException ex) { Logger.getLogger(Statistics.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton1ActionPerformed /** * @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(UpdateSubject.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(UpdateSubject.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(UpdateSubject.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(UpdateSubject.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 UpdateSubject().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAdd; private javax.swing.JButton btnAddFile; private javax.swing.JButton btnDelete; private javax.swing.JButton btnEdit; private javax.swing.JButton btnExit; private javax.swing.JButton btnSearch; private javax.swing.JComboBox<String> cbSubject; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable tbSubject; private javax.swing.JTextField txtFilterSubjectCode; private javax.swing.JTextField txtFilterSubjectName; private javax.swing.JTextField txtSearch; // End of variables declaration//GEN-END:variables }