Filter im JFileChooser.

Status
Nicht offen für weitere Antworten.

Vince

Mitglied
Hallo liebe Gemeinde,

ich hab mal eine Frage. Ich stehe vor einem Rätsel. Ich möchte in meine Gui, die bereits ein JFileChooser hat, einen Filter einbauen. Dieser soll mir beim Laden einer Datei, die Möglichkeit geben, nach nur bestimmten Dateiendungen auszuwählen. Sowas kennt man ja, ist ja wie, wenn man in Office eine Datei öffnen will, da kann man ja auch einen Filter anwenden, genau so einen suche ich. Kann mir jmd sagen, wie das funktioniert? Wenn schon ein Thread zu meinem Problem besteht, dann bitte nicht verklppen, ich weiß nur nicht, mit welchem Schlagwort ich suchen soll. Wär cool, wenn einer Rat weiß.

Habe übrigens Java 1.5
 

8ull23y3

Bekanntes Mitglied
Also ich habs letze Tage mal probier weil ich auch nie hin bekommen hab aber nu scheints das zu machen was ich will ;)
Hier mal ein bisschen Code und wehe einer beschwert sich darüber ;)

Code:
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

public class FileChooser extends JFileChooser
{
   public FileChooser()
   {
      setFileFilter(new FileNameFilter());
      showOpenDialog(this);
   }
   public class FileNameFilter extends FileFilter
   {
      public boolean accept(File arg0)
      {
         if(arg0.isDirectory()) return true;
         if(arg0.getName().endsWith("txt")) return true;
         return false;
      }
      public String getDescription()
      {
         return "Nur TextDateien";
      }
      
   }
   public static void main(String[] args)
   {
      new FileChooser();
   }

}
 

keisersoze

Mitglied
Hab das mal irgendwo im Internet aufgeschnappt:

Code:
/*
 * Copyright (c) 2003 Sun Microsystems, Inc. All  Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * -Redistributions of source code must retain the above copyright
 *  notice, this list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduct the above copyright
 *  notice, this list of conditions and the following disclaimer in
 *  the documentation and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
 * BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
 * OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
 * IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that Software is not designed, licensed or intended for
 * use in the design, construction, operation or maintenance of any nuclear
 * facility.
 */

/*
 * @(#)ExampleFileFilter.java        1.14 03/01/23
 */

package Vok;

import java.io.File;
import java.util.Hashtable;
import java.util.Enumeration;
import javax.swing.filechooser.*;

/**
 * A convenience implementation of FileFilter that filters out
 * all files except for those type extensions that it knows about.
 *
 * Extensions are of the type ".foo", which is typically found on
 * Windows and Unix boxes, but not on Macinthosh. Case is ignored.
 *
 * Example - create a new filter that filerts out all files
 * but gif and jpg image files:
 *
 *     JFileChooser chooser = new JFileChooser();
 *     ExampleFileFilter filter = new ExampleFileFilter(
 *                   new String{"gif", "jpg"}, "JPEG & GIF Images")
 *     chooser.addChoosableFileFilter(filter);
 *     chooser.showOpenDialog(this);
 *
 * @version 1.14 01/23/03
 * @author Jeff Dinkins
 */
public class ExampleFileFilter extends FileFilter {

	private static String TYPE_UNKNOWN = "Type Unknown";
	private static String HIDDEN_FILE = "Hidden File";

	private Hashtable filters = null;
	private String description = null;
	private String fullDescription = null;
	private boolean useExtensionsInDescription = true;

	/**
	 * Creates a file filter. If no filters are added, then all
	 * files are accepted.
	 *
	 * @see #addExtension
	 */
	public ExampleFileFilter() {
		this.filters = new Hashtable();
	}

	/**
	 * Creates a file filter that accepts files with the given extension.
	 * Example: new ExampleFileFilter("jpg");
	 *
	 * @see #addExtension
	 */
	public ExampleFileFilter(String extension) {
		this(extension,null);
	}

	/**
	 * Creates a file filter that accepts the given file type.
	 * Example: new ExampleFileFilter("jpg", "JPEG Image Images");
	 *
	 * Note that the "." before the extension is not needed. If
	 * provided, it will be ignored.
	 *
	 * @see #addExtension
	 */
	public ExampleFileFilter(String extension, String description) {
		this();
		if(extension!=null) addExtension(extension);
		 if(description!=null) setDescription(description);
	}

	/**
	 * Creates a file filter from the given string array.
	 * Example: new ExampleFileFilter(String {"gif", "jpg"});
	 *
	 * Note that the "." before the extension is not needed adn
	 * will be ignored.
	 *
	 * @see #addExtension
	 */
	public ExampleFileFilter(String[] filters) {
		this(filters, null);
	}

	/**
	 * Creates a file filter from the given string array and description.
	 * Example: new ExampleFileFilter(String {"gif", "jpg"}, "Gif and JPG Images");
	 *
	 * Note that the "." before the extension is not needed and will be ignored.
	 *
	 * @see #addExtension
	 */
	public ExampleFileFilter(String[] filters, String description) {
		this();
		for (int i = 0; i < filters.length; i++) {
			// add filters one by one
			addExtension(filters[i]);
		}
		 if(description!=null) setDescription(description);
	}

	/**
	 * Return true if this file should be shown in the directory pane,
	 * false if it shouldn't.
	 *
	 * Files that begin with "." are ignored.
	 *
	 * @see #getExtension
	 * @see FileFilter#accepts
	 */
	public boolean accept(File f) {
		if(f != null) {
			if(f.isDirectory()) {
				return true;
			}
			String extension = getExtension(f);
			if(extension != null && filters.get(getExtension(f)) != null) {
				return true;
			};
		}
		return false;
	}

	/**
	 * Return the extension portion of the file's name .
	 *
	 * @see #getExtension
	 * @see FileFilter#accept
	 */
	 public String getExtension(File f) {
		if(f != null) {
			String filename = f.getName();
			int i = filename.lastIndexOf('.');
			if(i>0 && i<filename.length()-1) {
				return filename.substring(i+1).toLowerCase();
			};
		}
		return null;
	}

	/**
	 * Adds a filetype "dot" extension to filter against.
	 *
	 * For example: the following code will create a filter that filters
	 * out all files except those that end in ".jpg" and ".tif":
	 *
	 *   ExampleFileFilter filter = new ExampleFileFilter();
	 *   filter.addExtension("jpg");
	 *   filter.addExtension("tif");
	 *
	 * Note that the "." before the extension is not needed and will be ignored.
	 */
	public void addExtension(String extension) {
		if(filters == null) {
			filters = new Hashtable(5);
		}
		filters.put(extension.toLowerCase(), this);
		fullDescription = null;
	}


	/**
	 * Returns the human readable description of this filter. For
	 * example: "JPEG and GIF Image Files (*.jpg, *.gif)"
	 *
	 * @see setDescription
	 * @see setExtensionListInDescription
	 * @see isExtensionListInDescription
	 * @see FileFilter#getDescription
	 */
	public String getDescription() {
		if(fullDescription == null) {
			if(description == null || isExtensionListInDescription()) {
				 fullDescription = description==null ? "(" : description + " (";
				// build the description from the extension list
				Enumeration extensions = filters.keys();
				if(extensions != null) {
					fullDescription += "." + (String) extensions.nextElement();
					while (extensions.hasMoreElements()) {
						fullDescription += ", ." + (String) extensions.nextElement();
					}
				}
				fullDescription += ")";
			} else {
				fullDescription = description;
			}
		}
		return fullDescription;
	}

	/**
	 * Sets the human readable description of this filter. For
	 * example: filter.setDescription("Gif and JPG Images");
	 *
	 * @see setDescription
	 * @see setExtensionListInDescription
	 * @see isExtensionListInDescription
	 */
	public void setDescription(String description) {
		this.description = description;
		fullDescription = null;
	}

	/**
	 * Determines whether the extension list (.jpg, .gif, etc) should
	 * show up in the human readable description.
	 *
	 * Only relevent if a description was provided in the constructor
	 * or using setDescription();
	 *
	 * @see getDescription
	 * @see setDescription
	 * @see isExtensionListInDescription
	 */
	public void setExtensionListInDescription(boolean b) {
		useExtensionsInDescription = b;
		fullDescription = null;
	}

	/**
	 * Returns whether the extension list (.jpg, .gif, etc) should
	 * show up in the human readable description.
	 *
	 * Only relevent if a description was provided in the constructor
	 * or using setDescription();
	 *
	 * @see getDescription
	 * @see setDescription
	 * @see setExtensionListInDescription
	 */
	public boolean isExtensionListInDescription() {
		return useExtensionsInDescription;
	}
}

so sieht dann die Verwendung der Klasse aus:
Code:
ExampleFileFilter fileFilter = new ExampleFileFilter("abc", "Dateiendung");
jFileChooser.addChoosableFileFilter(fileFilter);
 
Status
Nicht offen für weitere Antworten.
Ähnliche Java Themen
  Titel Forum Antworten Datum
jueki Aktuell eingestellten Filter aus einem JFileChooser abfragen. AWT, Swing, JavaFX & SWT 5
G Jfilechooser filter AWT, Swing, JavaFX & SWT 10
G Probleme mit JFileChooser und Filter AWT, Swing, JavaFX & SWT 11
A Swing Filter-Problem AWT, Swing, JavaFX & SWT 1
D Filter in Tabelle Sql AWT, Swing, JavaFX & SWT 6
D JavaFX Table Filter AWT, Swing, JavaFX & SWT 4
J ComboBox als Filter benutzen AWT, Swing, JavaFX & SWT 1
M Filter in die JFace/SWT Tabelle einbauen AWT, Swing, JavaFX & SWT 5
J Kombinieren von Filter-Optionen für JTable AWT, Swing, JavaFX & SWT 4
C Eclipse Filter-Muster AWT, Swing, JavaFX & SWT 2
B Swing Filter für JTable mit Netbeans Editor AWT, Swing, JavaFX & SWT 2
S Swing Tabelle mit Model bei eingeschaltetem Filter synchronisieren AWT, Swing, JavaFX & SWT 6
D Filter für JTable AWT, Swing, JavaFX & SWT 5
M JTable Filter AWT, Swing, JavaFX & SWT 3
C Swing Dynamische JComboBox (Filter) AWT, Swing, JavaFX & SWT 28
S JTable Filter nach Wort oder Wortteil über ganze Tabelle AWT, Swing, JavaFX & SWT 5
M ISelection an Filter übergeben AWT, Swing, JavaFX & SWT 2
L SWT Filter zur TreeViewer hinzufügen AWT, Swing, JavaFX & SWT 9
K JTable wird nicht aktualisiert, wenn Filter gesetzt ist AWT, Swing, JavaFX & SWT 9
E Swing JTree Filter Suche mit Collapse?! AWT, Swing, JavaFX & SWT 4
C JTable Dropdown Filter AWT, Swing, JavaFX & SWT 5
B AWT FileDialog Filter wird ignoriert AWT, Swing, JavaFX & SWT 7
D JTree Filter erstellen AWT, Swing, JavaFX & SWT 4
H FileChooser und Filter AWT, Swing, JavaFX & SWT 4
G dynamischer Filter bei JTable AWT, Swing, JavaFX & SWT 2
D HSB - Filter AWT, Swing, JavaFX & SWT 3
Tommy135 JFileChooser ist sehr langsam AWT, Swing, JavaFX & SWT 13
T JFileChooser ist Englisch und bleibt Englisch und bleibt Englisch... AWT, Swing, JavaFX & SWT 15
M Swing jFileChooser Header viewTypeDetails setFont AWT, Swing, JavaFX & SWT 0
I JFileChooser mit System L&F bei anderem L&F der eigtl. Anwendung AWT, Swing, JavaFX & SWT 0
Meeresgott AWT JFileChooser bestimmte Ordner anzeigen AWT, Swing, JavaFX & SWT 16
S Swing JFileChooser best. Ordner wie Dateien behandeln AWT, Swing, JavaFX & SWT 4
H Swing JFileChooser für nicht existierendes Unterverzeichnis AWT, Swing, JavaFX & SWT 3
javampir Swing Anzeige der FileFilter im JFileChooser AWT, Swing, JavaFX & SWT 0
L JFileChooser Datentyp Unterscheidung AWT, Swing, JavaFX & SWT 6
K JFileChooser NullPointerException AWT, Swing, JavaFX & SWT 7
H JFileChooser Dateinamen vorgeben (Save Dialog) AWT, Swing, JavaFX & SWT 9
Neumi5694 Swing JFilechooser - Detailansicht AWT, Swing, JavaFX & SWT 0
M JFileChooser Look and Feel AWT, Swing, JavaFX & SWT 2
T JFileChooser Rahmenfarbe ändern AWT, Swing, JavaFX & SWT 1
K Pfad mit JFileChooser ausgeben lassen AWT, Swing, JavaFX & SWT 7
C JFileChooser hängt bei Ausführung mit Terminal AWT, Swing, JavaFX & SWT 2
T Swing JFileChooser und FileView AWT, Swing, JavaFX & SWT 4
M Einzelne Ordner im JFileChooser ausgrauen? AWT, Swing, JavaFX & SWT 4
H Swing JFileChooser inline editing AWT, Swing, JavaFX & SWT 4
D JFileChooser anpassen AWT, Swing, JavaFX & SWT 5
AssELAss Verzeichnis JFileChooser aktualisieren AWT, Swing, JavaFX & SWT 0
A JFileChooser Datei speichern AWT, Swing, JavaFX & SWT 4
A Datei weiterverwenden mit JFileChooser AWT, Swing, JavaFX & SWT 6
T Importer-Auswahl im JFileChooser AWT, Swing, JavaFX & SWT 3
N JFileChooser bzw. FileDialog Problem AWT, Swing, JavaFX & SWT 10
A Swing JFileChooser - Größenänderung nach Aufruf von showOpenDialog() AWT, Swing, JavaFX & SWT 15
D Serverdirectory auf Client browsen mit JFileChooser AWT, Swing, JavaFX & SWT 7
F icon aus exe auslesen mithilfe des JFilechooser ? AWT, Swing, JavaFX & SWT 4
C JFileChooser und Netzwerk Laufwerke AWT, Swing, JavaFX & SWT 4
Iron Monkey JFileChooser - Drag and Drop AWT, Swing, JavaFX & SWT 5
J JFileChooser - Datei speichern AWT, Swing, JavaFX & SWT 7
M Element aus JList eines JFileChooser entfernen AWT, Swing, JavaFX & SWT 3
P JFileChooser mit verschidene Endungen AWT, Swing, JavaFX & SWT 12
S Swing Ordner im JFileChooser auswählen AWT, Swing, JavaFX & SWT 2
C JFileChooser bringt parent durcheinander AWT, Swing, JavaFX & SWT 2
N JFileChooser mit Dateinamenvorgabe AWT, Swing, JavaFX & SWT 9
S JFileChooser GTK (Ubuntu) "hässlich" AWT, Swing, JavaFX & SWT 2
A Swing JFileChooser mit modifiziertem Kontextmenü AWT, Swing, JavaFX & SWT 4
S JFileChooser öffnet den falschen Ordner AWT, Swing, JavaFX & SWT 4
A Swing JFilechooser zeigt verzeichnisse nicht an AWT, Swing, JavaFX & SWT 2
A Swing JFileChooser - Anzeige in Echtzeit filtern AWT, Swing, JavaFX & SWT 10
M JFileChooser umbenennen verbieten AWT, Swing, JavaFX & SWT 4
Helgon JFileChooser öffnet sich 2x AWT, Swing, JavaFX & SWT 12
K JFileChooser mit Zusatzfunktionen AWT, Swing, JavaFX & SWT 8
GUI-Programmer JFilechooser, mehrere Datein selektieren und Reihenfolge (2) AWT, Swing, JavaFX & SWT 8
V JFileChooser auf Mac und Netzwerkordner AWT, Swing, JavaFX & SWT 2
B JFileChooser breite der Spalten? AWT, Swing, JavaFX & SWT 5
M JFileChooser setCurrentDirectory() - Verzeichnis relativ zum Code/binary AWT, Swing, JavaFX & SWT 14
P Swing Dateinamen im JFileChooser vorschlagen AWT, Swing, JavaFX & SWT 11
M JFileChooser Abfangen des DateiTypen möglich?? AWT, Swing, JavaFX & SWT 5
T Swing JFileChooser --> Desktop und Laufwerke im "Suchen in" - Drop Down AWT, Swing, JavaFX & SWT 3
N JFileChooser - Keine Funtkion AWT, Swing, JavaFX & SWT 13
T JFileChooser - "Öffnen-Button" aktivieren/deaktivieren möglich??? AWT, Swing, JavaFX & SWT 2
F Swing JFileChooser - Dateinamen nicht editierbar machen AWT, Swing, JavaFX & SWT 8
I Fehler bei JFileChooser AWT, Swing, JavaFX & SWT 2
K JFileChooser mehrere Dateien markieren ohne STRG AWT, Swing, JavaFX & SWT 4
Ivan Dolvich [Linux] JFileChooser sieht komisch aus... AWT, Swing, JavaFX & SWT 12
M Zurück-Button in JFileChooser AWT, Swing, JavaFX & SWT 9
N JFileChooser AWT, Swing, JavaFX & SWT 4
D Problem mit JFileChooser -> Daten werden mit anführungsstriche in JTable geschrieben AWT, Swing, JavaFX & SWT 8
S JFileChooser Dateiname Autovervollständigung AWT, Swing, JavaFX & SWT 2
B JDialog über JFileChooser anzeigen AWT, Swing, JavaFX & SWT 6
I Swing JFileChooser '\' im Pfad... AWT, Swing, JavaFX & SWT 2
K Swing JFileChooser zum Speichern - FileFilter AWT, Swing, JavaFX & SWT 2
M Swing Execption beim JFileChooser AWT, Swing, JavaFX & SWT 4
kodela Swing JFileChooser und die Datei-Extension AWT, Swing, JavaFX & SWT 3
jueki eigenen Button in JFileChooser einfügen AWT, Swing, JavaFX & SWT 7
alderwaran jFileChooser showSaveDialog, dateinamen werden mit pfadnamen überschrieben beim navigieren AWT, Swing, JavaFX & SWT 1
B Swing Suche JFileChooser zum Speichern AWT, Swing, JavaFX & SWT 2
Iron Monkey JFileChooser DIRECTORIES_ONLY AWT, Swing, JavaFX & SWT 4
Semox Swing JFileChooser: Problem Approve oder Cancel abzufangen AWT, Swing, JavaFX & SWT 7
H JTree - nach Auswahl aus JFileChooser wird nur der erste Knoten angezeigt AWT, Swing, JavaFX & SWT 3
kodela Sicherheitsabfrage mit JFileChooser AWT, Swing, JavaFX & SWT 2
DARK_ZERATO2 jFileChooser AWT, Swing, JavaFX & SWT 4

Ähnliche Java Themen


Oben