jueves, 26 de febrero de 2009

Adjuntando Archivos (Imagenes) Ejemplo


Muchas Veces hemos querido adjuntar archivos mediante JAVA.
A continuación explico el codigo para llevarlo a cabo.

Si usted usa Netbeans este codigo se resuce por los eventos.

Codigo1: Dentro del evento del boton, hacer lo siguiente.

JFileChooser fc = new JFileChooser();

fc.addChoosableFileFilter(new ImageFilter());
fc.setFileView(new ImageFileView());
JComponent jcom = new visual.ImagePreview(fc);
fc.setAccessory(jcom);

int returnVal = fc.showDialog(this,
"Adjuntar");

if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
log.append("Attaching file: " + file.getName() + "." + newline);
} else {
log.append("Attachment cancelled by user." + newline);
}


Codigo2:

import java.io.File;
import javax.swing.filechooser.FileFilter;
public class ImageFilter extends FileFilter {

//Accept all directories and all gif, jpg, tiff, or png files.
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}

String extension = Utils.getExtension(f);
if (extension != null) {
if (extension.equals(Utils.tiff) ||
extension.equals(Utils.tif) ||
extension.equals(Utils.gif) ||
extension.equals(Utils.jpeg) ||
extension.equals(Utils.jpg) ||
extension.equals(Utils.png)) {
return true;
} else {
return false;
}
}

return false;
}

//The description of this filter
public String getDescription() {
return "Solo Images";
}
}

Codigo3:
import java.io.File;

/**
*
* @author njoaquin
*/
public class Utils {

static String tiff = "tiff";
static String tif = "tif";
static String gif = "gif";
static String jpg = "jpg";
static String png = "png";
static String jpeg = "jpeg";

static String getExtension(File f) {
String no_archiv=f.getName().trim();
int indice=no_archiv.indexOf(".");
String sub=no_archiv.substring(indice+1);

return sub;
}
}

Codigo4:
ImagePreview
Al final Quedara asi:

No hay comentarios: