IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

avec Java Discussion :

appeler une methode


Sujet :

avec Java

  1. #1
    Membre confirmé Avatar de khallou2007
    Profil pro
    Inscrit en
    Mars 2008
    Messages
    111
    Détails du profil
    Informations personnelles :
    Âge : 38
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations forums :
    Inscription : Mars 2008
    Messages : 111
    Par défaut appeler une methode
    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() :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     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() "

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    	/**
             * 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() "

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    	/** getCurrentFile returns the value of the currently selected file. */
    	public File getCurrentFile() {
    		return currentFile;
    	}
    alors je modifie le main du diaporama :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
     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.

  2. #2
    Membre éclairé
    Profil pro
    Inscrit en
    Décembre 2002
    Messages
    325
    Détails du profil
    Informations personnelles :
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Décembre 2002
    Messages : 325
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    StringBuffer sb = new StringBuffer();
    sb.append("pourrais-tu");
    sb.append("avoir");
    sb.append("l'amabilité");
    sb.append("de");
    sb.append("présenter");
    sb.append("ton problème");
    sb.append("de manière");
    sb.append("plus claire ?");
    System.out.println(sb.toString());
    System.out.println("Merci d'avance ;)");

  3. #3
    Membre confirmé Avatar de khallou2007
    Profil pro
    Inscrit en
    Mars 2008
    Messages
    111
    Détails du profil
    Informations personnelles :
    Âge : 38
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations forums :
    Inscription : Mars 2008
    Messages : 111
    Par défaut re
    tout simplement j'ai la class Diaporama (essai de la compiler et executer avec Jcreator , bi1sur en changant le repertoire d'images) :








    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    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) {
        	Diaporama diap = new Diaporama(new File("F:\\Khaled\\images"));
            new Thread(diap).start();
        }
    }
    mais j'essai de creer toute une application (interface graphique) (lister des images ds un panel et un bouton de diaporama) or j'ai pu importer des images et les lister (à l'aide des class " TreeFolder " , " ImagesBrowser" et autre..) alors je veut au lieu de faire entrer le chemin du repertoire d'image ds la class diaporama ,faire appel à une methode dans la class TreeFolder pour avoire le chemin (en cliquant sur un noeud) (voila le code de la class):
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    /**
     * 
     */
    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;
    		}
    	}
     
     
     
    }

Discussions similaires

  1. Réponses: 5
    Dernier message: 01/08/2006, 13h41
  2. Réponses: 2
    Dernier message: 19/05/2006, 15h53
  3. Réponses: 1
    Dernier message: 15/05/2006, 18h43
  4. [debutant]appeler une methode d'un autre document
    Par la7su dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 05/10/2005, 10h22
  5. Réponses: 2
    Dernier message: 15/08/2005, 20h54

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo