Der FileChooser inklusive Preview und Dateifilter
//BildFilter:
public class BildFilter extends javax.swing.filechooser.FileFilter implements FileFilter{
@Override
public boolean accept(File f) {
// TODO Auto-generated method stub
return (f.getName().endsWith(".bmp") || f.getName().endsWith(".png") || f.isDirectory());
}
public String getDescription(){
return ".png, .bmp";
}
}
//FileChooser:
if(e.getActionCommand().equals("durchsuchen")){
gestartet=false;
JFileChooser chooser=new JFileChooser();
chooser.setFileFilter(new BildFilter());
Bildervorschau vorschau=new Bildervorschau(chooser);
chooser.setAccessory(vorschau);
chooser.addPropertyChangeListener(vorschau);
chooser.setCurrentDirectory(new File("/..."));
int antwort=chooser.showOpenDialog(null);
if(antwort!=JFileChooser.APPROVE_OPTION)
return;
//Preview:
public class Bildervorschau extends JPanel implements PropertyChangeListener{
private JFileChooser f;
private Image img;
public Bildervorschau(JFileChooser f){
img=null;
this.f=f;
setPreferredSize(new Dimension(192,144));
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
// TODO Auto-generated method stub
img=null;
try{
img=ImageIO.read(f.getSelectedFile());
}catch(Exception e){}
repaint();
}
@Override
public void paintComponent(Graphics g){
g.setColor(Color.WHITE);
g.fillRect(0, 0, 192, 144);
g.setColor(Color.RED);
if(img!=null)
g.drawImage(img, 0, 0, 192, 144, null);
else
g.drawString("Keine Vorschau\n verfügbar", 20, 20);
}
}