Use of jfilechooser

Source: Internet
Author: User

I



Its
The basic usage of jfilechooser is still very simple. The following two examples show how to use jfilechooser. If you want to add some functions, you can add a filter to display only the filtered files.
When saving the file, if the file already exists in the directory is saved, the dialog box is not closed, and a joptionpane prompt is displayed to indicate whether to save the file.

Open file dialog box:

Import java. Io. file;
Import javax. Swing. jfilechooser;
Import javax. Swing. filechooser. filefilter;

Public class filechoosertest {

Public static void main (string [] ARGs ){

// Create a jfilechooser object with a parameter, indicating the default directory to be opened. This is the directory where the current file is opened by default.

Jfilechooser file = new jfilechooser (".");
// Remove the filter that shows all files.
File. setacceptallfilefilterused (false );
// Add an Excel file Filter
File. addchoosablefilefilter (New excelfilefilter ("xls "));
// Add the filter for the EXE file
File. addchoosablefilefilter (New excelfilefilter ("EXE "));

/* Use the showopendialog () method to display the window for opening the selected file. If a file is selected or the window is closed,

Integer value. If 0 is returned, a file has been selected. If 1 is returned, the cancel button is selected or the window is closed */
Int result = file. showopendialog (null );

/* Jfilechooser. approve_option is an integer constant, representing 0. That is to say, when the return value is 0, we will perform the relevant operation, otherwise nothing will be done.
If (result = jfilechooser. approve_option)
{

/* Obtain the absolute path of the selected file. And output. Of course, we can do a lot after getting this path.
String Path = file. getselectedfile (). getabsolutepath ();
System. Out. println (PATH );
}
Else
{

System. Out. println ("You have canceled and closed the window! ");
}
}

/* Because we need to create a file filter so that the file dialog box displays the file we specified. Here we will take the Excel file and EXE file as an example.

To do this, we need to override the accept of the filefilter class to set the related filter. You can write this inheritance class as an external class, internal class, or even

Anonymous internal class. I have written an internal class form here. Because it is used in the main method, this class should also be defined as static.

Private Static class excelfilefilter extends filefilter {

String ext;

// The parameters of the constructor are the file types we need to filter. For example, the Excel file is xls, And the EXE file is exe.

Excelfilefilter (string ext ){

This. Ext = ext;
}

/* This method is used to override the filefilter class. The parameter is a file object. We do not need to worry about how this parameter is passed in. Returns a Boolean value. If it is true, the file meets the filtering settings. The file is displayed in the current directory. If it is false, the file is filtered out.

Public Boolean accept (File file ){

// First, check whether a file in the directory is a directory. If the file is a directory, true is returned, which means the file can be displayed in the directory.

If (file. isdirectory ())
{
Return true;
}

// Obtain the file name of a file, and use lastindexof () to obtain the position of the character '.' In the string of the file name. And return
Integer to determine whether the file meets the *. * Format of the file + file name. If not, the file is not displayed. If yes, extract the string following the '.' character and filter the text.
Compare the file names. If they are equal, the file format is displayed. If they are not equal, filter them out. */

String filename = file. getname ();
Int Index = filename. lastindexof ('.');

If (index> 0 & index <FILENAME. Length ()-1)
{
String extension = filename. substring (index + 1). tolowercase ();
If (extension. Equals (EXT ))
Return true;
}
Return false;
}

/* This method is also used to override filefilter, which is used to display related information in the filter name. This matches the file type we have filtered. With this information, users can better understand what types of files need to be filtered. */

Public String getdescription (){

If (ext. Equals ("xls "))
{
Return "Microsoft Excel file (*. xls )";
}
If (ext. Equals ("EXE "))
{
Return "executable file (*. EXE )";
}
Return "";
}
}

}

The Select File Dialog Box is created. However, the above program has flaws. This is because no operation is performed only when the user clicks cancel or close the window. If the text you enter in the dialog box
When the file does not exist in the current directory, the window will still be closed. In this case, you may need to make a judgment in the program. However, when the user inputs an incorrect file name, the window will not close, but will not execute any
What operations or pop-up dialog box prompts the user, you can see that the selection dialog box in most window programs is doing this, in fact, it is not difficult to implement this function,
You only need to rewrite the approveselection () method of the jfilechooser class.

First, we need to create a class that inherits from jfilechooser by modifying the above program. This class can be written as an external or internal class. Here we still write it as an internal class. Note, if you need to call it in a static method, you need to set it to static.

Private Static class mychooser extends jfilechooser {
Mychooser (string path ){
Super (PATH );
}

/**
* Reload the jfilechooser method. When in the file selection dialog box
* If no input file is found in the directory, the dialog box is not closed. The dialog box is closed and subsequent operations are performed only when the selected file is in the selected directory.
*/
Public void approveselection (){

File file = new file (getselectedfile (). getpath ());

If (file. exists ())
Super. approveselection ();
Else
Joptionpane. showmessagedialog (null, "the file you selected does not exist. Please reselect it! ");

}

Add the above Code to the class just now, and then

Jfilechooser file = new jfilechooser ("."); changed

Jfilechooser file = new mychooser (".");

Now, we can determine whether the user input is incorrect without closing the dialog box. You can also add a regular expression to determine whether the user input meets the requirements. The operation is based on this framework, so there is no problem. I will not go into details here. The Save dialog box is displayed!

Save dialog box:

In fact, there is no difference between the Save dialog box and the open file dialog box. They all use the same class jfilechooser, because in swing, the open and save dialog box does not do
All these functions need to be implemented by ourselves. Instead, we only provide a window model like this. Therefore, these two windows only replace the button labels.
Only
. The only difference between creating them is that opening is to call the showopendialog () method, while saving is to call showsavedialog (). The creation form is almost the same. We are making
When using them, we need to perform different processing for the returned results of the two windows respectively, and set the filters to be the same. Therefore, we will reuse the above method to open the file window, however, when determining whether the input is saved
When the directory is in the current directory, we need to make different processing. After the user enters the same file name as the current directory, a dialog box is displayed asking whether the user needs to overwrite the original file. If the user chooses no
Return to the Save file dialog box to allow the user to continue selecting or entering the saved file name.

Below I only need to modify the above Code to achieve the goal. First, modify the class mychooser.

Private Static class mychooser extends jfilechooser {
Mychooser (string path ){
Super (PATH );
}

/* Overwrite the approveselection method. First, obtain the path of the input file, and then determine whether it is in the current directory. If yes, a dialog box is displayed asking whether to overwrite the current file, if you cancel the operation, return to the Save dialog box. You can continue to save the operation. */
Public void approveselection (){
File file = This. getselectedfile ();
If (file. exists ())
{
Int copy = joptionpane. showconfirmdialog (null,
"Do you want to overwrite the current file? "," Save ", joptionpane. yes_no_option,
Joptionpane. question_message );
If (copy = joptionpane. yes_option)
Super. approveselection ();
}
Else
Super. approveselection ();
}
}

Then

Int result = file. showopendialog (null );

Change

Int result = file. showsavedialog (null );

The two basic selection file dialog boxes are created.

If multiple options are required, set setmultiselectionenabled (true)

File file = This. getselectedfile (); we need to change this sentence

File [] files = This. getselectedfiles ();

The files array stores multiple file objects. Then, you only need to operate the array.

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.