numerical.Fibonnaci.java Source code

Java tutorial

Introduction

Here is the source code for numerical.Fibonnaci.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 numerical;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.HeadlessException;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author Cyril
 */
public class Fibonnaci extends javax.swing.JFrame {
    long count;

    /**
     * Creates new form Fibonnaci
     */
    public Fibonnaci() {
        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() {

        f_enter = new javax.swing.JButton();
        txt_sequence_no = new javax.swing.JTextField();
        lbl_sequence_no = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txt_result = new javax.swing.JTextArea();
        btn_save = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Fibonnaci");
        setResizable(false);

        f_enter.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        f_enter.setText("Enter");
        f_enter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                f_enterActionPerformed(evt);
            }
        });

        txt_sequence_no.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txt_sequence_no.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txt_sequence_noKeyPressed(evt);
            }
        });

        lbl_sequence_no.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lbl_sequence_no.setText("Enter Sequence Number:");

        txt_result.setEditable(false);
        txt_result.setColumns(20);
        txt_result.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        txt_result.setRows(5);
        jScrollPane1.setViewportView(txt_result);

        btn_save.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        btn_save.setText("Save as PDF");
        btn_save.setEnabled(false);
        btn_save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_saveActionPerformed(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel6.setText("Result:");

        jLabel9.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel9.setText("Fibonnaci");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup().addComponent(lbl_sequence_no)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txt_sequence_no, javax.swing.GroupLayout.PREFERRED_SIZE, 204,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(f_enter).addGap(18, 18, 18))
                        .addGroup(
                                layout.createSequentialGroup().addComponent(jLabel9).addGap(0, 0, Short.MAX_VALUE))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jScrollPane1)
                                        .addGroup(layout.createSequentialGroup().addGap(0, 0, Short.MAX_VALUE)
                                                .addComponent(btn_save))
                                        .addGroup(layout.createSequentialGroup().addComponent(jLabel6).addGap(362,
                                                362, 362)))
                                .addContainerGap()))));
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel9).addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(f_enter).addComponent(lbl_sequence_no)
                                        .addComponent(txt_sequence_no, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btn_save).addGap(6, 6, 6)));

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

    private void f_enterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_f_enterActionPerformed
        txt_result.setText("");

        long n1 = 1, n2 = 1, n3, i;
        count = Integer.parseInt(txt_sequence_no.getText());
        txt_result.append(n1 + ", " + n2);//printing 0 and 1
        //loop starts from 2 because 0 and 1 are already printed
        for (i = 2; i < count; ++i) {
            n3 = n1 + n2;
            txt_result.append(", " + n3);
            n1 = n2;
            n2 = n3;
        }
        btn_save.setEnabled(true);
    }//GEN-LAST:event_f_enterActionPerformed

    private void txt_sequence_noKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_sequence_noKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            f_enter.doClick();
        }
    }//GEN-LAST:event_txt_sequence_noKeyPressed

    private void btn_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_saveActionPerformed
        JFileChooser jfc = new JFileChooser();
        jfc.setCurrentDirectory(new File("/My Documents"));
        int return_val = jfc.showSaveDialog(rootPane);
        if (return_val == JFileChooser.APPROVE_OPTION) {
            Document doc = new Document();
            try {
                jfc.getSelectedFile();
                PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(jfc.getSelectedFile() + ".pdf"));
                doc.open();

                Font f = new Font(Font.FontFamily.TIMES_ROMAN, 12.0f, Font.NORMAL, BaseColor.BLACK);
                Font f1 = new Font(Font.FontFamily.TIMES_ROMAN, 18.0f, Font.BOLD, BaseColor.BLACK);

                Paragraph paragraph = new Paragraph(null, f);
                Paragraph title = new Paragraph(null, f1);
                title.add("Fibonnaci\n");
                paragraph.add("Sequence number: " + count + "\n");
                paragraph.add("Result: ");
                paragraph.add(txt_result.getText());
                doc.add(title);
                doc.add(paragraph);
                doc.close();
                writer.close();

                JOptionPane.showMessageDialog(rootPane, "Successfully saved!");
            } catch (FileNotFoundException | DocumentException | HeadlessException e) {
                System.err.println(e);
            }
        }
    }//GEN-LAST:event_btn_saveActionPerformed

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

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Fibonnaci().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_save;
    private javax.swing.JButton f_enter;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbl_sequence_no;
    private javax.swing.JTextArea txt_result;
    private javax.swing.JTextField txt_sequence_no;
    // End of variables declaration//GEN-END:variables

}