Java file selection dialog box (File selector JFileChooser): Take a file encryptor as an example. The selector jfilechooser

Source: Internet
Author: User

Java file selection dialog box (File selector JFileChooser): Take a file encryptor as an example. The selector jfilechooser

The file encryptor is involved in the operation process, so the file encryptor is used as an example. In the following example, I wrote a file encryptor. There is no special encryption algorithm. It is used only for the demonstration file selector JFileChooser.

Encryptor Interface

Project directory structure

The source code of each file is pasted below:

MainForm. java

Package com. lidi; import javax. swing. *; import java. awt. *; public class MainForm extends JFrame {/*** constructor interface ** @ author 1109030125 */private static final long serialVersionUID = 1L; /* several elements in the main form */private JFrame mainForm = new JFrame ("TXT file encryption"); // The main form, the title is "TXT file encryption" private JLabel label1 = new JLabel ("select the file to be encrypted or decrypted :"); private JLabel label2 = new JLabel ("select the encrypted or decrypted file storage location:"); public static JTextField Sourcefile = new JTextField (); // select the public static JTextField targetfile = new JTextField () in the text field of the file path to be encrypted or decrypted (); // select the public static JButton buttonBrowseSource = new JButton ("") in the text field of the encrypted or decrypted file path "); // open the public static JButton buttonBrowseTarget = new JButton (""); // open the public static JButton buttonEncrypt = new JButton ("encrypted "); // encryption button public static JButton buttonDecrypt = new JButton ("decrypt"); // decryption button pu Blic MainForm () {Container container = mainForm. getContentPane ();/* set the main form attribute */mainForm. setSize (400,270); // set the main form size mainForm. setdefaclocloseoperation (WindowConstants. EXIT_ON_CLOSE); // set the main form closing button style mainForm. setLocationRelativeTo (null); // set mainForm in the center of the screen. setResizable (false); // set that the window cannot be scaled to mainForm. setLayout (null); mainForm. setVisible (true); // display window/* set the layout of each element position */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 the event listener to each element */buttonBrowseSource. addActionListener (new BrowseAction (); // bind the listener to the source file browser button. Click this button to call the file selection window. Port buttonBrowseTarget. addActionListener (new BrowseAction (); // bind the listener to the browser button of the target location. Click this button to call the file selection window buttonEncrypt. addActionListener (new EncryptAction (); // bind the listener to the encryption button. Click the encryption button to encrypt the source file and output it to the target location buttonDecrypt. addActionListener (new DecryptAction (); // bind the listener to the decryption button, and click the decryption button to decrypt the source file and output it to the target sourcefile. getDocument (). addDocumentListener (new TextFieldAction (); // bind events to the source file region. If the file is of the .txt type, disable the decryption button. kcd file, disable the encryption button. Sourcefile. setEditable (false); // you cannot manually modify the targetfile in the source file text field. setEditable (false); // you cannot manually modify the container in the text field of the target location. add (label1); 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 actionreceivmed (ActionEvent e) {if (e. getSource (). equals (MainForm. buttonBrowseSource) {JFileChooser fcDlg = new JFileChooser (); fcDlg. setDialogTitle ("select the file to be encrypted or decrypted... "); 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 ("select the directory for storing encrypted or decrypted files"); fcDlg. setFileSelectionMode (JFileChooser. DIRECTORIES_ONLY); int returnVal = fcDlg. showOpenDialog (null); if (returnVal = JFileChooser. APPROVE_OPTION) {String filepath = fcDlg. getSelectedFile (). getPath (); MainForm.tar getfile. setText (filepath );}}}}View code

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 actionreceivmed (ActionEvent e) {// TODO Auto-generated method stub if (MainForm. sourcefile. getText (). isEm Pty () {JOptionPane. showMessageDialog (null, "select the file to be encrypted! ");} Else if (MainForm.tar getfile. getText (). isEmpty () {JOptionPane. showMessageDialog (null," select the directory for storing encrypted files! ");} Else {String sourcepath = MainForm. sourcefile. getText (); String targetpath = MainForm.tar getfile. 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, "the target file failed to be created. Check whether the directory is 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 successful! ");} Catch (Exception e1) {JOptionPane. showMessageDialog (null," Unknown error! ") ;}} Else if (! File. exists () {JOptionPane. showMessageDialog (null, "the file to be encrypted does not exist! ");} Else {JOptionPane. showMessageDialog (null," the 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 ;}}View code

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 actionreceivmed (ActionEvent e) {// TODO Auto-generated method stub if (MainForm. sourcefile. getText (). isEm Pty () {JOptionPane. showMessageDialog (null, "select the file to be decrypted! ");} Else if (MainForm.tar getfile. getText (). isEmpty () {JOptionPane. showMessageDialog (null," select the directory where the files are stored after decryption! ");} Else {String sourcepath = MainForm. sourcefile. getText (); String targetpath = MainForm.tar getfile. 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, "the target file failed to be created. Check whether the directory is 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," the 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 ;}}View code

TextFieldAction. java

Package com. lidi; import javax. swing. event. documentEvent; import javax. swing. event. documentListener; public class TextFieldAction implements DocumentListener {@ Override public void insertUpdate (effece) {// TODO Auto-generated method stub ButtonAjust () ;}@ Override public void removeUpdate (effecentevent) {// TODO Auto-generated method stub ButtonAjust () ;}@ Override public void changedUpdate (deleentevent 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 );}}}View code

 

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.