Java File Selection dialog box JFileChooser use the detailed _java

Source: Internet
Author: User

File encryption device, the operation process must involve the use of file selector, so here to file encryption as an example. The following example for my own write a file cipher, there is no special encryption algorithm, only for the demo file selector jfilechooser use.

The cryptographic interface is shown as follows:

Project directory structure as shown:

The source code of each file is posted below:

Mainform.java

Package Com.lidi;
Import javax.swing.*;
Import java.awt.*; public class MainForm extends JFrame {/** * Construction interface * * @author 1109030125/private static final long ser
  Ialversionuid = 1L; /* Main form inside a number of elements * * Private JFrame MainForm = new JFrame ("TXT file encryption");
  Main form, titled "TXT file Encryption" Private JLabel Label1 = new JLabel ("Please select files to be encrypted or decrypted:");
  Private JLabel Label2 = new JLabel ("Please select the location where the file is encrypted or decrypted:"); public static JTextField sourcefile = new JTextField (); Select the text field to encrypt or decrypt the file path public static JTextField targetfile = new JTextField (); Select the text field that encrypts or decrypts the file path public static JButton Buttonbrowsesource = new JButton ("Browse"); Browse button public static JButton Buttonbrowsetarget = new JButton ("Browse"); Browse button public static JButton Buttonencrypt = new JButton ("Encryption"); Encryption button public static JButton Buttondecrypt = new JButton ("decryption");
    Decryption button public MainForm () {Container Container = Mainform.getcontentpane (); /* Set main form Properties/Mainform.setsize (400, 270);//Set main form size MAINFORM.SETDEFAULTCLOseoperation (Windowconstants.exit_on_close),//Set the main form Close button style mainform.setlocationrelativeto (null);/set to reside in the center of the screen Mainfo
    Rm.setresizable (false);/Set Window not scalable mainform.setlayout (null);
    Mainform.setvisible (TRUE);//Display window/* Set each element position layout * * Label1.setbounds (30, 10, 300, 30);
    Sourcefile.setbounds (50, 50, 200, 30);
    Buttonbrowsesource.setbounds (270, 50, 60, 30);
    Label2.setbounds (30, 90, 300, 30);
    Targetfile.setbounds (50, 130, 200, 30);
    Buttonbrowsetarget.setbounds (270, 130, 60, 30);
    Buttonencrypt.setbounds (100, 180, 60, 30);
    Buttondecrypt.setbounds (200, 180, 60, 30); /* Bind event listeners to each element/Buttonbrowsesource.addactionlistener (new Browseaction ()); To bind the listener to the source file browse button, click the button to invoke the File Selection window Buttonbrowsetarget.addactionlistener (new Browseaction ()); For the target Location browse button binding listener, click the button to invoke the File Selection window Buttonencrypt.addactionlistener (new Encryptaction ()); Bind the listener for the Encryption button, and clicking the encryption button encrypts the source file and outputs it to the target location Buttondecrypt.addactionlistener (new Decryptaction ()); To bind the listener to the Decryption button, clicking the decryption button decrypts the source file andOutput to target location sourcefile.getdocument (). Adddocumentlistener (New Textfieldaction ());//To bind events for source file text field.
    If the file is a. txt type, disable the decryption button, or disable the encryption button if it is a. kcd file. Sourcefile.seteditable (false);/Set the source file text field cannot be manually modified targetfile.seteditable (FALSE);/Set Target location text field cannot be manually modified Container.add (Lab
    EL1);
    Container.add (Label2);
    Container.add (sourcefile);
    Container.add (targetfile);
    Container.add (Buttonbrowsesource);
    Container.add (Buttonbrowsetarget);
    Container.add (Buttonencrypt);
  Container.add (Buttondecrypt);
  public static void Main (String args[]) {new MainForm ();

 }
}

Browseaction.java

Package Com.lidi;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
Import Javax.swing.JFileChooser;
Import Javax.swing.filechooser.FileNameExtensionFilter; public class Browseaction implements ActionListener {@Override public void actionperformed (ActionEvent e) {if (e)
      . GetSource (). Equals (Mainform.buttonbrowsesource)) {JFileChooser Fcdlg = new JFileChooser ();
      Fcdlg.setdialogtitle ("Please select the file to encrypt or decrypt ...");
      Filenameextensionfilter filter = new Filenameextensionfilter ("Text file (*.TXT;*.KCD)", "TXT", "KCD");
      Fcdlg.setfilefilter (filter);
      int returnval = Fcdlg.showopendialog (null);
        if (ReturnVal = = jfilechooser.approve_option) {String filepath = Fcdlg.getselectedfile (). GetPath ();
      MainForm.sourcefile.setText (filepath);
      } else if (E.getsource (). Equals (Mainform.buttonbrowsetarget)) {JFileChooser Fcdlg = new JFileChooser ();
      Fcdlg.setdialogtitle ("Please select the file storage directory after encryption or decryption"); Fcdlg.setfileSelectionMode (jfilechooser.directories_only);
      int returnval = Fcdlg.showopendialog (null);
        if (ReturnVal = = jfilechooser.approve_option) {String filepath = Fcdlg.getselectedfile (). GetPath ();
      MainForm.targetfile.setText (filepath);

 }
    }
  }
}

Encryptaction.java

Package Com.lidi;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
Import Java.io.File;
Import Java.io.FileReader;
Import Java.io.FileWriter;
Import java.io.IOException;
Import Javax.swing.JOptionPane; public class Encryptaction implements ActionListener {@Override public void actionperformed (ActionEvent e) {//T Odo auto-generated Method Stub if (MainForm.sourcefile.getText (). IsEmpty ()) {Joptionpane.showmessagedialog (null , select the file you want to encrypt!
    "); else if (MainForm.targetfile.getText (). IsEmpty ()) {Joptionpane.showmessagedialog (null), select the encrypted file storage directory!
    ");
      else {String SourcePath = MainForm.sourcefile.getText ();
      String TargetPath = MainForm.targetfile.getText ();
      File File = new file (SourcePath);
      String filename = File.getname ();
      File dir = new file (TargetPath);
        if (file.exists () && dir.isdirectory ()) {file result = new file (getfinalfile (TargetPath, filename)); if (!resuLt.exists ()) {try {result.createnewfile (); catch (IOException E1) {Joptionpane.showmessagedialog (null, "Target file creation failed, check the directory for Read Only!")
          ");
          } try {FileReader fr = new FileReader (file);
          FileWriter FW = new FileWriter (result);
          int ch = 0;
            while (ch = fr.read ())!=-1) {//System.out.print (Encrypt (ch));
          Fw.write (Encrypt (ch));
          } fw.close ();
          Fr.close (); Joptionpane.showmessagedialog (NULL, "Encryption succeeded!")
        "); catch (Exception E1) {Joptionpane.showmessagedialog (NULL, unknown error!)
        "); } else if (!file.exists ()) {Joptionpane.showmessagedialog (null, "The file you want to encrypt does not exist!")
      "); else {Joptionpane.showmessagedialog (null, "Encrypted file storage directory does not exist!")
      ");
    }} public char Encrypt (int ch) {int x = ch + 1;
  Return (char) (x); public string Getfinalfile (string TargetpAth, String filename) {int length = Filename.length ();
    String finalfilename = filename.substring (0, length-4);
    String finalfile = TargetPath + "\" + Finalfilename + ". KCD";
  return finalfile;

 }
}

Decryptaction.java

Package Com.lidi;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
Import Java.io.File;
Import Java.io.FileReader;
Import Java.io.FileWriter;
Import java.io.IOException;
Import Javax.swing.JOptionPane; public class Decryptaction implements ActionListener {@Override public void actionperformed (ActionEvent e) {//T Odo auto-generated Method Stub if (MainForm.sourcefile.getText (). IsEmpty ()) {Joptionpane.showmessagedialog (null , "Please select the file you want to decrypt!"
    "); else if (MainForm.targetfile.getText (). IsEmpty ()) {Joptionpane.showmessagedialog (null, "Please select the decrypted file storage directory!")
    ");
      else {String SourcePath = MainForm.sourcefile.getText ();
      String TargetPath = MainForm.targetfile.getText ();
      File File = new file (SourcePath);
      String filename = File.getname ();
      File dir = new file (TargetPath);
        if (file.exists () && dir.isdirectory ()) {file result = new file (getfinalfile (TargetPath, filename)); if (!resuLt.exists ()) {try {result.createnewfile (); catch (IOException E1) {Joptionpane.showmessagedialog (null, "Target file creation failed, check the directory for Read Only!")
          ");
          } try {FileReader fr = new FileReader (file);
          FileWriter FW = new FileWriter (result);
          int ch = 0;
            while (ch = fr.read ())!=-1) {//System.out.print (Encrypt (ch));
          Fw.write (Decrypt (ch));
          } fw.close ();
          Fr.close (); Joptionpane.showmessagedialog (NULL, "decryption successful!)
        "); catch (Exception E1) {Joptionpane.showmessagedialog (NULL, unknown error!)
        "); } else if (!file.exists ()) {Joptionpane.showmessagedialog (null, "The file to be decrypted does not exist!")
      "); else {Joptionpane.showmessagedialog (null, "decrypted file storage directory does not exist!")
      ");
    }} public char Decrypt (int ch) {/Double x = 0-math.pow (ch, 2);
    int x = ch-1;
  Return (char) (x); } PUBlic string Getfinalfile (String targetpath, string filename) {int length = Filename.length ();
    String finalfilename = filename.substring (0, length-4);
    String finalfile = TargetPath + "\" + finalfilename + ". txt";
  return finalfile;

 }
}

Textfieldaction.java

Package Com.lidi;
Import javax.swing.event.DocumentEvent;
Import Javax.swing.event.DocumentListener;
public class Textfieldaction implements Documentlistener {
  @Override public
  void Insertupdate (Documentevent e) {
    //TODO auto-generated method Stub
    buttonajust ();
  }
  @Override public
  void Removeupdate (Documentevent e) {
    //TODO auto-generated method Stub
    buttonajust ();
  }
  @Override public
  void Changedupdate (Documentevent e) {
    //TODO auto-generated method Stub
    buttonajust () ;
  }
  public void Buttonajust () {
    String file = MainForm.sourcefile.getText ();
    if (File.endswith ("TXT")) {
      MainForm.buttonDecrypt.setEnabled (false);
      MainForm.buttonEncrypt.setEnabled (true);
    if (File.endswith ("KCD")) {
      MainForm.buttonEncrypt.setEnabled (false);
      MainForm.buttonDecrypt.setEnabled (True);}}


The above is the entire contents of this article, I hope you can enjoy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.