public class Model implements TreeModel{
private Vector listeners = new Vector();
// Diese Methode wird vom JTree und vielleicht auch von anderen Objekten aufgerufen
public void addTreeModelListener( TreeModelListener l ){
listeners.add( l );
}
[...]
// Diese Methode muss vom Programm aufgerufen werden, sobald ein Knoten entfernt wurde.
public void removeNode( Object parent, Object node ){
TreePath path = pathOf( parent ); // Der Pfad zum Vater des Knotens
TreeModelEvent e = new TreeModelEvent( path, [...] ); // Das Event herstellen, verschiedene Argumente müssen noch benutzt werden, siehe API
// Und jetzt den JTree benachrichtigen
for( int i = 0, n = listeners.size(); i<n; i++ )
((TreeModelListener) listeners.get(i) ).treeNodesRemoved( e );
}
}
import javax.swing.*;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.EventListenerList;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.*;
import java.util.HashMap;
import java.io.File;
import java.io.Serializable;
import javax.swing.tree.*;
public class FileTreeModel implements TreeModel, Serializable, Cloneable {
protected EventListenerList listeners;
private Map map;
private File root;
public FileTreeModel(File root) {
if (!root.exists())
throw new IllegalArgumentException(String.valueOf(root));
this.root = root;
this.listeners = new EventListenerList();
this.map = new HashMap();
}
public Object getRoot() {
return root;
}
public boolean isLeaf(Object node) {
return !((File) node).isDirectory();
}
public int getChildCount(Object node) {
List children = children(node);
if (children == null)
return 0;
return children.size();
}
public Object getChild(Object parent, int index) {
return children(parent).get(index);
}
public int getIndexOfChild(Object parent, Object child) {
return children(parent).indexOf(child);
}
public void valueForPathChanged(TreePath path, Object value) {
}
protected List children(Object node) {
File f = (File) node;
if (!f.isDirectory())
return null;
List children = (List) map.get(f);
if (children == null) {
File[] c = f.listFiles();
if (c == null)
return null;
children = new ArrayList(c.length);
for (int len = c.length, i = 0; i < len; i++)
children.add(c[i]);
map.put(f, children);
}
return children;
}
public Object clone() {
try {
FileTreeModel clone = (FileTreeModel) super.clone();
clone.listeners = new EventListenerList();
return clone;
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
//HAB ICH SCHON!!
public void addTreeModelListener(TreeModelListener l) {
listeners.add(TreeModelListener.class, l);
}
public void removeTreeModelListener(TreeModelListener l) {
listeners.remove(TreeModelListener.class, l);
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java FileTreeModel path");
System.exit(1);
}
File root = new File(args[0]);
if (!root.exists()) {
System.err.println(root + ": No such file or directory");
System.exit(2);
}
JTree t = new JTree(new FileTreeModel(root));
//t.setCellRenderer(new Renderer());
JFrame f = new JFrame(root.toString());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(t));
f.pack();
f.setVisible(true);
}
}
Math55 hat gesagt.:hi, danker erstmal. muss das unbedingt ein vector sein? in meinem programm gibt es die methode
import javax.swing.*;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.EventListenerList;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.*;
import java.util.HashMap;
import java.io.File;
import java.io.Serializable;
import javax.swing.tree.*;
public class FileTreeModel implements TreeModel, Serializable, Cloneable {
protected EventListenerList listeners;
private Map map;
private File root;
public FileTreeModel(File root) {
if (!root.exists())
throw new IllegalArgumentException(String.valueOf(root));
this.root = root;
this.listeners = new EventListenerList();
this.map = new HashMap();
}
public Object getRoot() {
return root;
}
public boolean isLeaf(Object node) {
return !((File) node).isDirectory();
}
public int getChildCount(Object node) {
List children = children(node);
if (children == null)
return 0;
return children.size();
}
public Object getChild(Object parent, int index) {
return children(parent).get(index);
}
public int getIndexOfChild(Object parent, Object child) {
return children(parent).indexOf(child);
}
public void valueForPathChanged(TreePath path, Object value) {
}
// einfach hier rein.
// Diese Methode muss vom Programm aufgerufen werden, sobald ein Knoten entfernt wurde.
public void removeNode( Object parent, Object node ){
TreePath path = pathOf( parent ); // Der Pfad zum Vater des Knotens. Der muss noch berechnet werden, und darf dummerweise nur Objekte beinhalten, welche auch benutzt wurden.
TreeModelEvent e = new TreeModelEvent( path, [...] ); // Das Event herstellen, verschiedene Argumente müssen noch benutzt werden, siehe API
// Und jetzt den JTree benachrichtigen
for( int i = 0, n = listeners.size(); i<n; i++ )
((TreeModelListener) listeners.get(i) ).treeNodesRemoved( e );
}
protected List children(Object node) {
File f = (File) node;
if (!f.isDirectory())
return null;
List children = (List) map.get(f);
if (children == null) {
File[] c = f.listFiles();
if (c == null)
return null;
children = new ArrayList(c.length);
for (int len = c.length, i = 0; i < len; i++)
children.add(c[i]);
map.put(f, children);
}
return children;
}
public Object clone() {
try {
FileTreeModel clone = (FileTreeModel) super.clone();
clone.listeners = new EventListenerList();
return clone;
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
//HAB ICH SCHON!!
public void addTreeModelListener(TreeModelListener l) {
listeners.add(TreeModelListener.class, l);
}
public void removeTreeModelListener(TreeModelListener l) {
listeners.remove(TreeModelListener.class, l);
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java FileTreeModel path");
System.exit(1);
}
File root = new File(args[0]);
if (!root.exists()) {
System.err.println(root + ": No such file or directory");
System.exit(2);
}
JTree t = new JTree(new FileTreeModel(root));
//t.setCellRenderer(new Renderer());
JFrame f = new JFrame(root.toString());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(t));
f.pack();
f.setVisible(true);
}
}
public void delete( File file ){
File parent = file.getParentFile(); // oder so ähnlich
file.delete();
FileTreeModel model = ... // Das FileTreeModel, welches die Dateien anzeigt
model.removeNode( parent, file );
}
import javax.swing.*;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.EventListenerList;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.*;
import java.util.HashMap;
import java.io.File;
import java.io.Serializable;
import javax.swing.tree.*;
import javax.swing.event.*;
public class FileTreeModel implements TreeModel, Serializable, Cloneable {
protected EventListenerList listeners;
private Map map;
private File root;
static ArrayList myPathList = new ArrayList();
public FileTreeModel(File root) {
if (!root.exists())
throw new IllegalArgumentException(String.valueOf(root));
this.root = root;
this.listeners = new EventListenerList();
this.map = new HashMap();
}
public Object getRoot() {
return root;
}
public boolean isLeaf(Object node) {
return !((File) node).isDirectory();
}
public int getChildCount(Object node) {
List children = children(node);
if (children == null)
return 0;
return children.size();
}
public Object getChild(Object parent, int index) {
return children(parent).get(index);
}
public int getIndexOfChild(Object parent, Object child) {
return children(parent).indexOf(child);
}
public void valueForPathChanged(TreePath path, Object value) {
}
protected List children(Object node) {
File f = (File) node;
if (!f.isDirectory())
return null;
List children = (List) map.get(f);
if (children == null) {
File[] c = f.listFiles();
if (c == null)
return null;
children = new ArrayList(c.length);
for (int len = c.length, i = 0; i < len; i++)
children.add(c[i]);
map.put(f, children);
}
return children;
}
public Object clone() {
try {
FileTreeModel clone = (FileTreeModel) super.clone();
clone.listeners = new EventListenerList();
return clone;
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
//HAB ICH SCHON!!
public void addTreeModelListener(TreeModelListener l) {
listeners.add(TreeModelListener.class, l);
}
public void removeTreeModelListener(TreeModelListener l) {
listeners.remove(TreeModelListener.class, l);
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java FileTreeModel path");
System.exit(1);
}
File root = new File(args[0]);
if (!root.exists()) {
System.err.println(root + ": No such file or directory");
System.exit(2);
}
JTree t = new JTree(new FileTreeModel(root));
t.addTreeExpansionListener(new TreeExpansionListener() {
public void treeCollapsed(TreeExpansionEvent e) {
myPathList.remove(e.getPath());
}
public void treeExpanded(TreeExpansionEvent e) {
myPathList.add(e.getPath());
}
});
//t.setCellRenderer(new Renderer());
JFrame f = new JFrame(root.toString());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(t));
f.pack();
f.setVisible(true);
try{
Thread.sleep(5000);
}catch(Exception te){
}
System.out.println("Calling...");
t.setModel(new FileTreeModel(root));
TreePath tpa = null;
for(int li=0;li<myPathList.size();li++){
String test=myPathList.get(li).toString();
test=test.replaceAll("^\\[", "");
test=test.replaceAll("\\]$", "");
tpa= new TreePath(test);
System.out.println("expanding: " + tpa);
t.expandPath(tpa);
//System.out.println("test: " + tpa);
}
/*for (Iterator it=myPathList.iterator(); it.hasNext(); ) {
String test=it.next().toString();
test=test.replaceAll("^\\[", "");
test=test.replaceAll("\\]$", "");
tpa= new TreePath(test);
t.expandPath(tpa);
System.out.println("test: " + tpa);
}
*/
}
}
import javax.swing.*;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.EventListenerList;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.*;
import java.util.HashMap;
import java.io.File;
import java.io.Serializable;
import javax.swing.tree.*;
import javax.swing.event.*;
public class FileTreeModel implements TreeModel, Serializable, Cloneable {
protected EventListenerList listeners;
private Map map;
private File root;
static TreePath tpa = null;
static ArrayList myPathList = new ArrayList();
static boolean open=false;
public FileTreeModel(File root) {
if (!root.exists())
throw new IllegalArgumentException(String.valueOf(root));
this.root = root;
this.listeners = new EventListenerList();
this.map = new HashMap();
}
public Object getRoot() {
return root;
}
public boolean isLeaf(Object node) {
File f = new File(node.toString());
String[] ft = node.toString().split(",");
if(open){
for(int i =0;i< ft.length; i++){
System.out.println("test: " + ft[ft.length-1] + " node: " + node);
f=new File(ft[i]);
}
}
//return !((File)node).isDirectory();
return !f.isDirectory();
}
public int getChildCount(Object node) {
List children = children(node);
if (children == null)
return 0;
return children.size();
}
public Object getChild(Object parent, int index) {
return children(parent).get(index);
}
public int getIndexOfChild(Object parent, Object child) {
return children(parent).indexOf(child);
}
public void valueForPathChanged(TreePath path, Object value) {
}
protected List children(Object node) {
File f = (File) node;
if (!f.isDirectory())
return null;
List children = (List) map.get(f);
if (children == null) {
File[] c = f.listFiles();
if (c == null)
return null;
children = new ArrayList(c.length);
for (int len = c.length, i = 0; i < len; i++)
children.add(c[i]);
map.put(f, children);
}
return children;
}
public Object clone() {
try {
FileTreeModel clone = (FileTreeModel) super.clone();
clone.listeners = new EventListenerList();
return clone;
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
//HAB ICH SCHON!!
public void addTreeModelListener(TreeModelListener l) {
listeners.add(TreeModelListener.class, l);
}
public void removeTreeModelListener(TreeModelListener l) {
listeners.remove(TreeModelListener.class, l);
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java FileTreeModel path");
System.exit(1);
}
File root = new File(args[0]);
if (!root.exists()) {
System.err.println(root + ": No such file or directory");
System.exit(2);
}
final JTree t = new JTree(new FileTreeModel(root));
t.addTreeExpansionListener(new TreeExpansionListener() {
public void treeCollapsed(TreeExpansionEvent e) {
myPathList.remove(e.getPath());
}
public void treeExpanded(TreeExpansionEvent e) {
myPathList.add(e.getPath());
}
});
t.setCellRenderer(new Renderer());
JFrame f = new JFrame(root.toString());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(t));
f.pack();
f.setVisible(true);
try{
Thread.sleep(5000);
}catch(Exception te){
}
System.out.println("\n\nCalling...\n\n");
t.setModel(new FileTreeModel(root));
open=true;
for(int li=0;li<myPathList.size();li++){
String test=myPathList.get(li).toString();
test=test.replaceAll("^\\[", "");
test=test.replaceAll("\\]$", "");
tpa= new TreePath(test);
System.out.println("expanding: " + tpa);
t.expandPath(tpa);
}
}
}
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
public class FileTreeModel implements TreeModel{
private Vector vector = new Vector();
private Capsel root;
public static void main( String[] args ){
File root = new File( "d:/temp" );
final FileTreeModel model = new FileTreeModel( root );
JFrame frame = new JFrame();
final JTree tree = new JTree( model );
frame.getContentPane().add( new JScrollPane( tree ));
tree.addKeyListener( new KeyAdapter(){
public void keyPressed( KeyEvent e ) {
if( e.getKeyCode() == KeyEvent.VK_DELETE ){
File file = model.fileOf( tree.getSelectionPath().getLastPathComponent() );
if( file != null ){
model.deleteFile( file );
}
}
}
});
frame.pack();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setVisible( true );
}
public FileTreeModel( File root ){
Capsel temp = new Capsel();
temp.file = root;
this.root = temp;
}
/**
* Speichert einen zusätzlichen TreeModelListener
* @param l Der neue TreeModelListener
*/
public void addTreeModelListener(TreeModelListener l) {
vector.add( l );
}
public void removeTreeModelListener( TreeModelListener l ) {
vector.remove( l );
}
public boolean isLeaf( Object node ) {
return ((Capsel)node).file.isFile();
}
public Object getChild( Object parent, int index ) {
Capsel temp = (Capsel)parent;
temp.ensureChilds();
return temp.childs[ index ];
}
public int getChildCount( Object parent ) {
Capsel temp = (Capsel)parent;
temp.ensureChilds();
return temp.childs.length;
}
public int getIndexOfChild( Object parent, Object child ) {
Capsel temp = (Capsel)parent;
temp.ensureChilds();
Capsel[] childs = temp.childs;
for( int i = 0; i < childs.length; i++ )
if( childs[i] == child )
return i;
return -1;
}
public int getIndexOfChild( Capsel parent, File file ) {
parent.ensureChilds();
Capsel[] childs = parent.childs;
for( int i = 0; i < childs.length; i++ )
if( childs[i].file.equals( file ))
return i;
return -1;
}
public Object getRoot() {
return root;
}
public void valueForPathChanged( TreePath path, Object newValue ) {
}
public File fileOf( Object node ){
return ((Capsel)node).file;
}
/**
* Diese Methode löscht eine Datei und benachrichtigt anschliessend den JTree,
* das eine Datei gelöscht wurde.
* @param file Die Datei die gelöscht werden soll.
*/
public void deleteFile( File file ){
/*
* Es wäre einfacher, wenn man hier direkt die Capsel übergeben könnte.
* Aber es muss ja eigentlich niemand wissen, wie diese Model intern
* aufgebaut ist...
*/
TreePath treePath = createPath( file.getParentFile() );
// Den Treepath umwandeln
Capsel[] path = new Capsel[ treePath.getPathCount() ];
path[ 0 ] = root;
for( int i = 1; i < path.length; i++ ){
int index = getIndexOfChild( path[i-1], (File)treePath.getPathComponent( i ) );
path[i] = path[i-1].childs[ index ];
}
// Jetzt die Datei löschen
boolean deleted = file.delete();
if( deleted ){
// Aus der Capsel löschen
Capsel parent = path[ path.length-1 ];
int index = getIndexOfChild( parent, file );
Capsel[] temp = new Capsel[ parent.childs.length-1 ];
if( index > 0 )
System.arraycopy( parent.childs, 0, temp, 0, index );
if( index < temp.length )
System.arraycopy( parent.childs, index+1, temp, index, temp.length-index );
parent.childs = temp;
// jetzt den JTree benachrichtigen
fireNodeRemoved( new TreePath( path ), index, file );
}
}
/**
* Diese Methode liefert den TreePath zu dem angegebenen File.
* @param file Das File
* @return Der TreePath
*/
protected TreePath createPath( File file ){
Vector files = new Vector(); // Zwischenspeicher
// Die Parents der Reihe nach auslesen
if( file.equals( root.file ))
files.add( file );
else{
do{
files.add( file );
file = file.getParentFile();
}while( file != null && !root.file.equals( file ) );
files.add( root.file );
}
// Verkehrt herum in einen Array kopieren
int size = files.size();
Object[] path = new Object[ size ];
for( int i = 0; i < size; i++ )
path[i] = files.get( size - 1 - i );
// TreePath initialisieren und zurückgeben.
return new TreePath( path );
}
/**
* Benachrichtigt alle registrierten TreeModelListener, dass ein Node
* entfernt wurde.
* @param path Der Pfad zum Parent des entfernten Nodes
* @param index Der ehemalige Index des Nodes
* @param removed Der entfernte Node
*/
protected void fireNodeRemoved( TreePath path, int index, Object removed ){
// Event herstellen
TreeModelEvent event = new TreeModelEvent( this, path, new int[]{ index }, new Object[]{ removed } );
// Event verschicken
for( int i = 0, n = vector.size(); i<n; i++ )
((TreeModelListener)vector.get(i)).treeNodesRemoved( event );
}
private class Capsel{
public Capsel parent;
public File file;
public Capsel[] childs;
public void ensureChilds(){
if( childs == null ){
File[] files = file.listFiles();
childs = new Capsel[ files.length ];
for( int i = 0; i < files.length; i++ ){
Capsel temp = new Capsel();
temp.file = files[i];
temp.parent = this;
childs[i] = temp;
}
}
}
public String toString(){
return file.getName();
}
}
}