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 );
}