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

Agents de placement/Fenêtres Java Discussion :

tooltiptext sur jfilechooser


Sujet :

Agents de placement/Fenêtres Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre éclairé Avatar de donnadieujulien
    Développeur informatique
    Inscrit en
    Avril 2008
    Messages
    433
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Avril 2008
    Messages : 433
    Par défaut tooltiptext sur jfilechooser
    Bonjour,

    j'aimerais afficher un tooltiptext dans un jfilechooser selon le fichier ou se trouve la souris, c'est possible?

  2. #2
    Nouveau candidat au Club
    Homme Profil pro
    Stagiaire génie logiciel
    Inscrit en
    Juillet 2018
    Messages
    2
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 28
    Localisation : Canada

    Informations professionnelles :
    Activité : Stagiaire génie logiciel

    Informations forums :
    Inscription : Juillet 2018
    Messages : 2
    Par défaut
    J'essaye également de réaliser ceci. Quelqu'un a une solution ?

    Merci d'avance ~

  3. #3
    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,

    Cela dépend de ce que tu veux afficher dans l'infobulle.

    1. Un simple texte
    2. Quelque chose de plus complexe, texte sur plusieurs lignes, images, texte stylé... en bref, tout ce qui n'est pas un simple tooltiptext.



    Pour le cas du texte simple, le principe peut être de simplement récupérer les sous-composants d'affichage pour leur affecter un tooltip. Il y en a deux, une JList pour la présentation en mosaïque, et une JTable pour la présentation en table.

    Voici un POC de base pour le principe :


    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
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.event.ContainerEvent;
    import java.awt.event.ContainerListener;
    import java.io.File;
    import java.util.Arrays;
    import java.util.Set;
    import java.util.stream.Collectors;
     
    import javax.swing.JComponent;
    import javax.swing.JFileChooser;
    import javax.swing.JList;
    import javax.swing.JTable;
    import javax.swing.ListCellRenderer;
    import javax.swing.SwingUtilities;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
     
    import darrylbu.util.SwingUtils;
     
    public interface JFileChooserTooltip { 
     
    	String getTooltipText(File file);
     
    	public static void main(String[] args) throws ClassNotFoundException {
    		JFileChooser filechooser = new JFileChooser();
    		setTooltip(filechooser, f-> f.getName());
    		filechooser.showOpenDialog(null);
    	}
     
    	@SuppressWarnings({ "rawtypes", "unchecked" })
    	public static void setTooltip(JFileChooser chooser, JFileChooserTooltip tooltip) throws ClassNotFoundException {
     
    		final JFileChooserTooltip ftooltip = tooltip==null?f->f.getName():tooltip; 
    	    final JList list = SwingUtils.getDescendantOfType(JList.class, chooser, "Enabled", true);
     
    	    // JList
    	    final ListCellRenderer listRenderer = list.getCellRenderer();
    	    final ListCellRenderer withTooltipListRenderer = new ListCellRenderer() {
    			@Override
    	    	public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
    	    			boolean cellHasFocus) {
    	    		Component component = listRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
    	    		if ( value instanceof File ) {
    	    			((JComponent)component).setToolTipText(ftooltip.getTooltipText((File)value));
    	    		}
    				else {
    	    			((JComponent)component).setToolTipText(null);
    				}
    	    		return component;
     
    	    	}
    		};
    		list.setCellRenderer(withTooltipListRenderer);
     
    		Container container = SwingUtilities.getAncestorOfClass(Container.class, list);
    		container = SwingUtilities.getAncestorOfClass(Container.class, container); // viewport
    		container = SwingUtilities.getAncestorOfClass(Container.class, container); // scrollpane
    		container = SwingUtilities.getAncestorOfClass(Container.class, container); // container
    		container.addContainerListener(new ContainerListener() {
     
    			private boolean done;
     
    			@Override
    			public void componentRemoved(ContainerEvent e) {
    			}
     
    			@Override
    			public void componentAdded(ContainerEvent e) {
    			    final JTable table = SwingUtils.getDescendantOfType(JTable.class, chooser, "Enabled", true);
    			    if ( table!=null && !done ) {
    			    	done=true;
    				    replaceCellRenderer(table, 0); // remplacement uniquement sur la première colonne (nom du fichier)
    				    setCancelTooltipTextCellRenderer(table, 0); // nécessaire pour désactiver le tooltip
    			    }
     
    			}
     
    			private void setCancelTooltipTextCellRenderer(JTable table, int...exclude) {
    				final Set<Integer> excludedColumnsSet = Arrays.stream(exclude).mapToObj(i->i).collect(Collectors.toSet());
    				for(int i=0; i<table.getColumnCount(); i++) {
    					if ( excludedColumnsSet.contains(i) ) continue;
    					setCancelCellRenderer(table, i);
    				}
    			}
     
    			private void setCancelCellRenderer(JTable table, int colIndex) {
    				final TableColumn col = table.getColumnModel().getColumn(colIndex);
    				final TableCellRenderer tableCellRenderer = getTableCellRenderer(table, col); 
    				final TableCellRenderer withTooltipTableCellRenderer = new TableCellRenderer() {
     
    					@Override
    					public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
    							boolean hasFocus, int row, int column) {
    						Component component = tableCellRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    						((JComponent)component).setToolTipText(null);
    						return component;
    					}
     
    				};
    				col.setCellRenderer(withTooltipTableCellRenderer);
    			}
     
    			private void replaceCellRenderer(JTable table, int colIndex) {
    				final TableColumn col = table.getColumnModel().getColumn(colIndex);
    				final TableCellRenderer tableCellRenderer = getTableCellRenderer(table, col); 
    				final TableCellRenderer withTooltipTableCellRenderer = new TableCellRenderer() {
     
    					@Override
    					public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
    							boolean hasFocus, int row, int column) {
    						Component component = tableCellRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    						if ( value instanceof File ) {
    			    			((JComponent)component).setToolTipText(ftooltip.getTooltipText((File)value));
    			    		}
    						else {
    							value = table.getValueAt(row, 0);
    							if ( value instanceof File ) {
    				    			((JComponent)component).setToolTipText(ftooltip.getTooltipText((File)value));
    				    		}
    							else {
    				    			((JComponent)component).setToolTipText(null);
    							}
    						}
    						return component;
    					}
     
    				};
    				col.setCellRenderer(withTooltipTableCellRenderer);
    			}
     
    			private TableCellRenderer getTableCellRenderer(JTable table, TableColumn col) {
    				TableCellRenderer tableCellRenderer = col.getCellRenderer();
    				if ( tableCellRenderer==null ) { // pas de renderer specifique
    					Class<?> k = table.getModel().getColumnClass(col.getModelIndex());
    					tableCellRenderer = table.getDefaultRenderer(k);
    				}
    				return tableCellRenderer;
    			}
     
    		});
    	}
     
    }


    J'ai utilisé l'utilitaire SwingUtils. Le reste c'est du standard.

    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
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    /*
     * @(#)SwingUtils.java	1.02 11/15/08
     *
     */
    package darrylbu.util;
     
    import java.awt.Component;
    import java.awt.Container;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import javax.swing.JComponent;
    import javax.swing.UIDefaults;
    import javax.swing.UIManager;
     
    /**
     * A collection of utility methods for Swing.
     *
     * @author Darryl Burke
     */
    public final class SwingUtils {
     
       private SwingUtils() {
          throw new Error("SwingUtils is just a container for static methods");
       }
     
       /**
        * Convenience method for searching below <code>container</code> in the
        * component hierarchy and return nested components that are instances of
        * class <code>clazz</code> it finds. Returns an empty list if no such
        * components exist in the container.
        * <P>
        * Invoking this method with a class parameter of JComponent.class
        * will return all nested components.
        * <P>
        * This method invokes getDescendantsOfType(clazz, container, true)
        * 
        * @param clazz the class of components whose instances are to be found.
        * @param container the container at which to begin the search
        * @return the List of components
        */
       public static <T extends JComponent> List<T> getDescendantsOfType(
             Class<T> clazz, Container container) {
          return getDescendantsOfType(clazz, container, true);
       }
     
       /**
        * Convenience method for searching below <code>container</code> in the
        * component hierarchy and return nested components that are instances of
        * class <code>clazz</code> it finds. Returns an empty list if no such
        * components exist in the container.
        * <P>
        * Invoking this method with a class parameter of JComponent.class
        * will return all nested components.
        * 
        * @param clazz the class of components whose instances are to be found.
        * @param container the container at which to begin the search
        * @param nested true to list components nested within another listed
        * component, false otherwise
        * @return the List of components
        */
       public static <T extends JComponent> List<T> getDescendantsOfType(
             Class<T> clazz, Container container, boolean nested) {
          List<T> tList = new ArrayList<T>();
          for (Component component : container.getComponents()) {
             if (clazz.isAssignableFrom(component.getClass())) {
                tList.add(clazz.cast(component));
             }
             if (nested || !clazz.isAssignableFrom(component.getClass())) {
                tList.addAll(SwingUtils.<T>getDescendantsOfType(clazz,
                      (Container) component, nested));
             }
          }
          return tList;
       }
     
       /**
        * Convenience method that searches below <code>container</code> in the
        * component hierarchy and returns the first found component that is an
        * instance of class <code>clazz</code> having the bound property value.
        * Returns {@code null} if such component cannot be found.
        * <P>
        * This method invokes getDescendantOfType(clazz, container, property, value,
        * true)
        * 
        * @param clazz the class of component whose instance is to be found.
        * @param container the container at which to begin the search
        * @param property the className of the bound property, exactly as expressed in
        * the accessor e.g. "Text" for getText(), "Value" for getValue().
        * @param value the value of the bound property
        * @return the component, or null if no such component exists in the
        * container
        * @throws java.lang.IllegalArgumentException if the bound property does
        * not exist for the class or cannot be accessed
        */
       public static <T extends JComponent> T getDescendantOfType(
             Class<T> clazz, Container container, String property, Object value)
             throws IllegalArgumentException {
          return getDescendantOfType(clazz, container, property, value, true);
       }
     
       /**
        * Convenience method that searches below <code>container</code> in the
        * component hierarchy and returns the first found component that is an
        * instance of class <code>clazz</code> and has the bound property value.
        * Returns {@code null} if such component cannot be found.
        * 
        * @param clazz the class of component whose instance to be found.
        * @param container the container at which to begin the search
        * @param property the className of the bound property, exactly as expressed in
        * the accessor e.g. "Text" for getText(), "Value" for getValue().
        * @param value the value of the bound property
        * @param nested true to list components nested within another component
        * which is also an instance of <code>clazz</code>, false otherwise
        * @return the component, or null if no such component exists in the
        * container
        * @throws java.lang.IllegalArgumentException if the bound property does
        * not exist for the class or cannot be accessed
        */
       public static <T extends JComponent> T getDescendantOfType(Class<T> clazz,
             Container container, String property, Object value, boolean nested)
             throws IllegalArgumentException {
          List<T> list = getDescendantsOfType(clazz, container, nested);
          return getComponentFromList(clazz, list, property, value);
       }
     
       /**
        * Convenience method for searching below <code>container</code> in the
        * component hierarchy and return nested components of class
        * <code>clazz</code> it finds.  Returns an empty list if no such
        * components exist in the container.
        * <P>
        * This method invokes getDescendantsOfClass(clazz, container, true)
        * 
        * @param clazz the class of components to be found.
        * @param container the container at which to begin the search
        * @return the List of components
        */
       public static <T extends JComponent> List<T> getDescendantsOfClass(
             Class<T> clazz, Container container) {
          return getDescendantsOfClass(clazz, container, true);
       }
     
       /**
        * Convenience method for searching below <code>container</code> in the
        * component hierarchy and return nested components of class
        * <code>clazz</code> it finds.  Returns an empty list if no such
        * components exist in the container.
        * 
        * @param clazz the class of components to be found.
        * @param container the container at which to begin the search
        * @param nested true to list components nested within another listed
        * component, false otherwise
        * @return the List of components
        */
       public static <T extends JComponent> List<T> getDescendantsOfClass(
             Class<T> clazz, Container container, boolean nested) {
          List<T> tList = new ArrayList<T>();
          for (Component component : container.getComponents()) {
             if (clazz.equals(component.getClass())) {
                tList.add(clazz.cast(component));
             }
             if (nested || !clazz.equals(component.getClass())) {
                tList.addAll(SwingUtils.<T>getDescendantsOfClass(clazz,
                      (Container) component, nested));
             }
          }
          return tList;
       }
     
       /**
        * Convenience method that searches below <code>container</code> in the
        * component hierarchy in a depth first manner and returns the first
        * found component of class <code>clazz</code> having the bound property
        * value.
        * <P>
        * Returns {@code null} if such component cannot be found.
        * <P>
        * This method invokes getDescendantOfClass(clazz, container, property,
        * value, true)
        * 
        * @param clazz the class of component to be found.
        * @param container the container at which to begin the search
        * @param property the className of the bound property, exactly as expressed in
        * the accessor e.g. "Text" for getText(), "Value" for getValue().
        * This parameter is case sensitive.
        * @param value the value of the bound property
        * @return the component, or null if no such component exists in the
        * container's hierarchy.
        * @throws java.lang.IllegalArgumentException if the bound property does
        * not exist for the class or cannot be accessed
        */
       public static <T extends JComponent> T getDescendantOfClass(Class<T> clazz,
             Container container, String property, Object value)
             throws IllegalArgumentException {
          return getDescendantOfClass(clazz, container, property, value, true);
       }
     
       /**
        * Convenience method that searches below <code>container</code> in the
        * component hierarchy in a depth first manner and returns the first
        * found component of class <code>clazz</code> having the bound property
        * value.
        * <P>
        * Returns {@code null} if such component cannot be found.
        * 
        * @param clazz the class of component to be found.
        * @param container the container at which to begin the search
        * @param property the className of the bound property, exactly as expressed
        * in the accessor e.g. "Text" for getText(), "Value" for getValue().
        * This parameter is case sensitive.
        * @param value the value of the bound property
        * @param nested true to include components nested within another listed
        * component, false otherwise
        * @return the component, or null if no such component exists in the
        * container's hierarchy
        * @throws java.lang.IllegalArgumentException if the bound property does
        * not exist for the class or cannot be accessed
        */
       public static <T extends JComponent> T getDescendantOfClass(Class<T> clazz,
             Container container, String property, Object value, boolean nested)
             throws IllegalArgumentException {
          List<T> list = getDescendantsOfClass(clazz, container, nested);
          return getComponentFromList(clazz, list, property, value);
       }
     
       private static <T extends JComponent> T getComponentFromList(Class<T> clazz,
             List<T> list, String property, Object value)
             throws IllegalArgumentException {
          T retVal = null;
          Method method = null;
          try {
             method = clazz.getMethod("get" + property);
          } catch (NoSuchMethodException ex) {
             try {
                method = clazz.getMethod("is" + property);
             } catch (NoSuchMethodException ex1) {
                throw new IllegalArgumentException("Property " + property +
                      " not found in class " + clazz.getName());
             }
          }
          try {
             for (T t : list) {
                Object testVal = method.invoke(t);
                if (equals(value, testVal)) {
                   return t;
                }
             }
          } catch (InvocationTargetException ex) {
             throw new IllegalArgumentException(
                   "Error accessing property " + property +
                   " in class " + clazz.getName());
          } catch (IllegalAccessException ex) {
             throw new IllegalArgumentException(
                   "Property " + property +
                   " cannot be accessed in class " + clazz.getName());
          } catch (SecurityException ex) {
             throw new IllegalArgumentException(
                   "Property " + property +
                   " cannot be accessed in class " + clazz.getName());
          }
          return retVal;
       }
     
       /**
        * Convenience method for determining whether two objects are either
        * equal or both null.
        * 
        * @param obj1 the first reference object to compare.
        * @param obj2 the second reference object to compare.
        * @return true if obj1 and obj2 are equal or if both are null,
        * false otherwise
        */
       public static boolean equals(Object obj1, Object obj2) {
          return obj1 == null ? obj2 == null : obj1.equals(obj2);
       }
     
       /**
        * Convenience method for mapping a container in the hierarchy to its
        * contained components.  The keys are the containers, and the values
        * are lists of contained components.
        * <P>
        * Implementation note:  The returned value is a HashMap and the values
        * are of type ArrayList.  This is subject to change, so callers should
        * code against the interfaces Map and List.
        * 
        * @param container The JComponent to be mapped
        * @param nested true to drill down to nested containers, false otherwise
        * @return the Map of the UI
        */
       public static Map<JComponent, List<JComponent>> getComponentMap(
             JComponent container, boolean nested) {
          HashMap<JComponent, List<JComponent>> retVal =
                new HashMap<JComponent, List<JComponent>>();
          for (JComponent component : getDescendantsOfType(JComponent.class,
                container, false)) {
             if (!retVal.containsKey(container)) {
                retVal.put(container,
                      new ArrayList<JComponent>());
             }
             retVal.get(container).add(component);
             if (nested) {
                retVal.putAll(getComponentMap(component, nested));
             }
          }
          return retVal;
       }
     
       /**
        * Convenience method for retrieving a subset of the UIDefaults pertaining
        * to a particular class.
        * 
        * @param clazz the class of interest
        * @return the UIDefaults of the class
        */
       public static UIDefaults getUIDefaultsOfClass(Class clazz) {
          String name = clazz.getName();
          name = name.substring(name.lastIndexOf(".") + 2);
          return getUIDefaultsOfClass(name);
       }
     
       /**
        * Convenience method for retrieving a subset of the UIDefaults pertaining
        * to a particular class.
        * 
        * @param className fully qualified name of the class of interest
        * @return the UIDefaults of the class named
        */
       public static UIDefaults getUIDefaultsOfClass(String className) {
          UIDefaults retVal = new UIDefaults();
          UIDefaults defaults = UIManager.getLookAndFeelDefaults();
          List<?> listKeys = Collections.list(defaults.keys());
          for (Object key : listKeys) {
             if (key instanceof String && ((String) key).startsWith(className)) {
                String stringKey = (String) key;
                String property = stringKey;
                if (stringKey.contains(".")) {
                   property = stringKey.substring(stringKey.indexOf(".") + 1);
                }
                retVal.put(property, defaults.get(key));
             }
          }
          return retVal;
       }
     
       /**
        * Convenience method for retrieving the UIDefault for a single property
        * of a particular class.
        * 
        * @param clazz the class of interest
        * @param property the property to query
        * @return the UIDefault property, or null if not found
        */
       public static Object getUIDefaultOfClass(Class clazz, String property) {
          Object retVal = null;
          UIDefaults defaults = getUIDefaultsOfClass(clazz);
          List<Object> listKeys = Collections.list(defaults.keys());
          for (Object key : listKeys) {
             if (key.equals(property)) {
                return defaults.get(key);
             }
             if (key.toString().equalsIgnoreCase(property)) {
                retVal = defaults.get(key);
             }
          }
          return retVal;
       }
     
       /**
        * Exclude methods that return values that are meaningless to the user
        */
       static Set<String> setExclude = new HashSet<String>();
       static {
          setExclude.add("getFocusCycleRootAncestor");
          setExclude.add("getAccessibleContext");
          setExclude.add("getColorModel");
          setExclude.add("getGraphics");
          setExclude.add("getGraphicsConfiguration");
       }
     
       /**
        * Convenience method for obtaining most non-null human readable properties
        * of a JComponent.  Array properties are not included.
        * <P>
        * Implementation note:  The returned value is a HashMap.  This is subject
        * to change, so callers should code against the interface Map.
        * 
        * @param component the component whose proerties are to be determined
        * @return the class and value of the properties
        */
       public static Map<Object, Object> getProperties(JComponent component) {
          Map<Object, Object> retVal = new HashMap<Object, Object>();
          Class<?> clazz = component.getClass();
          Method[] methods = clazz.getMethods();
          Object value = null;
          for (Method method : methods) {
             if (method.getName().matches("^(is|get).*") &&
                   method.getParameterTypes().length == 0) {
                try {
                   Class returnType = method.getReturnType();
                   if (returnType != void.class &&
                         !returnType.getName().startsWith("[") &&
                         !setExclude.contains(method.getName())) {
                      String key = method.getName();
                      value = method.invoke(component);
                      if (value != null && !(value instanceof Component)) {
                         retVal.put(key, value);
                      }
                   }
                // ignore exceptions that arise if the property could not be accessed
                } catch (IllegalAccessException ex) {
                } catch (IllegalArgumentException ex) {
                } catch (InvocationTargetException ex) {
                }
             }
          }
          return retVal;
       }
     
       /**
        * Convenience method to obtain the Swing class from which this
        * component was directly or indirectly derived.
        * 
        * @param component The component whose Swing superclass is to be
        * determined
        * @return The nearest Swing class in the inheritance tree
        */
       public static <T extends JComponent> Class getJClass(T component) {
          Class<?> clazz = component.getClass();
          while (!clazz.getName().matches("javax.swing.J[^.]*$")) {
             clazz = clazz.getSuperclass();
          }
          return clazz;
       }
    }


    Pour l'autre cas, il faut passer par un JToolTip, donc redéfinir la méthode createToolTip(), écouter les événements qui vont bien (détecter le changement de type de vue, détecter le mouvement de la souris, localiser le composant d'affichage en-dessous, etc. Plus siouxe et plus long à mettre au point.
    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.

  4. #4
    Nouveau candidat au Club
    Homme Profil pro
    Stagiaire génie logiciel
    Inscrit en
    Juillet 2018
    Messages
    2
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 28
    Localisation : Canada

    Informations professionnelles :
    Activité : Stagiaire génie logiciel

    Informations forums :
    Inscription : Juillet 2018
    Messages : 2
    Par défaut
    Salut,

    En fait, je voulais afficher le nom du fichier ou du dossier dans l'infobulle.

    J'ai trouvé un moyen d'obtenir ce que je voulais, merci pour ton aide

    1 - obtenir la liste (j'ai employé une autre façon)

    2 - ajouter un mouse listener sur la liste

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
    jList.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {
                JList l = (JList)e.getSource();
                ListModel m = l.getModel();
                int index = l.locationToIndex(e.getPoint());
                if( index>-1 ) {
                    l.setToolTipText(m.getElementAt(index).toString());
                }
            }
        });

Discussions similaires

  1. Focus sur JFileChooser lancer depuis une jsp
    Par Meunier dans le forum AWT/Swing
    Réponses: 7
    Dernier message: 13/09/2006, 22h23
  2. Utilisation d'un tooltiptext sur une cellule ..
    Par mitje dans le forum AWT/Swing
    Réponses: 7
    Dernier message: 01/07/2006, 02h44
  3. ToolTipText sur plusieurs lignes
    Par Nicool dans le forum AWT/Swing
    Réponses: 5
    Dernier message: 20/06/2006, 18h23
  4. Mettre une info bulle Tooltiptext sur un rectangle?
    Par danje dans le forum Graphisme
    Réponses: 7
    Dernier message: 21/11/2005, 09h31
  5. [JTree] ToolTipText sur chaque node
    Par Stessy dans le forum Composants
    Réponses: 6
    Dernier message: 19/04/2005, 16h01

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