View Full Version : JTree Java
Salve, sono riuscito a popolare un JTree con delle cartelle e dei file di un percorso del mio disco, ma non riesco a farmi restituire il file selezionato x poi aprirlo con il suo programma predefinito, qualcuno può aiutarmi a capire come fare? grazie mille.
Per capire se l'utente vuole aprire il file associato al nodo oppure no, puoi usare un ascoltatore per l'evento "è cambiata la selezione corrente dell'albero" oppure un ascoltatore per l'evento doppio-click del mouse.
Di solito si usa il secondo. In questo caso dirai:
tree.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if(SwingUtilities.isLeftMouseButton(e) && e.getClickCount() >= 2) {
TreePath path = getPathForLocation(e.x, e.y);
DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
File file = (File) node.getUserObject();
}
}
});
Qui si suppone che il JTree sia "standard" e che i nodi contengano dei file. I valori "path" "node" e "file" possono tutti essere null quindi devi aggiungere degli if ma il succo è quello.
ma getPathForLocation cosa è un metodo o una classe? perchè netBeans non melo riconosce.
Pardon, è un metodo di jtree:
tree.getPathForLocation(...)
Mi lancia questa eccezzione: "FileTreeNode cannot be cast to javax.swing.tree.DefaultMutableTreeNode"
e dentro a getPathForLocation(e.getX, e.getY);
invece di getPathForLocation(e.x, e.y);
:muro:
DefaultMutableTreeNode è l'elemento standard di un JTree. Se usi un tipo diverso di nodo allora fai la conversione esplicita al tipo che sai di stare usando:
FileTreeNode node = (FileTreeNode) path.getLastPathComponent()
Ho provato con DefaultTreeCellRenderer e mi da lo stesso errore, mentre con
FileTreeNode non riesco a recuperare il file, nel senso che non so dopo cosa mettergli per apreire il file.
TreeCellRenderer serve per "disegnare" i nodi che è un'altra cosa.
Questo FileTreeNode da dove arriva? Ce l'avrà una classe. Guarda e vedi se ha un metodo getFile o qualcosa del genere.
scusami, ma proprio non ci riesco, ti posto il codice e facciamo prima:
public class Albero {
protected static FileSystemView fsv = FileSystemView.getFileSystemView();
private static class FileTreeCellRenderer extends DefaultTreeCellRenderer {
private Map<String, Icon> iconCache = new HashMap<String, Icon>();
private Map<File, String> rootNameCache = new HashMap<File, String>();
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
FileTreeNode ftn = (FileTreeNode) value;
File file = ftn.file;
String filename = "";
if (file != null) {
if (ftn.isFileSystemRoot) {
filename = this.rootNameCache.get(file);
if (filename == null) {
filename = fsv.getSystemDisplayName(file);
this.rootNameCache.put(file, filename);
}
} else {
filename = file.getName();
if (file.isFile()) {
setFileDaAprire(file);
}
}
}
JLabel result = (JLabel) super.getTreeCellRendererComponent(tree, filename, sel, expanded, leaf, row, hasFocus);
if (file != null) {
Icon icon = this.iconCache.get(filename);
if (icon == null) {
icon = fsv.getSystemIcon(file);
this.iconCache.put(filename, icon);
}
result.setIcon(icon);
}
return result;
}
}
private static class FileTreeNode implements TreeNode {
private File file;
private File[] children;
private TreeNode parent;
private boolean isFileSystemRoot;
public FileTreeNode(File file, boolean isFileSystemRoot, TreeNode parent) {
this.file = file;
this.isFileSystemRoot = isFileSystemRoot;
this.parent = parent;
this.children = this.file.listFiles();
if (this.children == null) {
this.children = new File[0];
}
}
public FileTreeNode(File[] children) {
this.file = null;
this.parent = null;
this.children = children;
}
@Override
public Enumeration<?> children() {
final int elementCount = this.children.length;
return new Enumeration<File>() {
int count = 0;
@Override
public boolean hasMoreElements() {
return this.count < elementCount;
}
@Override
public File nextElement() {
if (this.count < elementCount) {
return FileTreeNode.this.children[this.count++];
}
throw new NoSuchElementException("Vector Enumeration");
}
};
}
@Override
public boolean getAllowsChildren() {
return true;
}
@Override
public TreeNode getChildAt(int childIndex) {
return new FileTreeNode(this.children[childIndex], this.parent == null, this);
}
@Override
public int getChildCount() {
return this.children.length;
}
@Override
public int getIndex(TreeNode node) {
FileTreeNode ftn = (FileTreeNode) node;
for (int i = 0; i < this.children.length; i++) {
if (ftn.file.equals(this.children[i])) {
return i;
}
}
return -1;
}
@Override
public TreeNode getParent() {
return this.parent;
}
@Override
public boolean isLeaf() {
return (this.getChildCount() == 0);
}
}
}
Aggiungi a FileTreeNode un metodo:
public File getFile() { return file; }
e sei a posto.
E poi? come e dove lo richiamo getFile()?
Nel mouse listener:
tree.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if(SwingUtilities.isLeftMouseButton(e) && e.getClickCount() >= 2) {
TreePath path = getPathForLocation(e.x, e.y);
FileTreeNode node = (FileTreeNode ) path.getLastPathComponent();
File file = node.getFile();
...fai quel che vuoi con file
}
}
});
Siii!!! grazie infinite ci sono riuscito.
vBulletin® v3.6.4, Copyright ©2000-2026, Jelsoft Enterprises Ltd.