Dúvidas com o JFileChooser

2 respostas
valquiriamatter

Olá galera!
Seguinte, quero colocar fotos num cadastro de clientes. Já dei uma pesquisada, e consigui criar o objeto, e chama-lo num botão…
O código tá assim :

JFileChooser fileChooser = new JFileChooser();  
   
        fileChooser.setDialogTitle("Selecione a imagem desejada ");  
        fileChooser.setApproveButtonText("Selecionar"); 
       
        //fileChooser.  
        
        fileChooser.setVisible(true);  
        fileChooser.setSize(100,80); 
        int returnVal = fileChooser.showOpenDialog(null);

Eu vou salvar as fotos no banco de dados, mas com o banco tá tudo certo.

A minha dúvida está em como filtrar as imagens, e como exibir a imagem selecionada ?
Posso exibir a imagem selecionada em um jpanel ???

Desde já agradeço…

2 Respostas

Ironlynx
Valquiria, é só fazer um ImageFilter para filtrar as suas imagens. Eu lembro de já ter posto um exemplo desses por aqui... dá uma pesquisada. Do site da Sun:
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 "Apenas Imagens";
    }
}
import java.io.File;
import javax.swing.ImageIcon;

/* Utils.java is a 1.4 example used by ImageChooser.java. */
public class Utils {
    public final static String jpeg = "jpeg";
    public final static String jpg = "jpg";
    public final static String gif = "gif";
    public final static String tiff = "tiff";
    public final static String tif = "tif";
    public final static String png = "png";

    /*
     * Pega a extensão do Arquivo.
     */
    public static String getExtension(File f) {
        String ext = null;
        String s = f.getName();
        int i = s.lastIndexOf('.');

        if (i > 0 &&  i < s.length() - 1) {
            ext = s.substring(i+1).toLowerCase();
        }
        return ext;
    }

    /** Returna um ImageIcon, ou null se o caminho é inválido */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = Utils.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("O arquivo não pode ser encontrado: " + path);
            return null;
        }
    }
}
E um ImagePreview:
import javax.swing.*;
import java.beans.*;
import java.awt.*;
import java.io.File;

/* ImagePreview.java é um 1.4 exemplo usado pelo FileChooser**/
public class ImagePreview extends JComponent
                          implements PropertyChangeListener {
    ImageIcon thumbnail = null;
    File file = null;

    public ImagePreview(JFileChooser fc) {
        setPreferredSize(new Dimension(100, 50));
        fc.addPropertyChangeListener(this);
    }

    public void loadImage() {
        if (file == null) {
            thumbnail = null;
            return;
        }

        //Don't use createImageIcon (which is a wrapper for getResource)
        //because the image we're trying to load is probably not one
        //of this program's own resources.
        ImageIcon tmpIcon = new ImageIcon(file.getPath());
        if (tmpIcon != null) {
            if (tmpIcon.getIconWidth() > 90) {
                thumbnail = new ImageIcon(tmpIcon.getImage().
                                          getScaledInstance(90, -1,
                                                      Image.SCALE_DEFAULT));
            } else { //sem necessidade de miniaturizar
                thumbnail = tmpIcon;
            }
        }
    }

    public void propertyChange(PropertyChangeEvent e) {
        boolean update = false;
        String prop = e.getPropertyName();

        //Se o diretório muda,não mostra a imagem.
        if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) {
            file = null;
            update = true;

        //Se um arquivo é seleciodado, find out which one.
        } else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
            file = (File) e.getNewValue();
            update = true;
        }

        //Atualiza o preview correspondente.
        if (update) {
            thumbnail = null;
            if (isShowing()) {
                loadImage();
                repaint();
            }
        }
    }

    protected void paintComponent(Graphics g) {
        if (thumbnail == null) {
            loadImage();
        }
        if (thumbnail != null) {
            int x = getWidth()/2 - thumbnail.getIconWidth()/2;
            int y = getHeight()/2 - thumbnail.getIconHeight()/2;

            if (y < 0) {
                y = 0;
            }

            if (x < 5) {
                x = 5;
            }
            thumbnail.paintIcon(this, g, x, y);
        }
    }//fim do método paintComponent()
 }
Esse mecanismo de miniatura usado no ImagePreview srve para pôr por exemplo num JLabel, e esse num JPanel.
valquiriamatter

Valew pela ajuda…

Só mais uma dúvida…
To com fazendo meu projeto no netbeans…
Ai nesse caso, eu faço 3 classe, para intereragir com a minha janela ???

E isso ???

Desde já agradeço…

Criado 3 de março de 2008
Ultima resposta 3 de mar. de 2008
Respostas 2
Participantes 2