Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Displaying database results on a GUI in a JTextArea with button click

  1. #1
    Junior Member
    Join Date
    Feb 2013
    Posts
    20
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Question Displaying database results on a GUI in a JTextArea with button click

    hi, i am creating a file signature analyser and i have hit a brick wall, what i have created is 3 classes, a splash screen (SplashScreen1.java), a gui (ProjectAssignment.java), and another gui that is opened from the first GUI (CompareSignature.java), when this code is ran it gives the ability to view information about a chosen file from a directory, all of this coding works exactly the way i want to apart from i have been told that i need to display the file type of the file in a way that it gets the first few hex values of the file (the file type bytes)...compares it to a database of hex values (25 40 46 34) and display the corresponding file type in the JTextArea with a button click (file type: PDF document). I also have the database coding and the coding that reads the first few bytes of the file to get the file type but for the life of me i do not know how these documents all go together to make the file type display in the JTextArea with a button click, i will attach all my files to this post and if anybody could have a look at them and provide a solution that would be amazing, thank in advance.











    SplashScreen1.java:

    [code=java]
    package splashscreen1;

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;

    public class SplashScreen1 extends JPanel implements ActionListener{
    JButton enterButton;
    private static JFrame frame;

    public SplashScreen1(){
    super(new BorderLayout());
    enterButton = new JButton("Enter");
    enterButton.addActionListener(this);
    enterButton.setBackground(Color.GREEN);
    JPanel Panel = new JPanel();
    JPanel Panel2 = new JPanel();
    JPanel buttonPanel = new JPanel();
    JLabel label = new JLabel("File Signature Analyser Tool");
    JLabel label2 = new JLabel("Created by Thomas Bannister");
    label.setFont(new Font("Arial", 2, 28));
    label2.setFont(new Font("Arial", 2, 14));
    Panel = new JPanel(new FlowLayout(FlowLayout.LEFT));// places at the left
    Panel.add(label);
    Panel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));// places at the left
    Panel2.add(label2);
    buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));// places at the left
    buttonPanel.add(enterButton);
    add(Panel, BorderLayout.NORTH);
    add(Panel2, BorderLayout.CENTER);
    add(buttonPanel, BorderLayout.SOUTH);
    label.setVerticalTextPosition(JLabel.TOP);
    label.setHorizontalTextPosition(JLabel.LEFT);
    label2.setVerticalTextPosition(JLabel.TOP);
    label2.setHorizontalTextPosition(JLabel.LEFT);
    enterButton.setVerticalTextPosition(JLabel.CENTER) ;
    enterButton.setHorizontalTextPosition(JLabel.CENTE R);
    }

    public static void createAndShowGUI(){
    frame = new JFrame("Welcome!");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);
    frame.pack();
    frame.add(new SplashScreen1());
    frame.setSize(500,130);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    }
    public void actionPerformed(ActionEvent e){
    if(e.getSource()==enterButton){
    JFrame frame2 = new JFrame("Compare Signature");
    frame2.add(new ProjectAssignment());
    frame2.setSize(580,245);
    frame2.setLocationRelativeTo(null);
    frame2.setResizable(false);
    frame2.setVisible(true);

    }
    if(e.getSource()==enterButton){
    frame.dispose();
    }
    }
    public static void main(String[] args) {
    createAndShowGUI();
    }
    }








    ProjectAssignment.java:

    package splashscreen1;
     
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import javax.swing.filechooser.FileNameExtensionFilter;
     
    public class ProjectAssignment extends JPanel implements ActionListener{
        static private final String newline = "\n";
        static ArrayList<FileSignature>fileSignatureList;
        private static final int BUFFER_SIZE = 4096;
        private static final int MAX_SIGNATURE_SIZE = 8;
        JButton openButton;
        JButton saveButton;
        JButton about;
        JButton comparison;
        JButton clear;
        JTextArea log;
        JFileChooser fc;
        String fileTypeName;
        double bytes;
        double kilobytes;   
        String hash;
        MessageDigest md;
        FileInputStream fis;
        byte[] dataBytes;
        SimpleDateFormat sdf;
        SimpleDateFormat sdf2;
        FileWriter fstream;
        int count = 2;
        FileNameExtensionFilter extensionFilter;
        JFileChooser saveAsFileChooser;
        File file;
        BufferedWriter outfile;
        String totalString = "";
        byte[] buffer;
        InputStream in;
        int n;
     
    public ProjectAssignment() {
        super(new BorderLayout());
     
        log = new JTextArea(10,50);
        log.setMargin(new Insets(5,5,5,5));
        log.setEditable(false);
        log.setBackground(Color.BLACK);
        log.setForeground(Color.GREEN);
        JScrollPane logScrollPane = new JScrollPane(log);
     
        fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
     
        openButton = new JButton("Open File");
        openButton.addActionListener(this);
        openButton.setBackground(Color.GREEN);
     
        saveButton = new JButton("Save File");
        saveButton.addActionListener(this);
        saveButton.setBackground(Color.GREEN);
     
        about = new JButton("About");
        about.addActionListener(this);
        about.setBackground(Color.GREEN);
     
        comparison = new JButton("Compare Signature");
        comparison.addActionListener(this);
        comparison.setBackground(Color.GREEN);
     
        clear = new JButton("Clear and Reset");
        clear.addActionListener(this);
        clear.setBackground(Color.YELLOW);
     
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(openButton);
        buttonPanel.add(saveButton);
        buttonPanel.add(comparison);
        buttonPanel.add(about);
        buttonPanel.add(clear);
     
        add(buttonPanel, BorderLayout.PAGE_START);
        add(logScrollPane, BorderLayout.CENTER);
    }
    private static void createAndShowGUI(){
        JFrame frame = new JFrame("Get File Signature" );
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new ProjectAssignment());
        frame.pack();
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    public class FileSignature {
        String getHexString() {
            return UseMySQLDB.fileType;
        }
        String getName() {
            return UseMySQLDB.fileExtension;
        }
    }
     
      public static void main(String[] args) throws NoSuchAlgorithmException, FileNotFoundException, IOException, Exception{
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){
                UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
            }
        });
        byte[] buffer = new byte[BUFFER_SIZE];
    		InputStream in = new FileInputStream(args[0]);
    		int n = in.read(buffer, 0, BUFFER_SIZE);
    		int m = n;
    		while ((m < MAX_SIGNATURE_SIZE) && (n > 0)) {
    			n = in.read(buffer, m, BUFFER_SIZE - m);
    			m += n;
    		}
    		in.close();
    	}
        public void actionPerformed(ActionEvent e){
            if(e.getSource() == saveButton){
            saveAs();
            }
            if(e.getSource() == comparison){
            JFrame frame = new JFrame("Compare Signature");
            frame.add(new CompareSignature());
            frame.setSize(580,245);
            frame.setLocationByPlatform(true);
            frame.setResizable(false);
            frame.setVisible(true);
            }
            if(e.getSource() == about){
            JOptionPane optionPane = new JOptionPane("How to use this tool:"+newline+"1. Open a file to view the signature"+newline+"2. Save the file signature in a directory of your choice"+newline+"3. Open the saved document to compare it to the updated document");
            JDialog dialog = optionPane.createDialog("Dialog");
            dialog.setVisible(true);
            }
            if(e.getSource() == openButton){
            int returnVal = fc.showOpenDialog(ProjectAssignment.this);
            fc.setCurrentDirectory(new File(System.getProperty("user.home")));
            if (returnVal == JFileChooser.APPROVE_OPTION){
                File selectedFile = fc.getSelectedFile();
                if(selectedFile.exists()){
                bytes = selectedFile.length();
                kilobytes = (bytes / 1024);
                fileTypeName = fc.getTypeDescription(selectedFile);   
                try {
                        md = MessageDigest.getInstance("MD5");
                    } catch (NoSuchAlgorithmException ex) {
                        Logger.getLogger(CompareSignature.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    try {
                        fis = new FileInputStream(selectedFile);
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(CompareSignature.class.getName()).log(Level.SEVERE, null, ex);
                    }
                dataBytes = new byte[1024];
     
                int nread = 0; 
                    try {
                        while ((nread = fis.read(dataBytes)) != -1) {
                        md.update(dataBytes, 0, nread);
                    }
                    } catch (IOException ex) {
                        Logger.getLogger(CompareSignature.class.getName()).log(Level.SEVERE, null, ex);
                    };
     
                StringBuffer hexString = new StringBuffer();
                byte[] mdbytes = md.digest();
                for (int i=0;i<mdbytes.length;i++) {
        		String hex=Integer.toHexString(0xff & mdbytes[i]);
       	     	if(hex.length()==1) hexString.append('0');
       	     	hexString.append(hex);
     
     
                }
                sdf = new SimpleDateFormat("dd/MM/yyyy");
                sdf2 = new SimpleDateFormat("hh:mm:ss");
                log.append("File Path: " + selectedFile.getAbsolutePath() + "." + newline);
                log.append("File Type: " + fileTypeName + "." + newline);
                log.append("File Size: " + kilobytes + "kb" + newline);
                log.append("MD5 Checksum: " + hexString.toString() + "." + newline);
                log.append("Last Modified Date and Time:" + sdf.format(selectedFile.lastModified()));
                log.append(" " + sdf2.format(selectedFile.lastModified()) + newline + newline);
            }
     
        }
            log.setCaretPosition(log.getDocument().getLength());
            openButton.setEnabled(false);
            }    
     
        if(e.getSource() == clear){
                log.setText("");
                openButton.setEnabled(true);
        }
    }
        public void saveAs(){
            extensionFilter = new FileNameExtensionFilter("Text File", "txt");
            saveAsFileChooser = new JFileChooser();
            saveAsFileChooser.setApproveButtonText("Save");
            saveAsFileChooser.setFileFilter(extensionFilter);
            int actionDialog = saveAsFileChooser.showOpenDialog(this);
            if(actionDialog != JFileChooser.APPROVE_OPTION){
                return;
            }
            file = saveAsFileChooser.getSelectedFile();
            if(!file.getName().endsWith(".txt")){
                file = new File(file.getAbsolutePath() + ".txt");
            }
            BufferedWriter outFile = null;
            try{
                outFile = new BufferedWriter(new FileWriter(file));
                log.write(outFile);
            }catch(IOException ex){
                ex.printStackTrace();
            } finally {
                if (outFile !=null){
                    try{
                        outFile.close();
                    } catch (IOException e){}
                }
            }
        }
    }







    CompareSignature.java:
    package splashscreen1;
     
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.text.SimpleDateFormat;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import javax.swing.filechooser.FileNameExtensionFilter;
     
    public class CompareSignature extends JPanel implements ActionListener{
        static private final String newline = "\n";
        JButton openButton;
        JButton saveButton;
        JButton clear;
        JTextArea log;
        JFileChooser fc;
        String fileTypeName;
        double bytes;
        double kilobytes;   
        String hash;
        MessageDigest md;
        FileInputStream fis;
        byte[] dataBytes;
        SimpleDateFormat sdf;
        SimpleDateFormat sdf2;
        FileWriter fstream;
        FileNameExtensionFilter extensionFilter;
        JFileChooser saveAsFileChooser;
        File file;
        BufferedWriter outfile;
     
    public CompareSignature() {
        super(new BorderLayout());
     
        log = new JTextArea(10,50);
        log.setMargin(new Insets(2,5,5,5));
        log.setEditable(false);
        log.setBackground(Color.BLACK);
        log.setForeground(Color.GREEN);
        JScrollPane logScrollPane = new JScrollPane(log);
     
        fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
     
        openButton = new JButton("Open File");
        openButton.addActionListener(this);
        openButton.setBackground(Color.GREEN);
     
        saveButton = new JButton("Save File");
        saveButton.addActionListener(this);
        saveButton.setBackground(Color.GREEN);
     
        clear = new JButton("Clear and Reset");
        clear.addActionListener(this);
        clear.setBackground(Color.YELLOW);
     
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(openButton);
        buttonPanel.add(saveButton);
        buttonPanel.add(clear);
     
        add(buttonPanel, BorderLayout.PAGE_START);
        add(logScrollPane, BorderLayout.CENTER);
     
     
    }
    private static void createAndShowGUI(){
        JFrame frame = new JFrame("Signature Comparison");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new CompareSignature());
        frame.pack();
        frame.setVisible(true);
    }
      public static void main(String[] args) throws NoSuchAlgorithmException, FileNotFoundException, IOException{
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){
                UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
            }
        }); 
        }
        @Override
        public void actionPerformed(ActionEvent e){
        if(e.getSource() == openButton){
            int returnVal = fc.showOpenDialog(CompareSignature.this);
            fc.setCurrentDirectory(new File(System.getProperty("user.home")));
            if (returnVal == JFileChooser.APPROVE_OPTION){
                File selectedFile = fc.getSelectedFile();
                if(selectedFile.exists()){
                bytes = selectedFile.length();
                kilobytes = (bytes / 1024);
                fileTypeName = fc.getTypeDescription(selectedFile);            
                    try {
                        md = MessageDigest.getInstance("MD5");
                    } catch (NoSuchAlgorithmException ex) {
                        Logger.getLogger(CompareSignature.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    try {
                        fis = new FileInputStream(selectedFile);
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(CompareSignature.class.getName()).log(Level.SEVERE, null, ex);
                    }
                dataBytes = new byte[1024];
     
                int nread = 0; 
                    try {
                        while ((nread = fis.read(dataBytes)) != -1) {
                        md.update(dataBytes, 0, nread);
                    }
                    } catch (IOException ex) {
                        Logger.getLogger(CompareSignature.class.getName()).log(Level.SEVERE, null, ex);
                    };
     
                StringBuffer hexString = new StringBuffer();
                byte[] mdbytes = md.digest();
                for (int i=0;i<mdbytes.length;i++) {
        		String hex=Integer.toHexString(0xff & mdbytes[i]);
       	     	if(hex.length()==1) hexString.append('0');
       	     	hexString.append(hex);
     
     
                }
                sdf = new SimpleDateFormat("dd/MM/yyyy");
                sdf2 = new SimpleDateFormat("hh:mm:ss");
                log.append("File Path: " + selectedFile.getAbsolutePath() + "." + newline);
                log.append("File Type: " + fileTypeName + "." + newline);
                log.append("File Size: " + kilobytes + "kb" + newline);
                log.append("MD5 Checksum: " + hexString.toString() + "." + newline);
                log.append("Last Modified Date and Time:" + sdf.format(selectedFile.lastModified()));
                log.append(" " + sdf2.format(selectedFile.lastModified()) + newline + newline);
            }
     
        }
            log.setCaretPosition(log.getDocument().getLength());
            openButton.setEnabled(false);
            }
        if(e.getSource() == saveButton){
            saveAs();
        }
        if(e.getSource() == clear){
            log.setText("");
            openButton.setEnabled(true);
        }
        log.setCaretPosition(log.getDocument().getLength());
     
    }
     
        public void saveAs(){
            extensionFilter = new FileNameExtensionFilter("Text File", "txt");
            saveAsFileChooser = new JFileChooser();
            saveAsFileChooser.setApproveButtonText("Save");
            saveAsFileChooser.setFileFilter(extensionFilter);
            int actionDialog = saveAsFileChooser.showOpenDialog(this);
            if(actionDialog != JFileChooser.APPROVE_OPTION){
                return;
            }
            file = saveAsFileChooser.getSelectedFile();
            if(!file.getName().endsWith(".txt")){
                file = new File(file.getAbsolutePath() + ".txt");
            }
            BufferedWriter outFile = null;
            try{
                outFile = new BufferedWriter(new FileWriter(file));
                log.write(outFile);
            }catch(IOException ex){
                ex.printStackTrace();
            } finally {
                if (outFile !=null){
                    try{
                        outFile.close();
                    } catch (IOException e){}
                }
            }
        }
    }











    UseMySQLDB.java:
    package splashscreen1;
     
    import java.sql.*;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import javax.swing.JOptionPane;
    import java.sql.Statement;
     
    public class UseMySQLDB {
        static String fileType;
        static String fileExtension;
     
        public static void main(String[] args) {
            try{
            String host = "jdbc:mysql://localhost:3306/schema";
            String uName = "root";
            String uPass = "banni1";
            Connection con = DriverManager.getConnection(host, uName, uPass);
     
            Statement stmt = con.createStatement();
            String sql = "SELECT * from schema.table";
            ResultSet rs = stmt.executeQuery(sql);
     
            while(rs.next()){
            fileType = rs.getString("fileType");
            fileExtension = rs.getString("fileExtension");
            String p = fileType + " " + fileExtension + " ";
            }
            }
            catch(SQLException err){
            System.out.println(err.getMessage());
        }
      }
    }








    FileSignature.java:
    package splashscreen1;
     
    public class FileSignature {
        static String getHexString() {
            return UseMySQLDB.fileType;
        }
        static String getName() {
            return UseMySQLDB.fileExtension;
        }
    }












    RetriveFileType.java:

    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
     
     
    public class RetriveFileType {
    	private static final int BUFFER_SIZE = 4096;
    	private static final int MAX_SIGNATURE_SIZE = 8;
     
     
     
    	private static String matchesSignature(byte[] buffer, int size) {
    		String totalString = "";
     
    		for (int i = 0; i < 10; i++) {
    			String individualHex = Integer.toHexString(buffer[i]);
    			if (individualHex.length() == 1) {
    				individualHex = "0" + individualHex + " ";
    			} else {
    				individualHex += " ";
    			}
    			totalString += individualHex;
    		}
     
    		totalString = totalString.toUpperCase();
    		for (FileSignature fileSignature : Main.fileSignatureList) {
    			if (totalString.startsWith(fileSignature.getHexString())) {
    				return "The file type is: "
    						+ fileSignature.getName();
    			}
    		}
     
    		return "No file type found";
    	}
     
    	public String test(String[] args) throws IOException {
     
     
    		byte[] buffer = new byte[BUFFER_SIZE];
    		InputStream in = new FileInputStream(args[0]);
    		int n = in.read(buffer, 0, BUFFER_SIZE);
    		int m = n;
    		while ((m < MAX_SIGNATURE_SIZE) && (n > 0)) {
    			n = in.read(buffer, m, BUFFER_SIZE - m);
    			m += n;
    		}
    		in.close();
    		return matchesSignature(buffer, m);
    	}
    }
    Last edited by tomb1992; February 27th, 2013 at 08:55 PM. Reason: wrapped code


  2. #2
    Administrator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    24,848
    Thanks
    64
    Thanked 2,645 Times in 2,615 Posts

    Default Re: Displaying database results on a GUI in a JTextArea with button click

    Please edit your post and wrap your code with
    [code=java]
    <YOUR CODE HERE>
    [/code]
    to get highlighting and preserve formatting.

  3. #3
    Junior Member
    Join Date
    Feb 2013
    Posts
    20
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Displaying database results on a GUI in a JTextArea with button click

    hi, i am making a file signature analyser. i have written 3 classes which are GUI's, i have also written a class that connects to a database and i have a class that gets the first few hex bytes from a file (the ones that state the files type).

    so basically the first gui (SplashScreen1.java) is just an enter screen, the second one (ProjectAssignment.java) has a jtextarea on it , this is where you can open a file from your directory to see some information about the file and the third gui is a copy of the second gui which is opened with a button in the second gui.

    The thing i want it to do is that i want the open button to be clicked and for the files hex (25 40 46 34) to be read and compared with my database and for the file type to be then to be displayed in my TextArea (file type is: pdf file).

    My database has 2 columns:
    file type
    files hex

    I think i have all the coding but i just dont know how it all goes together, any help would be much appreciated, the coding is below:



    SplashScreen1.java:
    package splashscreen1;
     
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
     
    public class SplashScreen1 extends JPanel implements ActionListener{
    JButton enterButton;
    private static JFrame frame;
     
     public SplashScreen1(){
         super(new BorderLayout());
         enterButton = new JButton("Enter");
         enterButton.addActionListener(this);
         enterButton.setBackground(Color.GREEN);
         JPanel Panel = new JPanel();
         JPanel Panel2 = new JPanel();
         JPanel buttonPanel = new JPanel();
         JLabel label = new JLabel("File Signature Analyser Tool");
         JLabel label2 = new JLabel("Created by Thomas Bannister");
         label.setFont(new Font("Arial", 2, 28));
         label2.setFont(new Font("Arial", 2, 14));
         Panel = new JPanel(new FlowLayout(FlowLayout.LEFT));// places at the left
         Panel.add(label);
         Panel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));// places at the left
         Panel2.add(label2);
         buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));// places at the left
         buttonPanel.add(enterButton);
         add(Panel, BorderLayout.NORTH);
         add(Panel2, BorderLayout.CENTER);
         add(buttonPanel, BorderLayout.SOUTH);
         label.setVerticalTextPosition(JLabel.TOP);
         label.setHorizontalTextPosition(JLabel.LEFT);
         label2.setVerticalTextPosition(JLabel.TOP);
         label2.setHorizontalTextPosition(JLabel.LEFT);
         enterButton.setVerticalTextPosition(JLabel.CENTER);
         enterButton.setHorizontalTextPosition(JLabel.CENTER);
     }
     
    public static void createAndShowGUI(){
        frame = new JFrame("Welcome!");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.add(new SplashScreen1());
        frame.setSize(500,130);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    public void actionPerformed(ActionEvent e){
        if(e.getSource()==enterButton){
            JFrame frame2 = new JFrame("Compare Signature");
            frame2.add(new ProjectAssignment());
            frame2.setSize(580,245);
            frame2.setLocationRelativeTo(null);
            frame2.setResizable(false);
            frame2.setVisible(true);
     
            }
        if(e.getSource()==enterButton){
            frame.dispose();
        }
        }
        public static void main(String[] args) {
            createAndShowGUI();
        }
    }



    ProjectAssignment.java:
    package splashscreen1;
     
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import javax.swing.filechooser.FileNameExtensionFilter;
     
    public class ProjectAssignment extends JPanel implements ActionListener{
        static private final String newline = "\n";
        static ArrayList<FileSignature>fileSignatureList;
        private static final int BUFFER_SIZE = 4096;
        private static final int MAX_SIGNATURE_SIZE = 8;
        JButton openButton;
        JButton saveButton;
        JButton about;
        JButton comparison;
        JButton clear;
        JTextArea log;
        JFileChooser fc;
        String fileTypeName;
        double bytes;
        double kilobytes;   
        String hash;
        MessageDigest md;
        FileInputStream fis;
        byte[] dataBytes;
        SimpleDateFormat sdf;
        SimpleDateFormat sdf2;
        FileWriter fstream;
        int count = 2;
        FileNameExtensionFilter extensionFilter;
        JFileChooser saveAsFileChooser;
        File file;
        BufferedWriter outfile;
        String totalString = "";
        byte[] buffer;
        InputStream in;
        int n;
     
    public ProjectAssignment() {
        super(new BorderLayout());
     
        log = new JTextArea(10,50);
        log.setMargin(new Insets(5,5,5,5));
        log.setEditable(false);
        log.setBackground(Color.BLACK);
        log.setForeground(Color.GREEN);
        JScrollPane logScrollPane = new JScrollPane(log);
     
        fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
     
        openButton = new JButton("Open File");
        openButton.addActionListener(this);
        openButton.setBackground(Color.GREEN);
     
        saveButton = new JButton("Save File");
        saveButton.addActionListener(this);
        saveButton.setBackground(Color.GREEN);
     
        about = new JButton("About");
        about.addActionListener(this);
        about.setBackground(Color.GREEN);
     
        comparison = new JButton("Compare Signature");
        comparison.addActionListener(this);
        comparison.setBackground(Color.GREEN);
     
        clear = new JButton("Clear and Reset");
        clear.addActionListener(this);
        clear.setBackground(Color.YELLOW);
     
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(openButton);
        buttonPanel.add(saveButton);
        buttonPanel.add(comparison);
        buttonPanel.add(about);
        buttonPanel.add(clear);
     
        add(buttonPanel, BorderLayout.PAGE_START);
        add(logScrollPane, BorderLayout.CENTER);
    }
    private static void createAndShowGUI(){
        JFrame frame = new JFrame("Get File Signature" );
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new ProjectAssignment());
        frame.pack();
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    public class FileSignature {
        String getHexString() {
            return UseMySQLDB.fileType;
        }
        String getName() {
            return UseMySQLDB.fileExtension;
        }
    }
     
      public static void main(String[] args) throws NoSuchAlgorithmException, FileNotFoundException, IOException, Exception{
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){
                UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
            }
        });
        byte[] buffer = new byte[BUFFER_SIZE];
    		InputStream in = new FileInputStream(args[0]);
    		int n = in.read(buffer, 0, BUFFER_SIZE);
    		int m = n;
    		while ((m < MAX_SIGNATURE_SIZE) && (n > 0)) {
    			n = in.read(buffer, m, BUFFER_SIZE - m);
    			m += n;
    		}
    		in.close();
    	}
        public void actionPerformed(ActionEvent e){
            if(e.getSource() == saveButton){
            saveAs();
            }
            if(e.getSource() == comparison){
            JFrame frame = new JFrame("Compare Signature");
            frame.add(new CompareSignature());
            frame.setSize(580,245);
            frame.setLocationByPlatform(true);
            frame.setResizable(false);
            frame.setVisible(true);
            }
            if(e.getSource() == about){
            JOptionPane optionPane = new JOptionPane("How to use this tool:"+newline+"1. Open a file to view the signature"+newline+"2. Save the file signature in a directory of your choice"+newline+"3. Open the saved document to compare it to the updated document");
            JDialog dialog = optionPane.createDialog("Dialog");
            dialog.setVisible(true);
            }
            if(e.getSource() == openButton){
            int returnVal = fc.showOpenDialog(ProjectAssignment.this);
            fc.setCurrentDirectory(new File(System.getProperty("user.home")));
            if (returnVal == JFileChooser.APPROVE_OPTION){
                File selectedFile = fc.getSelectedFile();
                if(selectedFile.exists()){
                bytes = selectedFile.length();
                kilobytes = (bytes / 1024);
                fileTypeName = fc.getTypeDescription(selectedFile);   
                try {
                        md = MessageDigest.getInstance("MD5");
                    } catch (NoSuchAlgorithmException ex) {
                        Logger.getLogger(CompareSignature.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    try {
                        fis = new FileInputStream(selectedFile);
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(CompareSignature.class.getName()).log(Level.SEVERE, null, ex);
                    }
                dataBytes = new byte[1024];
     
                int nread = 0; 
                    try {
                        while ((nread = fis.read(dataBytes)) != -1) {
                        md.update(dataBytes, 0, nread);
                    }
                    } catch (IOException ex) {
                        Logger.getLogger(CompareSignature.class.getName()).log(Level.SEVERE, null, ex);
                    };
     
                StringBuffer hexString = new StringBuffer();
                byte[] mdbytes = md.digest();
                for (int i=0;i<mdbytes.length;i++) {
        		String hex=Integer.toHexString(0xff & mdbytes[i]);
       	     	if(hex.length()==1) hexString.append('0');
       	     	hexString.append(hex);
     
     
                }
                sdf = new SimpleDateFormat("dd/MM/yyyy");
                sdf2 = new SimpleDateFormat("hh:mm:ss");
                log.append("File Path: " + selectedFile.getAbsolutePath() + "." + newline);
                log.append("File Type: " + fileTypeName + "." + newline);
                log.append("File Size: " + kilobytes + "kb" + newline);
                log.append("MD5 Checksum: " + hexString.toString() + "." + newline);
                log.append("Last Modified Date and Time:" + sdf.format(selectedFile.lastModified()));
                log.append(" " + sdf2.format(selectedFile.lastModified()) + newline + newline);
            }
     
        }
            log.setCaretPosition(log.getDocument().getLength());
            openButton.setEnabled(false);
            }    
     
        if(e.getSource() == clear){
                log.setText("");
                openButton.setEnabled(true);
        }
    }
     
     
     
        public void saveAs(){
            extensionFilter = new FileNameExtensionFilter("Text File", "txt");
            saveAsFileChooser = new JFileChooser();
            saveAsFileChooser.setApproveButtonText("Save");
            saveAsFileChooser.setFileFilter(extensionFilter);
            int actionDialog = saveAsFileChooser.showOpenDialog(this);
            if(actionDialog != JFileChooser.APPROVE_OPTION){
                return;
            }
            file = saveAsFileChooser.getSelectedFile();
            if(!file.getName().endsWith(".txt")){
                file = new File(file.getAbsolutePath() + ".txt");
            }
            BufferedWriter outFile = null;
            try{
                outFile = new BufferedWriter(new FileWriter(file));
                log.write(outFile);
            }catch(IOException ex){
                ex.printStackTrace();
            } finally {
                if (outFile !=null){
                    try{
                        outFile.close();
                    } catch (IOException e){}
                }
            }
        }
    }






    CompareSignature.java:

    package splashscreen1;
     
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.text.SimpleDateFormat;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import javax.swing.filechooser.FileNameExtensionFilter;
     
    public class CompareSignature extends JPanel implements ActionListener{
        static private final String newline = "\n";
        JButton openButton;
        JButton saveButton;
        JButton clear;
        JTextArea log;
        JFileChooser fc;
        String fileTypeName;
        double bytes;
        double kilobytes;   
        String hash;
        MessageDigest md;
        FileInputStream fis;
        byte[] dataBytes;
        SimpleDateFormat sdf;
        SimpleDateFormat sdf2;
        FileWriter fstream;
        FileNameExtensionFilter extensionFilter;
        JFileChooser saveAsFileChooser;
        File file;
        BufferedWriter outfile;
     
    public CompareSignature() {
        super(new BorderLayout());
     
        log = new JTextArea(10,50);
        log.setMargin(new Insets(2,5,5,5));
        log.setEditable(false);
        log.setBackground(Color.BLACK);
        log.setForeground(Color.GREEN);
        JScrollPane logScrollPane = new JScrollPane(log);
     
        fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
     
        openButton = new JButton("Open File");
        openButton.addActionListener(this);
        openButton.setBackground(Color.GREEN);
     
        saveButton = new JButton("Save File");
        saveButton.addActionListener(this);
        saveButton.setBackground(Color.GREEN);
     
        clear = new JButton("Clear and Reset");
        clear.addActionListener(this);
        clear.setBackground(Color.YELLOW);
     
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(openButton);
        buttonPanel.add(saveButton);
        buttonPanel.add(clear);
     
        add(buttonPanel, BorderLayout.PAGE_START);
        add(logScrollPane, BorderLayout.CENTER);
     
     
    }
    private static void createAndShowGUI(){
        JFrame frame = new JFrame("Signature Comparison");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new CompareSignature());
        frame.pack();
        frame.setVisible(true);
    }
      public static void main(String[] args) throws NoSuchAlgorithmException, FileNotFoundException, IOException{
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){
                UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
            }
        }); 
        }
        @Override
        public void actionPerformed(ActionEvent e){
        if(e.getSource() == openButton){
            int returnVal = fc.showOpenDialog(CompareSignature.this);
            fc.setCurrentDirectory(new File(System.getProperty("user.home")));
            if (returnVal == JFileChooser.APPROVE_OPTION){
                File selectedFile = fc.getSelectedFile();
                if(selectedFile.exists()){
                bytes = selectedFile.length();
                kilobytes = (bytes / 1024);
                fileTypeName = fc.getTypeDescription(selectedFile);            
                    try {
                        md = MessageDigest.getInstance("MD5");
                    } catch (NoSuchAlgorithmException ex) {
                        Logger.getLogger(CompareSignature.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    try {
                        fis = new FileInputStream(selectedFile);
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(CompareSignature.class.getName()).log(Level.SEVERE, null, ex);
                    }
                dataBytes = new byte[1024];
     
                int nread = 0; 
                    try {
                        while ((nread = fis.read(dataBytes)) != -1) {
                        md.update(dataBytes, 0, nread);
                    }
                    } catch (IOException ex) {
                        Logger.getLogger(CompareSignature.class.getName()).log(Level.SEVERE, null, ex);
                    };
     
                StringBuffer hexString = new StringBuffer();
                byte[] mdbytes = md.digest();
                for (int i=0;i<mdbytes.length;i++) {
        		String hex=Integer.toHexString(0xff & mdbytes[i]);
       	     	if(hex.length()==1) hexString.append('0');
       	     	hexString.append(hex);
     
     
                }
                sdf = new SimpleDateFormat("dd/MM/yyyy");
                sdf2 = new SimpleDateFormat("hh:mm:ss");
                log.append("File Path: " + selectedFile.getAbsolutePath() + "." + newline);
                log.append("File Type: " + fileTypeName + "." + newline);
                log.append("File Size: " + kilobytes + "kb" + newline);
                log.append("MD5 Checksum: " + hexString.toString() + "." + newline);
                log.append("Last Modified Date and Time:" + sdf.format(selectedFile.lastModified()));
                log.append(" " + sdf2.format(selectedFile.lastModified()) + newline + newline);
            }
     
        }
            log.setCaretPosition(log.getDocument().getLength());
            openButton.setEnabled(false);
            }
        if(e.getSource() == saveButton){
            saveAs();
        }
        if(e.getSource() == clear){
            log.setText("");
            openButton.setEnabled(true);
        }
        log.setCaretPosition(log.getDocument().getLength());
     
    }
     
        public void saveAs(){
            extensionFilter = new FileNameExtensionFilter("Text File", "txt");
            saveAsFileChooser = new JFileChooser();
            saveAsFileChooser.setApproveButtonText("Save");
            saveAsFileChooser.setFileFilter(extensionFilter);
            int actionDialog = saveAsFileChooser.showOpenDialog(this);
            if(actionDialog != JFileChooser.APPROVE_OPTION){
                return;
            }
            file = saveAsFileChooser.getSelectedFile();
            if(!file.getName().endsWith(".txt")){
                file = new File(file.getAbsolutePath() + ".txt");
            }
            BufferedWriter outFile = null;
            try{
                outFile = new BufferedWriter(new FileWriter(file));
                log.write(outFile);
            }catch(IOException ex){
                ex.printStackTrace();
            } finally {
                if (outFile !=null){
                    try{
                        outFile.close();
                    } catch (IOException e){}
                }
            }
        }
    }






    FileSignature.java:

    package splashscreen1;
     
    public class FileSignature {
        static String getHexString() {
            return UseMySQLDB.fileType;
        }
        static String getName() {
            return UseMySQLDB.fileExtension;
        }
    }





    UseMySQLDB.java:

    package splashscreen1;
     
    import java.sql.*;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import javax.swing.JOptionPane;
    import java.sql.Statement;
     
    public class UseMySQLDB {
        static String fileType;
        static String fileExtension;
     
        public static void main(String[] args) {
            try{
            String host = "jdbc:mysql://localhost:3306/schema";
            String uName = "root";
            String uPass = "banni1";
            Connection con = DriverManager.getConnection(host, uName, uPass);
     
            Statement stmt = con.createStatement();
            String sql = "SELECT * from schema.table";
            ResultSet rs = stmt.executeQuery(sql);
     
            while(rs.next()){
            fileType = rs.getString("fileType");
            fileExtension = rs.getString("fileExtension");
            String p = fileType + " " + fileExtension + " ";
            }
            }
            catch(SQLException err){
            System.out.println(err.getMessage());
        }
      }
    }


    RetriveFileType.java:

    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
     
    import bean.FileSignature;
     
    public class RetriveFileType {
    	private static final int BUFFER_SIZE = 4096;
    	private static final int MAX_SIGNATURE_SIZE = 8;
     
     
     
    	private static String matchesSignature(byte[] buffer, int size) {
    		String totalString = "";
     
    		for (int i = 0; i < 10; i++) {
    			String individualHex = Integer.toHexString(buffer[i]);
    			if (individualHex.length() == 1) {
    				individualHex = "0" + individualHex + " ";
    			} else {
    				individualHex += " ";
    			}
    			totalString += individualHex;
    		}
     
    		totalString = totalString.toUpperCase();
    		for (FileSignature fileSignature : Main.fileSignatureList) {
    			if (totalString.startsWith(fileSignature.getHexString())) {
    				return "The file type is: "
    						+ fileSignature.getName();
    			}
    		}
     
    		return "No file type found";
    	}
     
    	public String test(String[] args) throws IOException {
     
     
    		byte[] buffer = new byte[BUFFER_SIZE];
    		InputStream in = new FileInputStream(args[0]);
    		int n = in.read(buffer, 0, BUFFER_SIZE);
    		int m = n;
    		while ((m < MAX_SIGNATURE_SIZE) && (n > 0)) {
    			n = in.read(buffer, m, BUFFER_SIZE - m);
    			m += n;
    		}
    		in.close();
    		return matchesSignature(buffer, m);
    	}
    }

  4. #4
    Junior Member
    Join Date
    Feb 2013
    Posts
    20
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Displaying database results on a GUI in a JTextArea with button click

    hi, thanks for your reply, i'm new to this site and accidentally deleted the post but i have set another one up under the same name as i have given this thread, any help you can give me would be great thanks, i have also but the code in the brackets as you have stated

  5. #5
    Administrator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    24,848
    Thanks
    64
    Thanked 2,645 Times in 2,615 Posts

    Default Re: Displaying database results on a GUI in a JTextArea with button click

    Can you be more specific about the problems you are having. This is a lot of code, most of which probably has nothing to do with the problem you are having.

  6. #6
    Junior Member
    Join Date
    Feb 2013
    Posts
    20
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Displaying database results on a GUI in a JTextArea with button click

    i wish i could trim the coding down but it's all revevant, what i need is to some how put the retrivefiletype class into the if(e.getSource==openButton) in the projectAssignment class which will make it so that when the open button is clicked it will get the hex values of the selectedFile, then i need it to somehow compare this data to a database of file signatures and then print out the corresponding file type in the row, for example, if the user selects a pdf file, the codng should get for example 25 40 46 34 from the selected file, and then match it with the pdf row in the database where it should then print the file type as (the file type of this file is: PDF file) in my JTextArea in the projectAssignment class, i am at a loss with this coding, i am at a brick wall

  7. #7
    Administrator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    24,848
    Thanks
    64
    Thanked 2,645 Times in 2,615 Posts

    Default Re: Displaying database results on a GUI in a JTextArea with button click

    but it's all revevant
    Make special testing drivers that set the values the user would enter to bypass that code.

    What does the code do? Open a file, read some bytes compare those bytes to a table of bytes and find a match for those bytes that gives some info about the file.
    Hard code as much of that as you can and work on one part at a time.

    Not many people will want to work with this large of a program. Isolate and reduce each part of the program to a small program that is easier to work with.

Similar Threads

  1. How to close a frame on a button click ??
    By rk0887 in forum AWT / Java Swing
    Replies: 1
    Last Post: August 22nd, 2012, 09:58 AM
  2. Searching and displaying results in a multi-dimensional array.
    By wfalcon2012 in forum Collections and Generics
    Replies: 2
    Last Post: February 18th, 2012, 08:06 PM
  3. add JTextField with a click of button
    By A4Andy in forum AWT / Java Swing
    Replies: 1
    Last Post: August 31st, 2011, 08:34 AM
  4. [SOLVED] Click button to open JDialog
    By susieferrari in forum Java Theory & Questions
    Replies: 6
    Last Post: March 30th, 2011, 10:24 AM
  5. close JDialog on button click
    By Christophe in forum AWT / Java Swing
    Replies: 4
    Last Post: April 5th, 2010, 12:04 AM

Tags for this Thread