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

Interfaces Graphiques en Java Discussion :

IconDemoApp Problème IHM


Sujet :

Interfaces Graphiques en Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre habitué
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2014
    Messages
    11
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Mai 2014
    Messages : 11
    Par défaut IconDemoApp Problème IHM
    Bonjour, j'ai un problème assez bizarre : je travail sur windows actuellement ( question de place sur le disque...) : avec Eclipse, je développe une application Java, dans laquelle j'ai besoin pour mon IHM, d'utiliser l'exemple officiel sur le site d'oracle pour faire un diaporama d'image: seulement je n'arrive pas à charger les images !!!

    mon code actuel :

    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
    package main;
     
    import java.awt.BorderLayout;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.RenderingHints;
    import java.awt.event.ActionEvent;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.util.List;
    import javax.swing.AbstractAction;
     
    import javax.swing.BorderFactory;
    import javax.swing.Box;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JToolBar;
    import javax.swing.SwingUtilities;
    import javax.swing.SwingWorker;
     
    public class IconDemoApp extends JFrame {
     
        private JLabel photographLabel = new JLabel();
        private JToolBar buttonBar = new JToolBar();
     
        private String imagedir = "C:\\Users\\Prenom\\Documents\\application_JAVA\\";
     
        private MissingIcon placeholderIcon = new MissingIcon();
     
        /**
         * List of all the descriptions of the image files. These correspond one to
         * one with the image file names
         */
        private String[] imageCaptions = { "Original SUNW Logo", "The Clocktower",
        "Clocktower from the West", "The Mansion", "Sun Auditorium"};
     
        /**
         * List of all the image files to load.
         */
        //File fd=new File(imagedir);
        //private String imageFileNames[]=fd.list();
     
        private String[] imageFileNames = { "sunw01.jpg", "sunw02.jpg",
       "sunw03.jpg", "sunw04.jpg", "sunw05.jpg"};
        //private String[] imageFileNames = { "42-17425640.jpg", "e_logo.gif",
    //"reversed-saya.jpg", "logo.jpg", "mitsubishi_concept_ra-2.jpg"};
     
        /**
         * Main entry point to the demo. Loads the Swing elements on the "Event
         * Dispatch Thread".
         *
         * @param args
         */
        public static void main(String args[]) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    IconDemoApp app = new IconDemoApp();
                    app.setVisible(true);
                }
            });
        }
     
        /**
         * Default constructor for the demo.
         */
        public IconDemoApp() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setTitle("Icon Demo: Please Select an Image");
     
            // A label for displaying the pictures
            photographLabel.setVerticalTextPosition(JLabel.BOTTOM);
            photographLabel.setHorizontalTextPosition(JLabel.CENTER);
            photographLabel.setHorizontalAlignment(JLabel.CENTER);
            photographLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
     
            // We add two glue components. Later in process() we will add thumbnail buttons
            // to the toolbar inbetween thease glue compoents. This will center the
            // buttons in the toolbar.
            buttonBar.add(Box.createGlue());
            buttonBar.add(Box.createGlue());
     
            add(buttonBar, BorderLayout.SOUTH);
            add(photographLabel, BorderLayout.CENTER);
     
            setSize(400, 300);
     
            // this centers the frame on the screen
            setLocationRelativeTo(null);
     
            // start the image loading SwingWorker in a background thread
            loadimages.execute();
        }
     
        /**
         * SwingWorker class that loads the images a background thread and calls publish
         * when a new one is ready to be displayed.
         *
         * We use Void as the first SwingWroker param as we do not need to return
         * anything from doInBackground().
         */
        private SwingWorker<Void, ThumbnailAction> loadimages = new SwingWorker<Void, ThumbnailAction>() {
     
            /**
             * Creates full size and thumbnail versions of the target image files.
             */
            @Override
            protected Void doInBackground() throws Exception {
                for (int i = 0; i < imageCaptions.length; i++) {
                    ImageIcon icon;
                    icon = createImageIcon(imagedir+imageFileNames[i], imageCaptions[i]);
     
                    ThumbnailAction thumbAction;
                    if(icon != null){
     
                        ImageIcon thumbnailIcon = new ImageIcon(getScaledImage(icon.getImage(), 32, 32));
                        thumbAction = new ThumbnailAction(icon, thumbnailIcon, imageCaptions[i]);
     
                    }else{
                        // the image failed to load for some reason
                        // so load a placeholder instead
                        thumbAction = new ThumbnailAction(placeholderIcon, placeholderIcon, imageCaptions[i]);
                    }
                    publish(thumbAction);
     
                }
                // unfortunately we must return something, and only null is valid to
                // return when the return type is void.
                return null;
            }
     
            /**
             * Process all loaded images.
             */
            @Override
            protected void process(List<ThumbnailAction> chunks) {
                for (ThumbnailAction thumbAction : chunks) {
                    JButton thumbButton = new JButton(thumbAction);
                    // add the new button BEFORE the last glue
                    // this centers the buttons in the toolbar
                    buttonBar.add(thumbButton, buttonBar.getComponentCount() - 1);
                }
            }
        };
     
        /**
         * Creates an ImageIcon if the path is valid.
         * @param String - resource path
         * @param String - description of the file
         */
        protected ImageIcon createImageIcon(String path,
                String description) {
            java.net.URL imgURL = getClass().getResource(path);
            if (imgURL != null) {
                return new ImageIcon(imgURL, description);
            } else {
                System.err.println("Couldn't find file: " + path);
                return null;
            }
        }
     
        /**
         * Resizes an image using a Graphics2D object backed by a BufferedImage.
         * @param srcImg - source image to scale
         * @param w - desired width
         * @param h - desired height
         * @return - the new resized image
         */
        private Image getScaledImage(Image srcImg, int w, int h){
            BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = resizedImg.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2.drawImage(srcImg, 0, 0, w, h, null);
            g2.dispose();
            return resizedImg;
        }
     
        /**
         * Action class that shows the image specified in it's constructor.
         */
        private class ThumbnailAction extends AbstractAction{
     
            /**
             *The icon if the full image we want to display.
             */
            private Icon displayPhoto;
     
            /**
             * @param Icon - The full size photo to show in the button.
             * @param Icon - The thumbnail to show in the button.
             * @param String - The descriptioon of the icon.
             */
            public ThumbnailAction(Icon photo, Icon thumb, String desc){
                displayPhoto = photo;
     
                // The short description becomes the tooltip of a button.
                putValue(SHORT_DESCRIPTION, desc);
     
                // The LARGE_ICON_KEY is the key for setting the
                // icon when an Action is applied to a button.
                putValue(LARGE_ICON_KEY, thumb);
            }
     
            /**
             * Shows the full image in the main area and sets the application title.
             */
            public void afficherImage(){
                photographLabel.setIcon(displayPhoto);
                setTitle("Icon Demo: " + getValue(SHORT_DESCRIPTION).toString());
            }
            public void actionPerformed(ActionEvent e) {
                photographLabel.setIcon(displayPhoto);
                setTitle("Icon Demo: " + getValue(SHORT_DESCRIPTION).toString());
            }
        }
    }

  2. #2
    Expert éminent
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Par défaut
    Je suis à peu près sur que le code d'origine ne contient pas ce imageDir. Tout le code charge les images dans le classpath et toi tu essaie de lui faire cherger des trucs extérieurs, ce n'est pas prêt de marcher.

  3. #3
    Membre habitué
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2014
    Messages
    11
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Mai 2014
    Messages : 11
    Par défaut IconDemoApp
    Bonjour, déjà merci pour ta réponse ! Ensuite, d'accord, ok je ne savais même pas ce que c'était le classPath, je ne suis pas très bon en code, mais du coup ça signifie que je doit changer quoi dans le code pour que ça marche ?!

    ça c'est la page du code officiel :

    http://docs.oracle.com/javase/tutori...onDemoApp.java

  4. #4
    Modérateur
    Avatar de joel.drigo
    Homme Profil pro
    Ingénieur R&D - Développeur Java
    Inscrit en
    Septembre 2009
    Messages
    12 430
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 56
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur R&D - Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Septembre 2009
    Messages : 12 430
    Billets dans le blog
    2
    Par défaut
    Salut,

    java.net.URL imgURL = getClass().getResource(path); permet d'obtenir l'URL d'un fichier dont path est le chemin relatif au classpath, pas d'accèder à un fichier par son chemin absolu sur le disque. le classpath c'est la liste des dossiers qu'utilise la jvm pour chercher les classes et ressources dont il a besoin pour éxécuter le code.

    Soit tu passes par le classpath, il faut placer le dossier imagedir dans ton dossier de sources.
    Soit tu passes par des fichiers, et il te suffit de remplacer ce code par java.net.URL imgURL = new File(path).toURI().toURL().

    L'avantage de la première solution est que les fichiers d'images seront inclus dans le jar exporté de ton programme, qui sera constitué que d'un fichier, qui pourra être placé n'importe où et fonctionner, mais les fichiers d'images ne pourront être changés, sans refaire le jar.

    L'avantage de la seconde solution est qu'on peut ajouter ou supprimer des images dans le dossier, et éxécuter à nouveau le programme pour afficher les nouvelles images. Mais le nom du dossier est en dur dans le code, donc on est obligé de toujours mettre ce dossier à cet endroit exact. Une alternative est de mettre la valeur de imagedir en paramètre.
    L'expression "ça marche pas" ne veut rien dire. Indiquez l'erreur, et/ou les comportements attendus et obtenus, et donnez un Exemple Complet Minimal qui permet de reproduire le problème.
    La plupart des réponses à vos questions sont déjà dans les FAQs ou les Tutoriels, ou peut-être dans une autre discussion : utilisez la recherche interne.
    Des questions sur Java : consultez le Forum Java. Des questions sur l'EDI Eclipse ou la plateforme Eclipse RCP : consultez le Forum Eclipse.
    Une question correctement posée et rédigée et vous aurez plus de chances de réponses adaptées et rapides.
    N'oubliez pas de mettre vos extraits de code entre balises CODE (Voir Mode d'emploi de l'éditeur de messages).
    Nouveau sur le forum ? Consultez Les Règles du Club.

  5. #5
    Membre habitué
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2014
    Messages
    11
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Mai 2014
    Messages : 11
    Par défaut IconDemoApp
    Je te remercie pour ta réponse, qui ma permit de comprendre, et en plus d'enfin faire fonctionner ce code !! Merci encore

  6. #6
    Membre habitué
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2014
    Messages
    11
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Mai 2014
    Messages : 11
    Par défaut Splash
    Sinon, j'ai un autre problème, j'aimerais avoir un Splash ( une image qui s'affiche quelques seconde au démarrage de mon application, mais je ne vois pas comment faire !?

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Probléme avec une IHM
    Par titoufguigui dans le forum MFC
    Réponses: 17
    Dernier message: 18/03/2009, 15h28
  2. Petit problème sur l'ihm génèré [Léo 4.2]
    Par FredPsy dans le forum W4 Express
    Réponses: 2
    Dernier message: 18/02/2009, 18h00
  3. Probléme d'IHM au changement d'écran
    Par Flo. dans le forum VC++ .NET
    Réponses: 0
    Dernier message: 30/10/2007, 16h47
  4. [Patterns]Séparation IHM <-> Noyau : Problême de progress bar ?
    Par Muetdhiver dans le forum Design Patterns
    Réponses: 8
    Dernier message: 18/09/2007, 22h28
  5. Réponses: 8
    Dernier message: 06/05/2007, 00h25

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