[java] appeler une methode

Résolu
b_khallou Messages postés 322 Date d'inscription   Statut Membre Dernière intervention   -  
 danimo -
Bonjour,
j'ai une class Diaporama où j'écris   le chemin du répertoire  qui contient les images que je vais  les visualiser en mode diaporama, dans le main() :

 public static void main(String[] args) {
    	Diaporama diap = new Diaporama(new File("F:\\Khaled\\images"));
        new Thread(diap).start();
    }

or je ne veut pas le faire entrer manuellement , j'ai une class FileTree qui possède une methode " getSelectedFiles() "


/**
	 * getSelectedFiles returns a File[] of the files represented by the
	 * selected treepaths
	 */
	public File[] getSelectedFiles() {
		TreePath[] selectedPaths = tree.getSelectionPaths();
		File[] fileBuffer = new File[selectedPaths.length];
		for (int i = 0; i < selectedPaths.length; i++)
			fileBuffer[i] = fileFromPath(selectedPaths[i]);
		return fileBuffer;
	}


et une autre methode " getCurrentFile() " 

	/** getCurrentFile returns the value of the currently selected file. */
	public File getCurrentFile() {
		return currentFile;
	}
alors je modifie le main du diaporama :
 Diaporama diap = new Diaporama(new File(getCurrentFile()));
pour que qd je clic sur un répertoire l'adresse de ce dernier soit comme un argument (parametre) pour Diaporama
mais elle m'affiche une erreur   " cannot find symbol method getCurrentFile() "
(les deux classe ds le meme package)
est ce qu'il y a une solution ?
et merci. 
Configuration: Windows XP
Firefox 2.0.0.14

4 réponses

  1. b_khallou Messages postés 322 Date d'inscription   Statut Membre Dernière intervention   34
     
    aucune idéé????
    0
    1. tarek_dotzero Messages postés 834 Statut Membre 122
       
      Salut,

      "getCorruntFile() "appartient à quelle classe, je ne pense pas qu'elle est dans la classe qui contient le main, alors il vous faut creer un objet de la classe qui la contient puis faire: monObjet.getCorruntFile().
      0
  2. b_khallou Messages postés 322 Date d'inscription   Statut Membre Dernière intervention   34
     
    elle appartient à la classe TreeFolder , je t'ai compris je vais l'essayer ,
    et merci pour votre reponse
    0
  3. b_khallou Messages postés 322 Date d'inscription   Statut Membre Dernière intervention   34
     
    l'erreur est la meme voila la classe TreeFolder :

    /**
    *
    */
    package imagesBrowser;

    /*
    * Copyright Jim Burton 2004
    *
    * This file is part of JMaid.
    *
    * JMaid is free software; you can redistribute it and/or modify it under the
    * terms of the GNU General Public License as published by the Free Software
    * Foundation; either version 2 of the License, or (at your option) any later
    * version.
    *
    * JMaid is distributed in the hope that it will be useful, but WITHOUT ANY
    * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
    * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
    *
    * You should have received a copy of the GNU General Public License along with
    * JMaid; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
    * Suite 330, Boston, MA 02111-1307 USA
    *
    * http://forum.java.sun.com/thread.jspa?threadID=497385&messageID=2347123
    */

    import java.io.File;
    import java.io.FilenameFilter;
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.Arrays;

    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.event.TreeExpansionEvent;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.event.TreeWillExpandListener;
    import javax.swing.text.Position;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.ExpandVetoException;
    import javax.swing.tree.MutableTreeNode;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeSelectionModel;

    /**
    * FileTree1 class displays the whole directory structure in the RHS of a
    * JSplitPane.
    *
    * @author jim burton
    */
    public class FileTree extends JScrollPane implements TreeWillExpandListener,
    TreeSelectionListener {

    private static final long serialVersionUID = 7970045957138128200L;
    private MutableTreeNode root;
    private JTree tree;
    private File currentFile;
    private boolean newFile = true;
    private static String PLACEHOLDER = "@@_jb_special_placeholder_@@";
    private ImagesBrowser imagesBrowser;

    /** Creates a new instance of FileTree */
    public FileTree(ImagesBrowser imagesBrowser) {
    this.imagesBrowser = imagesBrowser;
    getFiles();
    this.add(tree);
    this.setViewportView(tree);
    }

    /**
    * getFiles builds the tree from scratch. When the tree is first loaded it
    * contains the root directories or drives and the first level below that.
    * Directories below that are given a special placeholder which is
    * recognised by the TreeWillExpand event which then loads the contents of
    * that dir using addDirToModel. This is to avoid the overhead of loading
    * the whole tree.
    */
    public void getFiles() {
    root = new DefaultMutableTreeNode("fmTopLevel");
    File[] roots = File.listRoots();
    for (int i = 0; i < roots.length; i++) {
    File f = roots[i];
    String name = f.toString();
    if (name.equals("/"))
    name = "root";
    MutableTreeNode node = new DefaultMutableTreeNode(name);
    root.insert(node, root.getChildCount());
    // Windows problem: skip floppy drive on startup as an empty drive
    // gives annoying message...
    if (!name.equals("A:\\"))
    addDirToModel(f, node);
    }
    TreeModel model = new DefaultTreeModel(root);
    tree = new JTree(model);
    tree.getSelectionModel().setSelectionMode(
    TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    tree.setRootVisible(false);
    tree.setEditable(true);
    tree.setExpandsSelectedPaths(true);
    tree.setScrollsOnExpand(true);
    tree.setShowsRootHandles(true);
    tree.addTreeSelectionListener(this);
    tree.addTreeWillExpandListener(this);
    tree.setDragEnabled(true);
    // open to home directory
    setTree(new File(System.getProperty("user.home")), newFile);

    }

    /**
    * setTree is called to select a new node in the tree.
    *
    * @param f
    * the new selected File object
    * @param newFile
    * whether or not to also send this file to the DetailPane
    */
    public void setTree(File f, boolean newFile) {

    this.newFile = newFile;
    currentFile = f;
    TreePath p = pathFromFile(f);
    TreePath thePath;
    int lastIndex = 0;

    for (int i = 1; i < p.getPathCount(); i++) {
    thePath = tree.getNextMatch(p.getPathComponent(i).toString(),
    lastIndex, Position.Bias.Forward);
    tree.expandPath(thePath);
    lastIndex = tree.getRowForPath(thePath);
    }

    if (newFile)
    tree.setSelectionPath(p);
    tree.scrollPathToVisible(p);
    }

    /**
    * fileFromPath takes a TreePath object and creates a corresponding File
    * object.
    *
    * @param f
    * the File object
    */
    public static File fileFromPath(TreePath p) {
    StringBuffer filePath = new StringBuffer();
    for (int i = 1; i < p.getPathCount(); i++) {
    String component = (p.getPathComponent(i).toString().equals("root")) ? "//"
    : p.getPathComponent(i).toString();
    filePath.append(component + File.separator);
    }
    return new File(filePath.toString());
    }

    /**
    * pathFromFile takes a file object and creates a TreePath object which
    * relates to the tree in the filetree component.
    *
    * @param f
    * the File object
    */
    public static TreePath pathFromFile(File f) {
    String str = f.toString();
    Object[] nodes;
    if (str.equals("/")) {
    nodes = new Object[2];
    nodes[0] = new DefaultMutableTreeNode("fmTopLevel");
    nodes[1] = new DefaultMutableTreeNode("root");
    return new TreePath(nodes);
    } else {
    java.util.List<Serializable> nodeList = new ArrayList<Serializable>();
    nodeList.add(new DefaultMutableTreeNode("fmTopLevel"));
    String safeSeparator = (File.separator.equals("\\")) ? "\\\\"
    : File.separator;
    String[] temp = f.toString().split(safeSeparator);
    for (int i = 0; i < temp.length; i++) {
    String t = temp[i];
    if (t.endsWith(":")
    && System.getProperty("os.name").indexOf("Windows") > -1)
    t += "\\";
    nodeList.add(new DefaultMutableTreeNode(t));
    }
    if (File.separator.equals("/"))
    nodeList.set(1, "root");
    nodes = nodeList.toArray();
    return new TreePath(nodes);
    }
    }

    /**
    * selects a new node in the tree.
    *
    * @param p
    * the new selected TreePath object
    */
    public void setTree(TreePath p, boolean newFile) {
    setTree(fileFromPath(p), newFile);
    }

    /**
    * attempts to rebuild the tree from scratch to it's current position, to
    * reflect changes in the file system
    *
    *
    */
    public void refreshTree() {
    TreePath[] allPaths = tree.getSelectionPaths();
    for (int i = 0; i < allPaths.length; i++)
    setTree(allPaths[i], false);
    }

    /**
    * addDirToModel takes a directory filepath and adds it's nested directories
    * to the tree model, if they aren't already there.
    *
    * @param f
    * the directory to add
    * @param n
    * the node at which to add new nodes
    */
    private void addDirToModel(File f, MutableTreeNode n) {
    File[] contents = f.listFiles(new DirsOnlyFilter(true));
    if (contents != null)
    Arrays.sort(contents);
    File t = null;
    try {
    for (int i = 0; i < contents.length; i++) {
    t = contents[i];
    String name = t.getName();
    MutableTreeNode node = new DefaultMutableTreeNode(name);
    n.insert(node, n.getChildCount());
    // if this file contains files only they will never be shown in
    // the filetree view
    // so only show it as a node if it contains dirs
    if (containsDirs(t))
    node.insert(new DefaultMutableTreeNode(PLACEHOLDER), 0);
    }
    } catch (Exception e) {
    System.out.println(
    this.getClass().getName()
    +"."+Thread.currentThread().getStackTrace()[1].getMethodName()
    +" exception: '"
    + (t != null ? t : f) + "' inaccessible");
    }
    }

    /**
    * containsDir returns true if the given file contains a directory - used to
    * determine whether to add a dummy child to it on the tree
    */
    private boolean containsDirs(File f) {
    if (!f.canRead())
    return false;
    return (f.listFiles(new DirsOnlyFilter(true)).length > 0);
    }

    /**
    * getSelectedFiles returns a File[] of the files represented by the
    * selected treepaths
    */
    public File[] getSelectedFiles() {
    TreePath[] selectedPaths = tree.getSelectionPaths();
    File[] fileBuffer = new File[selectedPaths.length];
    for (int i = 0; i < selectedPaths.length; i++)
    fileBuffer[i] = fileFromPath(selectedPaths[i]);
    return fileBuffer;
    }

    /** getCurrentFile returns the value of the currently selected file. */
    public File getCurrentFile() {
    return currentFile;
    }

    /**
    * setSelectionPath sets the selectionpath of the tree component.
    *
    * @param p
    * the new selection path
    */
    public void setSelectionPath(TreePath p) {
    System.out.println("opening " + p);
    tree.setSelectionPath(p);
    }

    //////////////////////////////////////////
    // Event handlers
    //////////////////////////////////////////

    /** treeWillCollapse not used */
    public void treeWillCollapse(TreeExpansionEvent event)
    throws ExpandVetoException {
    }

    /**
    * treeWillExpand calls addDirToModel to build this part of the tree.
    */
    public void treeWillExpand(TreeExpansionEvent event)
    throws ExpandVetoException {
    TreePath path = event.getPath();
    MutableTreeNode node = (MutableTreeNode) path.getPathComponent(path
    .getPathCount() - 1);
    if (node.getChildAt(0).toString().equals(PLACEHOLDER)) {
    node.remove(0);
    addDirToModel(fileFromPath(path), node);
    }
    }

    /**
    * valueChanged receives treeselection events and loads the file or dir into
    * detailpane
    */
    public void valueChanged(TreeSelectionEvent e) {

    TreePath p = tree.getSelectionPath();
    if (p != null) { // it could be null if the tree was just collapsed
    // and the selected node is invisible
    currentFile = fileFromPath(tree.getSelectionPath());
    // if we don't have permission, do nothing
    if (currentFile.canRead()) {
    // dp.receiveFile(currentFile, newFile);
    // Mise à jour du panneau de la galerie
    if (this.imagesBrowser != null)
    this.imagesBrowser
    .loadImages(currentFile.getAbsolutePath());
    } else {
    return;
    }
    }
    }

    // public static void main(String[] args) { FileTree ft = new
    // FileTree(null); ft.setSize(300, 600); ft.setLocation(100,100);
    // ft.setVisible(true); }
    /*
    * Obsolète
    *
    * public static void main(String[] args) { FileTree ft = new
    * FileTree(null); ft.setSize(300, 600); ft.setLocation(100,100);
    * ft.setVisible(true); }
    */

    /**
    * Filtre de fichier n'acceptant que les répertoires
    */
    class DirsOnlyFilter implements FilenameFilter {

    boolean showHidden;

    public DirsOnlyFilter(boolean showHidden) {
    this.showHidden = showHidden;
    }

    public boolean accept(File dir, String name) {
    File f = new File(dir.getPath() + File.separator + name);
    if (!f.isDirectory()) {
    return false;
    } else if (!showHidden) {
    return (!(name.startsWith(".") || f.isHidden()));
    }
    return true;
    }
    }

    }

    et la classe diaporama :

    package imagesBrowser;
    import java.io.File;
    import java.io.FilenameFilter;
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.Arrays;

    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.event.TreeExpansionEvent;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.event.TreeWillExpandListener;
    import javax.swing.text.Position;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.ExpandVetoException;
    import javax.swing.tree.MutableTreeNode;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeSelectionModel;

    import java.io.File;
    import java.io.IOException;

    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;

    public class Diaporama extends JFrame implements Runnable
    {

    private static final long serialVersionUID = 1L;

    private String folder;

    private String[] images;

    private int index;

    private JLabel image;

    public Diaporama(File folder) {
    super("Diaporama");
    images = folder.list();
    this.folder = folder.getAbsolutePath();
    index = 0;

    setSize(800, 600);
    image = new JLabel();
    add(new JScrollPane(image));

    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    }

    public void lireImage(String imageName) throws IOException {
    System.out.println(folder + imageName);
    image.setIcon(new ImageIcon(ImageIO.read(new File(folder + "\\"
    + imageName))));
    }

    public void run() {
    while (true) {

    try {
    lireImage(images[index]);
    } catch (IOException e) {
    e.printStackTrace();
    } catch (NullPointerException e) {
    }

    try {
    Thread.sleep(2000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }

    index = (index + 1) % images.length;

    }
    }

    public static void main(String[] args) {
    FileTree che=new FileTree(); //j'ai ajouter cet instruction

    Diaporama diap = new Diaporama(new File(che.getCurruntFile()));
    new Thread(diap).start();
    }
    }

    voila j'ai modifié le main de diaporama ms il ne conné ni la classe TreeFolder ni la methode ;
    est ce qu'il y a une faute dans la declaration ou ..?
    merci
    0
  4. b_khallou Messages postés 322 Date d'inscription   Statut Membre Dernière intervention   34
     
    c'est résolu

    public static void main(String[] args) {
    FileTree che;
    Diaporama diap = new Diaporama(new File(che.getCurrentFile()));
    new Thread(diap).start();
    }
    merci tarek_dotzero,
    0
    1. de passage
       
      Le mec il s'appel khaled et dans son code c'est écrit copyright Jim Burton....

      moi à sa place j'aurais au moins pris soin de retirer le copyright avant de le poster sur un forum :)
      0
      1. danimo > de passage
         
        Salut "de passage"

        Comment sais-tu si ce n'est pas une condition pour une utilisation libre de mettre ce texte ?

        Cordialement,

        Dan
        0