NEWS: Total Picture Views: 151536 | Total Article Views: 161047 | Top 5 Most Popular Article: 1. Am I Stuck Algorithm with Becker Robot | 2. PickUpThings with Becker Robot | 3. How to read a JSON and work with it | 4. Encrypted Data GUI (Download .Zip) | 5. Create Wall and Things with Becker

Encrypted Data GUI (Download .Zip) Java

Description:

In this example I will be showing a example of a GUI in Java

Code:

/************************************* Launch.java ***********************************/
/*
 * 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 runtime;

import gui.Login;

/**
 *
 * @author Jean-Mathieu
 */
public class Launch {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Login l = new Login();
        l.setVisible(true);
    }
    
}

/************************************* Encryption.java ***********************************/
/*
 * 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 logic;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 *
 * @author Jean-Mathieu
 */
public class Encryption {

    // Iteration count
    int iterationCount = 19;
    String key = "771B229C7331CDDFF98C6DF4DF595E88";
    
    public String encrypt(String text) {
        try {
            SecretKeySpec sks = new SecretKeySpec(hexStringToByteArray(key), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters());
            byte[] encrypted = cipher.doFinal(text.getBytes());
            System.out.println("Ecrypted Succesfully!");
            return byteArrayToHexString(encrypted);
        } catch (Exception e) {
            return e.toString();
        }

    }

    public String decrypt(String text) {
        try {
            SecretKeySpec sks = new SecretKeySpec(hexStringToByteArray(key), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, sks);
            byte[] decrypted = cipher.doFinal(hexStringToByteArray(text));            
            return new String(decrypted);
        } catch (Exception e) {
            return e.toString();
        }

    }

    private static byte[] hexStringToByteArray(String s) {
        byte[] b = new byte[s.length() / 2];
        for (int i = 0; i < b.length; i++) {
            int index = i * 2;
            int v = Integer.parseInt(s.substring(index, index + 2), 16);
            b[i] = (byte) v;
        }
        return b;
    }

    private String byteArrayToHexString(byte[] b) {
        StringBuffer sb = new StringBuffer(b.length * 2);
        for (int i = 0; i < b.length; i++) {
            int v = b[i] & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString().toUpperCase();
    }
}


/************************************* Verification.java ***********************************/
/*
 * 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 logic;

/**
 *
 * @author Jean-Mathieu
 */
public class Verification {

    String username = "sheridan";
    String password = "jmdev";

    public boolean checkLogin(String login, String pass) {
        if (login.equals(username) && pass.equals(password)) {
            return true;
        } else {
            System.out.println(username + " != " + login + " | " + password + " != " + pass);
            return false;
        }

    }

}


/************************************* Constant.java ***********************************/
/*
 * 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 gui;

/**
 *
 * @author Jean-Mathieu
 */
public class Constant {
    public static final int GAP = 5;
}


/************************************* Login.java ***********************************/
/*
 * 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 gui;

import static gui.Constant.GAP;
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import logic.Verification;

/**
 *
 * @author Jean-Mathieu
 */
public class Login extends JFrame{

    private static final String CMD_LOGIN = "login";

    Button btnLogin = new Button("Login");
    Button btnCancel = new Button("Cancel");
    Verification veri = new Verification();

    public JTextField getTxtUsername() {
        return txtUsername;
    }

    public void setTxtUsername(JTextField txtUsername) {
        this.txtUsername = txtUsername;
    }

    public JPasswordField getTxtPassword() {
        return txtPassword;
    }

    public void setTxtPassword(JPasswordField txtPassword) {
        this.txtPassword = txtPassword;
    }
    private static final String CMD_CANCEL = "cancel";
    JTextField txtUsername = new JTextField(10);
    JPasswordField txtPassword = new JPasswordField(10);

    public Login() {
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setTitle("Login");
        setLayout(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.gridheight = 1;
        gbc.gridwidth = 1;
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.insets = new Insets(GAP, GAP, GAP, GAP);
        JLabel lblLogin = new JLabel("Username: ");
        JLabel lblCancel = new JLabel("Password: ");

        btnLogin.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                                boolean log;
                log = veri.checkLogin(getTxtUsername().getText(), getTxtPassword().getText());
                if (log == true) {
                    System.out.println("You are log in!");
                    noteFrame noteF = new noteFrame();
                    noteF.setVisible(true);
                    setVisible(false);
                } else {
                    System.out.println("Please try again. " + getTxtUsername().getText() + " : " + getTxtPassword().getText());
                    
                }
            }
        });
        
        
        btnCancel.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        gbc.gridx = 0;
        gbc.gridy = 0;
        add(lblLogin, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        add(lblCancel, gbc);

        gbc.gridx = 1;
        gbc.gridy = 0;
        add(txtUsername, gbc);

        gbc.gridx = 1;
        gbc.gridy = 1;
        add(txtPassword, gbc);

        gbc.gridx = 0;
        gbc.gridy = 2;
        add(btnLogin, gbc);

        gbc.gridx = 1;
        gbc.gridy = 2;
        add(btnCancel, gbc);
        pack();

    }

 

}


/************************************* noteFrame.java ***********************************/
/*
 * 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 gui;

import java.awt.BorderLayout;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.MenuShortcut;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import logic.Encryption;

/**
 *
 * @author Jean-Mathieu
 */
public class noteFrame extends JFrame implements ActionListener {

    private static final String CMD_NEW_File = "new";
    private static final String CMD_SAVE_File = "save";
    private static final String CMD_LOAD_File = "load";
    private static final String CMD_EXIT_File = "exit";
    private TextArea note = new TextArea(15, 30);

    public noteFrame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setTitle("Encrypt/Decrypt Text");

        add(note, BorderLayout.CENTER);
        buildMenuBar();
        pack();

    }

    private void buildMenuBar() {
        MenuBar menuBar = new MenuBar();
        Menu fileMenu = new Menu("File");

        MenuItem newFileItem = new MenuItem("New File");
        newFileItem.addActionListener(this);
        newFileItem.setShortcut(new MenuShortcut(KeyEvent.VK_N));
        newFileItem.setActionCommand(CMD_NEW_File);

        MenuItem saveFileItem = new MenuItem("Save");
        saveFileItem.setShortcut(new MenuShortcut(KeyEvent.VK_S));
        saveFileItem.addActionListener(this);
        saveFileItem.setActionCommand(CMD_SAVE_File);

        MenuItem loadFileItem = new MenuItem("Open");
        loadFileItem.setShortcut(new MenuShortcut(KeyEvent.VK_0));
        loadFileItem.addActionListener(this);
        loadFileItem.setActionCommand(CMD_LOAD_File);

        MenuItem exitFileItem = new MenuItem("Exit");
        exitFileItem.setShortcut(new MenuShortcut(KeyEvent.VK_0));
        exitFileItem.addActionListener(this);
        exitFileItem.setActionCommand(CMD_EXIT_File);

        fileMenu.add(newFileItem);
        fileMenu.add(saveFileItem);
        fileMenu.add(loadFileItem);
        fileMenu.add(exitFileItem);
        menuBar.add(fileMenu);

        this.setMenuBar(menuBar);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Encryption crypt = new Encryption();

        String command = "";
        String message = "";
        if (e.getSource() instanceof MenuItem) {
            command = ((MenuItem) e.getSource()).getActionCommand();
        }

        System.out.println(command);
        switch (command) {
            case (CMD_NEW_File):
                noteFrame th = new noteFrame();
                th.setVisible(true);
                break;
            case (CMD_LOAD_File):
                File aLoadFile = (getFileLocation());
                ObjectInputStream ois = null;
                FileInputStream fis = null;

                String text = "";
                try {
                    fis = new FileInputStream(aLoadFile);
                    ois = new ObjectInputStream(fis);
                    text = ois.readUTF();
                    try {
                        note.setText(crypt.decrypt(text));
                    } catch (Exception ex) {

                    }

                } catch (EOFException eof) {
                    try {
                        ois.close();
                    } catch (IOException ex) {
                        Logger.getLogger(noteFrame.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } catch (FileNotFoundException ex) {
                    System.out.println("File Not Found...");
                } catch (NullPointerException npe) {
                    System.out.println("File Corrupt please delete it.");
                } catch (IOException ex) {
                    Logger.getLogger(noteFrame.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    try {
                        ois.close();
                    } catch (IOException ex) {
                        Logger.getLogger(noteFrame.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }
                break;
            case (CMD_SAVE_File):
                File aSaveFile = (getFileLocation());

                FileOutputStream fos = null;
                ObjectOutputStream oos;
                oos = null;

                if (!aSaveFile.getParentFile().exists()) {
                    aSaveFile.getParentFile().mkdir();
                }
                try {
                    if (!aSaveFile.exists()) {
                        aSaveFile.createNewFile();
                    } else {

                        aSaveFile.delete();

                        aSaveFile.createNewFile();
                    }
                    if (aSaveFile.length() > 0) {
                        fos = new FileOutputStream(aSaveFile, true);
                    } else {
                        fos = new FileOutputStream(aSaveFile, false);
                    }
                    if (oos == null) {
                        oos = new ObjectOutputStream(fos);
                    }
                    String textToEncrypt = note.getText();

                    oos.writeUTF(crypt.encrypt(textToEncrypt));
                    oos.flush();
                    note.setText("");
                } catch (FileNotFoundException ex) {

                } catch (Exception x) {
                } finally {
                    try {
                        oos.close();
                    } catch (IOException ex) {
                        Logger.getLogger(noteFrame.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                break;

            case (CMD_EXIT_File):
                dispose();
                break;
        }
    }

    public File getFileLocation() {
        File aFile = new File("");
        JFileChooser fileChooser = new JFileChooser();
        int option = fileChooser.showOpenDialog(fileChooser);
        if (option == JFileChooser.APPROVE_OPTION) {
            aFile = fileChooser.getSelectedFile();
        }
        return aFile;
    }

    public TextArea getNote() {
        return note;
    }

    public void setNote(TextArea note) {
        this.note = note;
    }

}
Attachments:

Tags: GUI Try Catch Method Class

Total Views: 2573

My name is Jean-Mathieu

I created this website so other people could enjoy finding useful stuff easier. If you have any question do not hesitate to contact me.

jean8mathieuCreated on 09/26/14 and updated on 09/26/14


affiliate_link

Disclosure: We are a website that needs compensation to operate like any other website on the internet.
We may receive consideration for our reviews but we are totally unbiased and do not accept paid reviews or fake reviews claiming to be something they are not.