Two methods for selecting files in java

Source: Internet
Author: User

Two methods for selecting files in java

Type 1 JFileChooser


JLabel lblNewLabel_1 = new JLabel ("");

JFileChooser jf = new JFileChooser ();
Jf. setDialogTitle ("select Avatar ");
Jf. setFileFilter (new FileFilter (){

@ Override
Public String getDescription (){
// TODO Auto-generated method stub
Return null;
}

@ Override
Public boolean accept (File dir ){
String name = dir. getName ();
If (dir. isDirectory () | name. endsWith ("jpg") | name. endsWith ("gif") | name. endsWith ("png "))
Return true;
Else
Return false;
}
});
Int result = jf. showOpenDialog (Stuinfo. this );
Jf. setVisible (true );
File selectedFile = null; // The selected File
If (result = JFileChooser. APPROVE_OPTION)
{
SelectedFile = jf. getSelectedFile ();
// File exists
If (selectedFile. exists ())
{

String fliepath = selectedFile. getPath ();
ImageIcon iic = new ImageIcon (fliepath );
Iic. setImage (iic. getImage (). getScaledInstance (lblNewLabel_1.getWidth (), lblNewLabel_1.getHeight (), Image. SCALE_DEFAULT ));
LblNewLabel_1.setIcon (iic );


}
}





Type 2 FileDialog


FileDialog fd = new FileDialog (Stuinfo. this, "select Avatar", FileDialog. LOAD );
// Filter files
FilenameFilter filter = new FilenameFilter (){
Public boolean accept (File dir, String name ){
If (name. endsWith ("jpg") | name. endsWith ("gif") | name. endsWith ("png ")){
Return true;
}
Return false;
}
};
Fd. setFilenameFilter (filter );



Fd. setVisible (true );
String f = fd. getFile ();

String dir = fd. getDirectory ();
If (f! = Null ){

ImageIcon iic = new ImageIcon (dir + fd. getFile ());
Iic. setImage (iic. getImage (). getScaledInstance (lblNewLabel_1.getWidth (), lblNewLabel_1.getHeight (), Image. SCALE_DEFAULT ));
LblNewLabel_1.setIcon (iic );
}

Related Article

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.