Thursday 22 August 2013

How to make Notepad Application in Java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jNotepad.java
 *
 * Created on Dec 23, 2012, 3:45:03 PM
 */
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.TextEvent;
import java.io.*;
import javax.swing.JOptionPane;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
/**
 *
 * @author SENGHAK
 */
public class jNotepad extends javax.swing.JFrame {
    String programName = "Notepad";
    String filename = "";
    String holdText;
    String fn;
    String dir;

    boolean textChanged  =false;

    String fileName;
    Clipboard clip = getToolkit().getSystemClipboard();
    /** Creates new form jNotepad */
    public jNotepad() {
        initComponents();
    }
    public void checkFile() {
        BufferedReader read;
        StringBuffer sb = new StringBuffer();
        try {
            read = new BufferedReader(new FileReader(fileName));
            String line;
            while ((line = read.readLine()) != null) {
                sb.append(line + "\n");
            }
            textArea.setText(sb.toString());
            read.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found");
        } catch (IOException ioe) {
        }
    }
    /** 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() {

        dialogeColor = new javax.swing.JDialog();
        colorChooser = new javax.swing.JColorChooser();
        btnOK = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        textArea = new java.awt.TextArea();
        jMenuBar1 = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        newMenu = new javax.swing.JMenuItem();
        openMenu = new javax.swing.JMenuItem();
        saveMenu = new javax.swing.JMenuItem();
        saveasMenu = new javax.swing.JMenuItem();
        exitMenu = new javax.swing.JMenuItem();
        editMenu = new javax.swing.JMenu();
        colorMenu = new javax.swing.JMenuItem();

        btnOK.setText("OK");
        btnOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOKActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");

        javax.swing.GroupLayout dialogeColorLayout = new javax.swing.GroupLayout(dialogeColor.getContentPane());
        dialogeColor.getContentPane().setLayout(dialogeColorLayout);
        dialogeColorLayout.setHorizontalGroup(
            dialogeColorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(dialogeColorLayout.createSequentialGroup()
                .addGroup(dialogeColorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(dialogeColorLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(colorChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 583, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(dialogeColorLayout.createSequentialGroup()
                        .addGap(230, 230, 230)
                        .addComponent(btnOK)
                        .addGap(18, 18, 18)
                        .addComponent(btnCancel)))
                .addContainerGap(90, Short.MAX_VALUE))
        );
        dialogeColorLayout.setVerticalGroup(
            dialogeColorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(dialogeColorLayout.createSequentialGroup()
                .addComponent(colorChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 278, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addGroup(dialogeColorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnOK, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(19, Short.MAX_VALUE))
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("SENGHAK - Notepad");
        setAlwaysOnTop(true);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        textArea.addTextListener(new java.awt.event.TextListener() {
            public void textValueChanged(java.awt.event.TextEvent evt) {
                textAreaTextValueChanged(evt);
            }
        });

        fileMenu.setText("File");
        fileMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileMenuActionPerformed(evt);
            }
        });

        newMenu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        newMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/new.png"))); // NOI18N
        newMenu.setText("New");
        newMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newMenuActionPerformed(evt);
            }
        });
        fileMenu.add(newMenu);

        openMenu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        openMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/open.png"))); // NOI18N
        openMenu.setText("Open");
        openMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openMenuActionPerformed(evt);
            }
        });
        fileMenu.add(openMenu);

        saveMenu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        saveMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/save.png"))); // NOI18N
        saveMenu.setText("Save");
        saveMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveMenuActionPerformed(evt);
            }
        });
        fileMenu.add(saveMenu);

        saveasMenu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        saveasMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/saveas.png"))); // NOI18N
        saveasMenu.setText("Save As");
        saveasMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveasMenuActionPerformed(evt);
            }
        });
        fileMenu.add(saveasMenu);

        exitMenu.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
        exitMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/exit.png"))); // NOI18N
        exitMenu.setText("Exit");
        exitMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenu);

        jMenuBar1.add(fileMenu);

        editMenu.setText("Edit");

        colorMenu.setIcon(new javax.swing.ImageIcon("D:\\ITB\\Java\\icon\\Notepad\\color1.png")); // NOI18N
        colorMenu.setText("Text Color");
        colorMenu.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                colorMenuComponentResized(evt);
            }
        });
        colorMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                colorMenuActionPerformed(evt);
            }
        });
        editMenu.add(colorMenu);

        jMenuBar1.add(editMenu);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(textArea, javax.swing.GroupLayout.DEFAULT_SIZE, 514, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(textArea, javax.swing.GroupLayout.DEFAULT_SIZE, 328, Short.MAX_VALUE)
        );

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

private void newMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newMenuActionPerformed
// TODO add your handling code here:
    newFile();
}//GEN-LAST:event_newMenuActionPerformed

private void openMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openMenuActionPerformed
// TODO add your handling code here:
    if(textArea.getText().length() < 1){
        FileDialog fd = new FileDialog(this, "Choose File", FileDialog.LOAD);
        fd.show();
        if (fd.getFile() != null) {
            fileName = fd.getDirectory() + fd.getFile();
            setTitle(fileName);
            checkFile();
        }
        textArea.requestFocus();
     }
     else if(!textChanged){
        FileDialog fd = new FileDialog(this, "Choose File", FileDialog.LOAD);
        fd.show();
        if (fd.getFile() != null) {
            fileName = fd.getDirectory() + fd.getFile();
            setTitle(fileName);
            checkFile();
        }
        textArea.requestFocus();
     }
     else{
            int confirm = JOptionPane.showConfirmDialog(null, "Do you want to save befor exiting this program?", "Notepad",JOptionPane.YES_NO_CANCEL_OPTION);
            if (confirm==JOptionPane.YES_OPTION)
            {
                if("".equals(filename)){
                saveAs();
                }
                else{
                    save(filename);
                }
            FileDialog fd = new FileDialog(this, "Choose File", FileDialog.LOAD);
            fd.show();
            if (fd.getFile() != null) {
                fileName = fd.getDirectory() + fd.getFile();
                setTitle(fileName);
                checkFile();
            }
            textArea.requestFocus();

            }
            else if(confirm == JOptionPane.NO_OPTION){
                FileDialog fd = new FileDialog(this, "Choose File", FileDialog.LOAD);
                fd.show();
                if (fd.getFile() != null) {
                    fileName = fd.getDirectory() + fd.getFile();
                    setTitle(fileName);
                    checkFile();
                }
                textArea.requestFocus();
            }

        }

}//GEN-LAST:event_openMenuActionPerformed

private void saveMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveMenuActionPerformed
// TODO add your handling code here:
      if(filename.equals(""))
            saveAs();
       else
            save(filename);
}//GEN-LAST:event_saveMenuActionPerformed

private void exitMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuActionPerformed
// TODO add your handling code here:
    if("".equals(textArea.getText())){
        System.exit(0);
    }
    else if(!textChanged){
        System.exit(0);
    }
    else{
        int confirm = JOptionPane.showConfirmDialog(this, "Do you want to save befor exiting this program?");
        if (confirm==JOptionPane.YES_OPTION){
            if(filename.equals(""))
                saveAs();
            else
                save(filename);
        }
        if (confirm==JOptionPane.NO_OPTION)
        {
            System.exit(0);
        }
    }
}//GEN-LAST:event_exitMenuActionPerformed

private void fileMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_fileMenuActionPerformed

private void saveasMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveasMenuActionPerformed
// TODO add your handling code here:
    saveAs();
}//GEN-LAST:event_saveasMenuActionPerformed

private void colorMenuComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_colorMenuComponentResized
// TODO add your handling code here:
}//GEN-LAST:event_colorMenuComponentResized

private void colorMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_colorMenuActionPerformed
// TODO add your handling code here:
    Color c = colorChooser.showDialog(null, "Color Dialog", textArea.getForeground());
    textArea.setForeground(c);
}//GEN-LAST:event_colorMenuActionPerformed

private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed
// TODO add your handling code here:

}//GEN-LAST:event_btnOKActionPerformed

private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
// TODO add your handling code here:
    if("".equals(textArea.getText())){
        System.exit(0);
    }
    else if(!textChanged){
        System.exit(0);
    }
    else{
        int confirm = JOptionPane.showConfirmDialog(this, "Do you want to save befor exiting this program?");
        if (confirm==JOptionPane.YES_OPTION){
            if(filename.equals(""))
                saveAs();
            else
                save(filename);
        }
        if (confirm==JOptionPane.NO_OPTION)
        {
            System.exit(0);
        }
    }
}//GEN-LAST:event_formWindowClosing

private void textAreaTextValueChanged(java.awt.event.TextEvent evt) {//GEN-FIRST:event_textAreaTextValueChanged
// TODO add your handling code here:
    if(TextEvent.TEXT_VALUE_CHANGED!=0)
        {
            if(!textChanged)
                setTitle("* "+getTitle());
            textChanged=true;
            saveMenu.setEnabled(true);
        }
}//GEN-LAST:event_textAreaTextValueChanged

    /**
     * @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(jNotepad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(jNotepad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(jNotepad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(jNotepad.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 jNotepad().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnOK;
    private javax.swing.JColorChooser colorChooser;
    private javax.swing.JMenuItem colorMenu;
    private javax.swing.JDialog dialogeColor;
    private javax.swing.JMenu editMenu;
    private javax.swing.JMenuItem exitMenu;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem newMenu;
    private javax.swing.JMenuItem openMenu;
    private javax.swing.JMenuItem saveMenu;
    private javax.swing.JMenuItem saveasMenu;
    private java.awt.TextArea textArea;
    // End of variables declaration//GEN-END:variables

    private void save(String fn){
        setTitle(programName+" "+filename);
        try
        {
            FileWriter out;
            out = new FileWriter(fn);
            out.write(textArea.getText());
            out.close();
        }
        catch(Exception err)
        {
            System.out.println("Error: " + err);
        }
        textChanged=false;
        saveMenu.setEnabled(false);

    }

    //function sava as
    private void saveAs() {
        FileDialog fd = new FileDialog(jNotepad.this, "Save", FileDialog.SAVE);
        fd.show();
        if (fd.getFile() != null) {

            fn=fd.getFile();
            dir=fd.getDirectory();
            filename = dir + fn +".txt";

            setTitle(filename);
            try
            {
                DataOutputStream d = new DataOutputStream(new FileOutputStream(filename));
                holdText = textArea.getText();
                BufferedReader br = new BufferedReader(new StringReader(holdText));
                while ((holdText = br.readLine()) != null)
                {
                    d.writeBytes(holdText + "\r\n");
                    d.close();
                }
            }
            catch (Exception e)
            {
                System.out.println("File note found");
            }
            textArea.requestFocus();
            save(filename);
        }
    }

    private void newFile() {

        if(textArea.getText().length() < 1){
            setTitle("Untitled-"+programName);
            textArea.setText("");
            textChanged=false;
        }
        else if(!textChanged){
            setTitle("Untitled-"+programName);
            textArea.setText("");
            textChanged=false;
        }
        else{
            int confirm = JOptionPane.showConfirmDialog(null, "Do you want to save befor exiting this program?", "Notepad",JOptionPane.YES_NO_CANCEL_OPTION);
            if (confirm==JOptionPane.YES_OPTION)
            {
                if("".equals(filename)){
                saveAs();
                }
                else{
                    save(filename);
                }
                setTitle(programName);
                filename="";
                textArea.setText("");
                textChanged=false;

            }
            else if(confirm == JOptionPane.NO_OPTION){
                setTitle(programName);
                textArea.setText("");
                textChanged=false;
            }
            /*setTitle("Untitled-"+programName);
            textArea.setText("");
            textChanged=false; */
        }
    }
}

Tuesday 6 November 2012

Cursion in C Programming Language

This video is about recursion in C programming language which used to calculate facterial value.

You can also visit this video at youtube.com by click this link below:

http://www.youtube.com/watch?v=cfUtnyaT3wQ&feature=youtu.be

Sunday 4 November 2012

C Structure insert ten student data


This is a source code about a program which can be used to insert student's information. The user can insert ten students only. The information about the students such as Number, nim, name, and value. After user input information about the students already, the program will show ten record of the students.

Source code:


#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int k;
    struct data
    {
        int number;
        char nim[20];
        char name[20];
        char value;
    };
    struct data st[10];
    printf("Input students' information\n");
    for (k=0;k<10;k++)
    {
        printf("Input Data %d \n",k+1);
        printf("Number : ");
        fflush(stdin);
        scanf("%d", &st[k].number);
        fflush(stdin);
        printf("NIM : ");
        scanf("%s", &st[k].nim);
        fflush(stdin);
        printf("Name : ");
        scanf("%s", &st[k].name);
        fflush(stdin);
        printf("Value : ");
        scanf("%c", &st[k].value);
    }

    for (k=0;k<10;k++)
    {
        printf("\nYour Data %d \n",k);
        printf("Number : %d", st[k].number);
        printf("\nNIM : %s", st[k].nim);
        printf("\nName : %s", st[k].name);
        printf("\nValue : %c", st[k].value);
    }
    system("pause");
    return 0;
}

This is about the video or you can also see it at youtube.com by click this link below: 
http://www.youtube.com/watch?v=EurlFTnlQ0A&feature=youtu.be

http://www.youtube.com/watch?v=EurlFTnlQ0A&feature=youtu.be

Thursday 1 November 2012

Array(define the array's element and average it)


This is a video in C programming language about array. In this video, the element of array need to input from keyboard. After input the number of array, the program will sum the value of each index of array, the average it.

You can visit this video at youtube.com by click this link below:
http://www.youtube.com/watch?v=9KLNvW16WKE&feature=youtu.be

http://www.youtube.com/watch?v=9KLNvW16WKE&feature=youtu.be

Tuesday 30 October 2012

Convert temperature from celcus to farenheit and kekvin in C programming

This is video show you a program to convert the temperature from celcus to farenheit and kelvin. You just input the temperature in celcus, and then the it will convert to farenheit and kelvin.

You can visit it at youtube.com by click the link below:

http://www.youtube.com/watch?v=FVYK9fJbgzQ&feature=youtu.be 


Monday 29 October 2012

Calculate volume of pyramid or volume of square using while with swith

This is a video show you a program to calculate the volume of pyramid or volume of square. This video, you can choose only one to calculate. If you you choose number 1, the program will calculate the volume of pyramid. If you choose number 2, it will calculate the volume of square. After it calculate the volume of pyramid or square already, it will end the program. However, if you input number which is difference from 1 and 2, it will allow you to input again for your choice.

Visit this video in youtube.com
http://www.youtube.com/watch?v=lsJ9wDomkKE&feature=youtu.be


Wednesday 24 October 2012


This is a video about operator in C programming language. It show you how to use operator properly in C programming. In addition, it tell how the operator work in C programming.

In C Programming Language, there are many operator such as Assignment Operators, Arithmetic Operators,  Logical Operators, Bitwise Operators, Assignment Operator, and Misc Operators. However, this article is not mention all bout the operator.

Here is the video about operator in C Programming, or you can visit this video at youtube.com by click the link below:
 http://www.youtube.com/watch?v=XJjHBcT_fK0&feature=youtu.be