com.thelinh.gui.PreviewExam.java Source code

Java tutorial

Introduction

Here is the source code for com.thelinh.gui.PreviewExam.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 com.thelinh.gui;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
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.model.Answer;
import com.thelinh.model.AnswerSql;
import com.thelinh.model.Exam;
import com.thelinh.model.ExamSql;
import com.thelinh.model.Question;
import com.thelinh.model.Subject;
import java.awt.Desktop;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author hoangkien
 */
public class PreviewExam extends javax.swing.JDialog {

    private ArrayList<Question> questionList;
    private Font times_13;
    private Font times_15;
    private Font timesBold_25;
    private Font timesBold_15;

    private int examId = 0;
    private Subject subject;
    private ManageExam superParent;

    /**
     * Creates new form PreviewExam
     */
    public PreviewExam(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.superParent = null;
        try {
            timesBold_25 = new Font(
                    BaseFont.createFont("resources/fonts/vuTimesBold.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED),
                    25);
            timesBold_15 = new Font(
                    BaseFont.createFont("resources/fonts/vuTimesBold.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED),
                    15);
            times_15 = new Font(
                    BaseFont.createFont("resources/fonts/vuTimes.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 15);
            times_13 = new Font(
                    BaseFont.createFont("resources/fonts/vuTimes.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 13);
        } catch (DocumentException | IOException ex) {
            Logger.getLogger(PreviewExam.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void setExamId(int examId) {
        this.examId = examId;
    }

    public void setSubject(Subject subject) {
        this.subject = subject;
        this.lbSubject.setText(subject.getSubjectName());
    }

    public void setQuestionList(ArrayList<Question> questionList) {
        this.questionList = questionList;
        DefaultTableModel model = (DefaultTableModel) this.tbQuestion.getModel();
        this.lbQuestionCount.setText(String.valueOf(questionList.size()));
        for (int i = 0; i < questionList.size(); i++) {
            Question q = questionList.get(i);
            model.addRow(new Object[] { i + 1, q.getChapter(), q.getQuestion() });
        }
    }

    public void setExamCode(String code) {
        this.txtExamCode.setText(code);
    }

    public void setTime(int time) {
        this.spTime.setValue(time);
    }

    public void setSuperParent(ManageExam superParent) {
        this.superParent = superParent;
    }

    /**
     * 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() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tbQuestion = new javax.swing.JTable();
        btnClose = new javax.swing.JButton();
        btnPrint = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        lbSubject = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtExamCode = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        lbQuestionCount = new javax.swing.JLabel();
        btnSave = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        spTime = new javax.swing.JSpinner();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Xem trc");

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

        }, new String[] { "S th t", "Chng", "Cu h?i" }));
        jScrollPane1.setViewportView(tbQuestion);

        btnClose.setText("?ng");
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });

        btnPrint.setText("In");
        btnPrint.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPrintActionPerformed(evt);
            }
        });

        jLabel1.setText("Mn:");

        lbSubject.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N

        jLabel2.setText("Nhp m ?:");

        jLabel3.setText("S cu h?i: ");

        lbQuestionCount.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lbQuestionCount.setText("0");

        btnSave.setText("Lu");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        jLabel4.setText("Th?i gian lm bi(pht):");

        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, 538, Short.MAX_VALUE)
                .addGroup(layout.createSequentialGroup().addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                        layout.createSequentialGroup().addComponent(jLabel4)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(spTime).addGap(18, 18, 18).addComponent(jLabel2)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(txtExamCode, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        76, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(btnPrint)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(btnSave)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(btnClose))
                                .addGroup(layout.createSequentialGroup().addComponent(jLabel1)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(lbSubject, javax.swing.GroupLayout.PREFERRED_SIZE, 103,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(108, 108, 108).addComponent(jLabel3)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(lbQuestionCount, javax.swing.GroupLayout.PREFERRED_SIZE, 74,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(0, 0, Short.MAX_VALUE)))
                        .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(lbSubject, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel3).addComponent(lbQuestionCount)))
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
                        .addGap(13, 13, 13)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(btnClose).addComponent(btnPrint)
                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 14,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(txtExamCode, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(btnSave).addComponent(jLabel4).addComponent(spTime,
                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap()));

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

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCloseActionPerformed

    private void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrintActionPerformed
        if (this.txtExamCode.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Hy nhp m ?");
        } else {
            JFileChooser fc = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF files (*.pdf)", "pdf");
            fc.setFileFilter(filter);
            int rt = fc.showSaveDialog(this);
            if (rt == JFileChooser.APPROVE_OPTION) {
                String filepath = fc.getSelectedFile().getPath();
                if (filepath.indexOf(".") == -1) {
                    filepath = filepath + ".pdf";
                }
                String dafilepath = (new StringBuffer(filepath)).insert(filepath.length() - 4, ".da").toString();
                try {
                    Document document = new Document();
                    PdfWriter.getInstance(document, new FileOutputStream(filepath));
                    document.open();

                    // Add title
                    Paragraph p = new Paragraph("Tr?ng ?i h?c Bch Khoa H Ni", timesBold_25);
                    p.setAlignment(Element.ALIGN_CENTER);
                    p.setSpacingAfter(5);
                    document.add(p);

                    p = new Paragraph("?? thi mn " + this.lbSubject.getText(), timesBold_25);
                    p.setAlignment(Element.ALIGN_CENTER);
                    p.setSpacingAfter(25);
                    document.add(p);

                    p = new Paragraph(
                            "Ng?i ra ?: " + Controller.getCurrentAdmin().getAdminName()
                                    + ", Ngy ra ?: "
                                    + (new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime())),
                            times_15);
                    p.setAlignment(Element.ALIGN_LEFT);
                    p.setSpacingAfter(5);
                    document.add(p);

                    p = new Paragraph("M ?: " + this.txtExamCode.getText() + "    Th?i gian lm bi: "
                            + spTime.getValue().toString() + " pht", timesBold_15);
                    p.setSpacingAfter(25);
                    document.add(p);

                    for (int i = 0; i < this.questionList.size(); i++) {
                        Question question = this.questionList.get(i);
                        ArrayList<Answer> answerList = AnswerSql
                                .getAnswersByQuestionId(question.getQuestionId().trim());
                        Phrase questionNumber = new Phrase("Cu " + (i + 1) + ": ", timesBold_15);
                        Phrase questionContent = new Phrase(question.getQuestion(), times_15);

                        Paragraph questionTitle = new Paragraph();
                        questionTitle.add(questionNumber);
                        questionTitle.add(questionContent);

                        document.add(questionTitle);
                        PdfPTable table = new PdfPTable(2);

                        for (int j = 0; j < answerList.size(); j++) {
                            Answer ans = answerList.get(j);
                            Phrase cap = new Phrase(Character.toString((char) (j + 65)) + ". ", timesBold_15);
                            Phrase answerContent = new Phrase(ans.getAnswer(), times_15);
                            Phrase elem = new Phrase();
                            elem.add(cap);
                            elem.add(answerContent);
                            PdfPCell cell = new PdfPCell();

                            cell.setBorder(Rectangle.NO_BORDER);
                            cell.setPhrase(elem);
                            cell.setFixedHeight(25);
                            table.addCell(cell);
                        }
                        document.add(table);
                    }
                    document.close();
                    //                    if (Desktop.isDesktopSupported()) {
                    //                        try {
                    //                            File myFile = new File(filepath);
                    //                            Desktop.getDesktop().open(myFile);
                    //                        } catch (IOException ex) {
                    //                            // no application registered for PDFs
                    //                            System.out.println(ex.toString());
                    //                        }
                    //                    }

                    document = new Document();
                    PdfWriter.getInstance(document, new FileOutputStream(dafilepath));
                    document.open();

                    // Add title
                    p = new Paragraph("Tr?ng ?i h?c Bch Khoa H Ni", timesBold_25);
                    p.setAlignment(Element.ALIGN_CENTER);
                    p.setSpacingAfter(5);
                    document.add(p);

                    p = new Paragraph("?? thi mn " + this.lbSubject.getText(), timesBold_25);
                    p.setAlignment(Element.ALIGN_CENTER);
                    p.setSpacingAfter(25);
                    document.add(p);

                    p = new Paragraph(
                            "Ng?i ra ?: " + Controller.getCurrentAdmin().getAdminName()
                                    + ", Ngy ra ?: "
                                    + (new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime())),
                            times_15);
                    p.setAlignment(Element.ALIGN_LEFT);
                    p.setSpacingAfter(5);
                    document.add(p);

                    p = new Paragraph("M ?: " + this.txtExamCode.getText() + "    Th?i gian lm bi: "
                            + spTime.getValue().toString() + " pht", timesBold_15);
                    p.setSpacingAfter(25);
                    document.add(p);

                    for (int i = 0; i < this.questionList.size(); i++) {
                        Question question = this.questionList.get(i);
                        ArrayList<Answer> answerList = AnswerSql
                                .getAnswersByQuestionId(question.getQuestionId().trim());
                        Phrase questionNumber = new Phrase("Cu " + (i + 1) + ": ", timesBold_15);
                        Phrase questionContent = new Phrase(question.getQuestion(), times_15);

                        Paragraph questionTitle = new Paragraph();
                        questionTitle.add(questionNumber);
                        questionTitle.add(questionContent);

                        document.add(questionTitle);
                        PdfPTable table = new PdfPTable(2);

                        for (int j = 0; j < answerList.size(); j++) {
                            Answer ans = answerList.get(j);
                            Phrase cap = new Phrase(Character.toString((char) (j + 65)) + ". ", timesBold_15);
                            Phrase answerContent = null;
                            if (ans.getYesNo()) {
                                answerContent = new Phrase(ans.getAnswer(), timesBold_15);
                            } else {
                                answerContent = new Phrase(ans.getAnswer(), times_15);
                            }
                            Phrase elem = new Phrase();
                            elem.add(cap);
                            elem.add(answerContent);
                            PdfPCell cell = new PdfPCell();

                            cell.setBorder(Rectangle.NO_BORDER);
                            cell.setPhrase(elem);
                            cell.setFixedHeight(25);
                            table.addCell(cell);
                        }
                        document.add(table);
                    }
                    document.close();

                } catch (FileNotFoundException | DocumentException ex) {
                    Logger.getLogger(PreviewExam.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }//GEN-LAST:event_btnPrintActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        Exam exam = new Exam();
        exam.setExamId(examId);
        exam.setExamCode(this.txtExamCode.getText());
        exam.setSubject(subject);
        exam.setTime((int) this.spTime.getValue());
        exam.setQuestionList(questionList);
        if (ExamSql.saveExam(exam)) {
            JOptionPane.showMessageDialog(this, "Save exam success");
        }
        this.btnSave.setEnabled(false);
        if (this.superParent != null) {
            this.superParent.reloadTable();
        }
    }//GEN-LAST:event_btnSaveActionPerformed

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

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                PreviewExam dialog = new PreviewExam(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnPrint;
    private javax.swing.JButton btnSave;
    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.JLabel lbQuestionCount;
    private javax.swing.JLabel lbSubject;
    private javax.swing.JSpinner spTime;
    private javax.swing.JTable tbQuestion;
    private javax.swing.JTextField txtExamCode;
    // End of variables declaration//GEN-END:variables
}