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

AWT/Swing Java Discussion :

Image dans ComboBox


Sujet :

AWT/Swing Java

  1. #1
    Membre confirmé
    Inscrit en
    Janvier 2011
    Messages
    100
    Détails du profil
    Informations forums :
    Inscription : Janvier 2011
    Messages : 100
    Par défaut Image dans ComboBox
    Bonjour,
    J'aimerais mettre une image + texte dans une ComboBox (Une seule image à coté du premier texte (indice 0)).
    J'ai utilisé le code repris ici et ça fonctionne chez moi.
    Mais dès que je souhaite implémenter ce code pour ma ComboBox, je rencontre plusieurs problèmes. Le plus récurrent est : 'Exception in thread "main" java.lang.NullPointerException
    at renderer.ComboBoxRenderer.getListCellRendererComponent' qui concerne la ligne 'int selectedIndex = ((Integer)value).intValue();' pour la méthode 'getListCellRendererComponent()'.
    Est-ce que quelqu'un peut m'aider ?
    Merci d'avance.
    Marc

  2. #2
    Modérateur
    Avatar de dinobogan
    Homme Profil pro
    ingénieur
    Inscrit en
    Juin 2007
    Messages
    4 073
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France

    Informations professionnelles :
    Activité : ingénieur
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2007
    Messages : 4 073
    Par défaut
    Donne ton code simplifié au maximum et compilable reproduisant le problème.
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java
    Que la force de la puissance soit avec le courage de ta sagesse.

  3. #3
    Membre confirmé
    Inscrit en
    Janvier 2011
    Messages
    100
    Détails du profil
    Informations forums :
    Inscription : Janvier 2011
    Messages : 100
    Par défaut
    Voici le code de la méthode de la class GUI:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    private JComboBox getJComboBoxClientsList() {
    		if (jComboBoxClientsList == null) {
    			CustomComboBox newContentPane = new CustomComboBox();
    			ComboBoxRenderer renderer = new ComboBoxRenderer(newContentPane.getImages(), newContentPane.getPetStrings());
    			jComboBoxClientsList = new JComboBox(newContentPane.getIntArray());
    			jComboBoxClientsList.setRenderer(renderer);
    			jComboBoxClientsList.setMaximumSize(jComboBoxClientsList.getPreferredSize());
    			jComboBoxClientsList.addActionListener(ccb);
    		}
    		return jComboBoxClientsList;
    	}
    Ensuite, la classe que j'ai nommée 'ComboBoxRenderer':
    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
    public class ComboBoxRenderer extends JLabel implements ListCellRenderer {
    	ImageIcon[] images;
        String[] petStrings = {"Bird", "Cat", "Dog", "Rabbit", "Pig"};
        private Font uhOhFont;
     
    	public ComboBoxRenderer(ImageIcon[] images,  String[] petStrings) {
    		setOpaque(true);
    		setHorizontalAlignment(CENTER);
    		setVerticalAlignment(CENTER);
    		this.images = images;
    		this.petStrings = petStrings;
    	}
     
    	/*
    	* This method finds the image and text corresponding
    	* to the selected value and returns the label, set up
    	* to display the text and image.
    	*/
    	public Component getListCellRendererComponent(
    	                JList list,
    	                Object value,
    	                int index,
    	                boolean isSelected,
    	                boolean cellHasFocus) {
    	//Get the selected index. (The index param isn't
    	//always valid, so just use the value.)
    	int selectedIndex = ((Integer)value).intValue();
     
    	if (isSelected) {
    	setBackground(list.getSelectionBackground());
    	setForeground(list.getSelectionForeground());
    	} else {
    	setBackground(list.getBackground());
    	setForeground(list.getForeground());
    	}
     
    	//Set the icon and text.  If icon was null, say so.
    	ImageIcon icon = images[selectedIndex];
    	String pet = petStrings[selectedIndex];
    	setIcon(icon);
    	if (icon != null) {
    	setText(pet);
    	setFont(list.getFont());
    	} else {
    	setUhOhText(pet + " (no image available)",
    	 list.getFont());
    	}
     
    	return this;
    	}
     
    	//Set the font and text when no image was found.
    	protected void setUhOhText(String uhOhText, Font normalFont) {
    	if (uhOhFont == null) { //lazily create this font
    	uhOhFont = normalFont.deriveFont(Font.ITALIC);
    	}
    	setFont(uhOhFont);
    	setText(uhOhText);
    	}
    }
    Et pour finir, la class que j'ai nommée 'CustomComboBox':
    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
    public class CustomComboBox extends JPanel {
        ImageIcon[] images;
        String[] petStrings = {"Bird", "Cat", "Dog", "Rabbit", "Pig"};
        Integer[] intArray = new Integer[petStrings.length];
     
        /*
         * Despite its use of EmptyBorder, this panel makes a fine content
         * pane because the empty border just increases the panel's size
         * and is "painted" on top of the panel's normal background.  In
         * other words, the JPanel fills its entire background if it's
         * opaque (which it is by default); adding a border doesn't change
         * that.
         */
        public CustomComboBox() {
            super(new BorderLayout());
     
            //Load the pet images and create an array of indexes.
            images = new ImageIcon[petStrings.length];
            Integer[] intArray = new Integer[petStrings.length];
            for (int i = 0; i < petStrings.length; i++) {
                intArray[i] = new Integer(i);
                images[0] = new ImageIcon(ClassLoader.getSystemResource("images/48x48/dualScreen.png"));
                if (images[i] != null) {
                    images[i].setDescription(petStrings[i]);
                }
            }
        }
     
        // GETTES-----------------------
     
    	public ImageIcon[] getImages() {
    		return images;
    	}
     
    	public String[] getPetStrings() {
    		return petStrings;
    	}
     
    	public Integer[] getIntArray() {
    		return intArray;
    	}
     
        /**
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
         */
     
    }

Discussions similaires

  1. Images dans un ComboBox
    Par yonpo dans le forum Windows Presentation Foundation
    Réponses: 3
    Dernier message: 10/11/2010, 19h05
  2. Comment insérer des images dans une ComboBox HTML ?
    Par UiYuki dans le forum Balisage (X)HTML et validation W3C
    Réponses: 2
    Dernier message: 29/08/2010, 15h35
  3. Afficher des images depuis une table dans combobox
    Par sihammaster dans le forum VB.NET
    Réponses: 2
    Dernier message: 13/04/2010, 19h51
  4. Images dans combobox
    Par Arthis dans le forum ASP.NET
    Réponses: 1
    Dernier message: 13/08/2007, 14h15
  5. Probleme image dans combobox.
    Par devoluti0n dans le forum Delphi
    Réponses: 11
    Dernier message: 10/07/2007, 09h53

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