Java file dialog box filters specific file types sample _java

Source: Internet
Author: User
Tags custom name

Thinking Analysis:

Because it is a form application, look at the view layer first. You need a button control JButton to select a folder; You need a Label control JLabel to display the selected path; a Label control JLabel prompts the user for something; a text box control JTextField for user input file types ; You need a Table control jtable to display files of the specified type under the selected directory.
For a button control, it binds the event-handling method, in which the JFileChooser file selector object is first created, and the filter for the selector is set for the object, that is, the Setfileselectionmode () method of the Jfilechoose class is set to select only the path. Then execute the ShowDialog () method and use the Getselectedfile () method of the JFileChooser class to get the selected path, assign it to a file variable, and use the ToString () method to display the path in the label. Finally gets the filtered array of files that match the criteria.
For text box controls, once the text inside changes, it is necessary to filter the files in the selected path, so the Addcaretlistener () method of the JTextField class is used to bind the event-handling method to get the filtered array of eligible files in the method.
Because both the button control and the text box control implement filtering and display, therefore, filtering and display can be used as a separate method in which the current path is first judged to be null, and if not NULL, the Listfiles () method of the file class is used to obtain an array of eligible files, assigned to a file-type array, Then use the Getmodel () method of the JTable class to get the data model of the table, empty the table using the Setrowcount () method of the DefaultTableModel class, and then iterate through the file array using a foreach () loop. Use the object[] array in the loop to create the table row data, call the GetName () method of the file class to get the file name, the length () method gets the size, and the LastModified () method gets the modified date. Finally, the AddRow () method of the DefaultTableModel class is used to add row data to the table model.
The code is as follows:

Copy Code code as follows:

Import Java.awt.BorderLayout;
Import Java.awt.EventQueue;
Import java.awt.GridBagConstraints;
Import Java.awt.GridBagLayout;
Import Java.awt.Insets;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
Import Java.io.File;
Import Java.sql.Date;

Import Javax.swing.JButton;
Import Javax.swing.JFileChooser;
Import Javax.swing.JFrame;
Import Javax.swing.JLabel;
Import Javax.swing.JPanel;
Import Javax.swing.JScrollPane;
Import javax.swing.JTable;
Import Javax.swing.JTextField;
Import Javax.swing.border.EmptyBorder;
Import javax.swing.event.CaretEvent;
Import Javax.swing.event.CaretListener;
Import Javax.swing.table.DefaultTableModel;

public class Listcustomtypefile extends JFrame {
/**
*
*/
Private static final long serialversionuid = -6263975104443132420l;

/**
* Custom name extension filter
*
* @author Li Zhongji
*/
Private Final class Customfilter implements Java.io.FileFilter {
@Override
Public Boolean accept (File pathname) {
Gets the specified extension of the user's settings
String extname = Extnamefield.gettext ();
if (Extname = null | | extname.isempty ())
return false;
if (!extname.startswith (".")) To determine the name extension prefix
Extname = "." + extname;//finished extension prefix
Extname = Extname.tolowercase ();
Determine if the extension and filter file name meet the requirements
if (Pathname.getname (). toLowerCase (). EndsWith (Extname))
return true;
return false;
}
}

Private JPanel ContentPane;
Private JTextField Extnamefield;
Private JTable table;
Private File dir;
Private JLabel label;

/**
* Launch the application.
*/
public static void Main (string[] args) {
Eventqueue.invokelater (New Runnable () {
public void Run () {
try {
Listcustomtypefile frame = new Listcustomtypefile ();
Frame.setvisible (TRUE);
catch (Exception e) {
E.printstacktrace ();
}
}
});
}

/**
* Create the frame.
*/
Public Listcustomtypefile () {
Settitle ("Show files of the specified type");
Setdefaultcloseoperation (Jframe.exit_on_close);
SetBounds (100, 100, 450, 300);
ContentPane = new JPanel ();
Contentpane.setborder (New Emptyborder (5, 5, 5, 5));
Contentpane.setlayout (New BorderLayout (0, 0));
Setcontentpane (ContentPane);

JPanel panel = new JPanel ();
Contentpane.add (panel, Borderlayout.north);
GridBagLayout Gbl_panel = new GridBagLayout ();
Gbl_panel.columnwidths = new int[] {93, 54, 0};
Gbl_panel.rowheights = new int[] {23, 0, 0};
Gbl_panel.columnweights = new double[] {0.0, 1.0, double.min_value};
Gbl_panel.rowweights = new double[] {0.0, 0.0, double.min_value};
Panel.setlayout (Gbl_panel);

JButton button = new JButton ("Select folder");
Button.addactionlistener (new ActionListener () {
public void actionperformed (ActionEvent e) {
Do_button_actionperformed (e);
}
});
Gridbagconstraints Gbc_button = new Gridbagconstraints ();
Gbc_button.anchor = Gridbagconstraints.north;
Gbc_button.gridx = 0;
Gbc_button.gridy = 0;
Panel.add (button, Gbc_button);

label = new JLabel ("folder");
Gridbagconstraints Gbc_label = new Gridbagconstraints ();
Gbc_label.fill = Gridbagconstraints.horizontal;
Gbc_label.gridx = 1;
Gbc_label.gridy = 0;
Panel.add (label, Gbc_label);

JLabel label_1 = new JLabel ("Enter specified file extension name:");
Gridbagconstraints gbc_label_1 = new Gridbagconstraints ();
Gbc_label_1.anchor = Gridbagconstraints.east;
Gbc_label_1.insets = new Insets (0, 0, 0, 5);
Gbc_label_1.gridx = 0;
Gbc_label_1.gridy = 1;
Panel.add (Label_1, Gbc_label_1);

Extnamefield = new JTextField ();
Extnamefield.addcaretlistener (New Caretlistener () {
public void Caretupdate (Caretevent e) {
Do_extnamefield_caretupdate (e);
}
});
Extnamefield.settext (". gif");
Gridbagconstraints Gbc_extnamefield = new Gridbagconstraints ();
Gbc_extnamefield.insets = new Insets (0, 0, 5, 0);
Gbc_extnamefield.fill = Gridbagconstraints.horizontal;
Gbc_extnamefield.gridx = 1;
Gbc_extnamefield.gridy = 1;
Panel.add (Extnamefield, Gbc_extnamefield);
Extnamefield.setcolumns (10);

JScrollPane ScrollPane = new JScrollPane ();
Contentpane.add (ScrollPane, Borderlayout.center);

Table = new JTable ();
Table.setautoresizemode (Jtable.auto_resize_off);
Table.setmodel (New DefaultTableModel (new object[][] {}, new string[] {"File name", "File Size", "Modified Date"}) {
/**
*
*/
Private static final long serialversionuid = 5274214559103654856L;
boolean[] Columneditables = new boolean[] {false, False, false};

public boolean iscelleditable (int row, int column) {
return Columneditables[column];
}
});
Table.getcolumnmodel (). GetColumn (0). Setpreferredwidth (220);
Table.getcolumnmodel (). GetColumn (1). Setpreferredwidth (85);
Table.getcolumnmodel (). GetColumn (2). Setpreferredwidth (110);
Scrollpane.setviewportview (table);
}

/**
* Select the event handling method for the folder button
*
* @param E
*/
protected void do_button_actionperformed (ActionEvent e) {
JFileChooser chooser = new JFileChooser ();//Create File Selector
Set Filter for Selector
Chooser.setfileselectionmode (jfilechooser.directories_only);
Chooser.showdialog (this, null);
dir = Chooser.getselectedfile ();
Getlabel (). SetText (Dir.tostring ());
Gets the filtered array of files that match the criteria
Listfiles ();
}

/**
* Display files in a folder
*/
private void Listfiles () {
if (dir = null)
Return
Gets an array of files that match the criteria
file[] files = dir.listfiles (new Customfilter ());
Get the data model for a table
DefaultTableModel model = (DefaultTableModel) Table.getmodel ();
Model.setrowcount (0);
for (file file:files) {//Traverse file array
CREATE TABLE row Data
object[] row = {File.getname (), File.length (),
New Date (File.lastmodified ())};
Model.addrow (row);//Add row data to the table model
}
}

protected void Do_extnamefield_caretupdate (Caretevent e) {
Listfiles ();
}

Protected JLabel Getlabel () {
return label;
}
}

Effect as shown:

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.