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

Composants Java Discussion :

Récupérer et comparer la valeur d'un JCombobox


Sujet :

Composants Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre éclairé
    Profil pro
    Inscrit en
    Novembre 2007
    Messages
    426
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2007
    Messages : 426
    Par défaut Récupérer et comparer la valeur d'un JCombobox
    Bonjour à tous,

    J'ai un problème au coeur de mon projet, ce n'est pas facile à expliquer car tout est lié, mais je vais essayer d'être claire car j'ai vraiment besoin d'aide.

    En gros, j'essaye de récupérer la valeur d'un JCombobox (sachant que c'est un combobox que j'ai customisé car il contient une image juste avant le texte comme dans cet exemple la : exemple) et cette valeur je veux la comparer à un tableau de string.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
    public void itemStateChanged(ItemEvent e) {
    		ind = -1;
    		for (int i = 0; i < maxInd; i++) {
    			if (((String)e.getItem()).compareTo( str[i]) == 0)
    				ind = i + 1;
    		}
     
    	}
    Avant que je mette les images, cette méthode avec compareTo marchait nickel. Maintenant ça plante direct sur cette ligne avec le compareTo. L'erreur est la suivante :
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
    Je précise que str est définit de la manière suivante :
    Pourriez-vous m'aider svp?
    Merci à tous!
    Aud-

  2. #2
    Membre éclairé
    Profil pro
    Inscrit en
    Novembre 2007
    Messages
    426
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2007
    Messages : 426
    Par défaut
    je viens de mettre des mouchards et voila ce que j'obtiens:
    valeur de str:Lyon
    valeur de getItem:0

    Le problème c'est donc que j'ai un texte et l'autre un chiffre donc il ne peux pas comparer les chaines de caracteres. Que faire?
    Le problème réside dans le fait qu'il y a une image juste avant le texte. Comment puis-je récupérer uniquement le texte qui se trouve à coté de l'image?

    Voici le code qui customize mon ComboBox:
    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
    class ComboBoxRenderer extends JLabel implements ListCellRenderer {
    		private Font monFont;
     
    		public ComboBoxRenderer() {
    			setOpaque(true);
    			setHorizontalAlignment(LEFT);
    			setVerticalAlignment(TOP);
    		}
     
    		/**
                     * 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 logo = logoStrings[selectedIndex];
    			setIcon(icon);
    			if (icon != null) {
    				setText(logo);
    				setFont(list.getFont());
    			} else {
    				setmonText(logo + " (no image available)", list.getFont());
    			}
     
    			return this;
    		}
     
    		// Set the font and text when no image was found.
    		protected void setmonText(String monText, Font normalFont) {
    			if (monFont == null) { // lazily create this font
    				monFont = normalFont.deriveFont(Font.ITALIC);
    			}
    			setFont(monFont);
    			setText(monText);
    		}
    	}
    Et voici ma classe complete :
    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
    package com.ourco.util;
     
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
     
    public class WChoice extends JPanel implements ItemListener {
    	private JComboBox meschoix;
    	private String str[];
    	private int ind;
    	private int maxInd;
    	ImageIcon[] images;
    	String[] logoStrings = { "Lyon", "Bordeaux", "Lille", "Lens", "Marseille",
    			"Rennes", "Auxerre", "Paris", "Nice", "Le_Mans", "Monaco", "Nancy",
    			"Nantes", "St-Etienne", "Toulouse", "Sochaux", "Troyes", "Ajaccio",
    			"Strasbourg", "Metz" };
     
    	public void init() {
     
    		images = new ImageIcon[logoStrings.length];
    		Integer[] intArray = new Integer[logoStrings.length];
     
    		Championnat ch = new Championnat("test.txt");
    		str = new String[ch.getNbrMaxEq()];
    		maxInd = ch.getNbrMaxEq();
     
    		for (int i = 0; i < ch.getNbrMaxEq(); i++) {
    			str[i] = ch.getNomEquipe(i + 1);
     
    			intArray[i] = new Integer(i);
    			images[i] = createImageIcon("images/" + logoStrings[i] + ".jpg");
     
    			if (images[i] != null) { images[i].setDescription(logoStrings[i]); }
     
    			JComponent newContentPane = new WChoice();
    			newContentPane.setOpaque(true); 
     
    		}
     
    		// Creation du combo box.
    		meschoix = new JComboBox(intArray);
    		ComboBoxRenderer renderer = new ComboBoxRenderer(); //mon custom d'un combobox
    		renderer.setPreferredSize(new Dimension(130, 50)); //taille du combobox
    		meschoix.setRenderer(renderer);
    		meschoix.setMaximumRowCount(3);
     
    		// Lay out the demo.
    		add(meschoix, BorderLayout.PAGE_START);
    		meschoix.addItemListener(this);
    	}
     
    	/** Retourne une imageIcone sinon null si le path n'est pas valide */
    	protected static ImageIcon createImageIcon(String path) {
    		java.net.URL imgURL = WChoice.class.getResource(path);
    		if (imgURL != null) {
    			return new ImageIcon(imgURL);
    		} else {
    			System.err.println("Couldn't find file: " + path);
    			return null;
    		}
    	}
     
    	public void itemStateChanged(ItemEvent e) {
    		ind = -1;
    		for (int i = 0; i < maxInd; i++) {
    			System.out.println("valeur de str:"+str[i]);
    			System.out.println("valeur de getItem:"+ e.getItem()+"\n");
    			if (((String)e.getItem()).compareTo( str[i]) == 0)
    				ind = i + 1;
    			System.out.println("valeur de ind dans if:"+ind);
    		}
     
    	}
     
    	public int getInd() {
    		if (ind == 0)
    			ind = 1;
    		 System.out.println("valeur de ind WChoice1 retourné:"+ind);
    		return ind;
    	}
     
    	class ComboBoxRenderer extends JLabel implements ListCellRenderer {
    		private Font monFont;
     
    		public ComboBoxRenderer() {
    			setOpaque(true);
    			setHorizontalAlignment(LEFT);
    			setVerticalAlignment(TOP);
    		}
     
    		/**
                     * 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 logo = logoStrings[selectedIndex];
    			setIcon(icon);
    			if (icon != null) {
    				setText(logo);
    				setFont(list.getFont());
    			} else {
    				setmonText(logo + " (no image available)", list.getFont());
    			}
     
    			return this;
    		}
     
    		// Set the font and text when no image was found.
    		protected void setmonText(String monText, Font normalFont) {
    			if (monFont == null) { // lazily create this font
    				monFont = normalFont.deriveFont(Font.ITALIC);
    			}
    			setFont(monFont);
    			setText(monText);
    		}
    	}
    }

  3. #3
    Membre éclairé
    Profil pro
    Inscrit en
    Novembre 2007
    Messages
    426
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2007
    Messages : 426
    Par défaut
    J'ai remplacé le getItem() par "logo" que j'ai déclaré en private au debut :
    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
    package com.ourco.util;
     
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
     
    public class WChoice extends JPanel implements ItemListener {
    	private JComboBox meschoix;
    	private String str[];
    	private int ind;
    	private int maxInd;
    	private String logo;
    	ImageIcon[] images;
    	String[] logoStrings = { "Lyon", "Bordeaux", "Lille", "Lens", "Marseille",
    			"Rennes", "Auxerre", "Paris", "Nice", "Le_Mans", "Monaco", "Nancy",
    			"Nantes", "St-Etienne", "Toulouse", "Sochaux", "Troyes", "Ajaccio",
    			"Strasbourg", "Metz" };
     
    	public void init() {
     
    		images = new ImageIcon[logoStrings.length];
    		Integer[] intArray = new Integer[logoStrings.length];
     
    		Championnat ch = new Championnat("test.txt");
    		str = new String[ch.getNbrMaxEq()];
    		maxInd = ch.getNbrMaxEq();
     
    		for (int i = 0; i < ch.getNbrMaxEq(); i++) {
    			str[i] = ch.getNomEquipe(i + 1);
     
    			intArray[i] = new Integer(i);
    			images[i] = createImageIcon("images/" + logoStrings[i] + ".jpg");
     
    			if (images[i] != null) { images[i].setDescription(logoStrings[i]); }
     
    			JComponent newContentPane = new WChoice();
    			newContentPane.setOpaque(true); 
     
    		}
     
    		// Creation du combo box.
    		meschoix = new JComboBox(intArray);
    		ComboBoxRenderer renderer = new ComboBoxRenderer(); //mon custom d'un combobox
    		renderer.setPreferredSize(new Dimension(130, 50)); //taille du combobox
    		meschoix.setRenderer(renderer);
    		meschoix.setMaximumRowCount(3);
     
    		// Lay out the demo.
    		add(meschoix, BorderLayout.PAGE_START);
    		meschoix.addItemListener(this);
    	}
     
    	/** Retourne une imageIcone sinon null si le path n'est pas valide */
    	protected static ImageIcon createImageIcon(String path) {
    		java.net.URL imgURL = WChoice.class.getResource(path);
    		if (imgURL != null) {
    			return new ImageIcon(imgURL);
    		} else {
    			System.err.println("Couldn't find file: " + path);
    			return null;
    		}
    	}
     
    	public void itemStateChanged(ItemEvent e) {
    		ind = -1;
    		for (int i = 0; i < maxInd; i++) {
    			System.out.println("valeur de str:"+str[i]);
    			System.out.println("valeur de i:"+i);
    			System.out.println("valeur de getItem:"+ e.getItem());
    			System.out.println("valeur de logo:"+ logo);
    			if ((logo).compareTo(str[i]) == 0)
    				ind = i + 1;
     
    			System.out.println("valeur de ind dans if:"+ind+"\n");
    		}
     
    	}
     
    	public int getInd() {
    		if (ind == 0)
    			ind = 1;
    		 System.out.println("valeur de ind WChoice1 retourné:"+ind);
    		return ind;
    	}
     
    	class ComboBoxRenderer extends JLabel implements ListCellRenderer {
    		private Font monFont;
     
    		public ComboBoxRenderer() {
    			setOpaque(true);
    			setHorizontalAlignment(LEFT);
    			setVerticalAlignment(TOP);
    		}
     
    		/**
                     * 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];
    			logo ="";
    			logo = logoStrings[selectedIndex];
    			setIcon(icon);
    			if (icon != null) {
    				setText(logo);
    				setFont(list.getFont());
    			} else {
    				setmonText(logo + " (no image available)", list.getFont());
    			}
     
    			return this;
    		}
     
    		// Set the font and text when no image was found.
    		protected void setmonText(String monText, Font normalFont) {
    			if (monFont == null) { // lazily create this font
    				monFont = normalFont.deriveFont(Font.ITALIC);
    			}
    			setFont(monFont);
    			setText(monText);
    		}
    	}
    }
    en mettant des mouchards j'obtiens :
    valeur de str:Lille
    valeur de i:2
    valeur de getItem:0
    valeur de logo:Lille
    valeur de ind dans if:-1

    alors que la valeur de int dans le if devrait être de 3!
    cela veut donc dire que la ligne :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    if ((logo).compareTo(str[i]) == 0)
    				ind = i + 1;
    n'est pas éxecutée correctement alors que les deux chaines de caractères comparées sont identiques (ici "Lille")!! comment ça se fait??

  4. #4
    Membre chevronné Avatar de ngpub
    Profil pro
    Inscrit en
    Mai 2008
    Messages
    449
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2008
    Messages : 449
    Par défaut
    As-tu essayé comme ça :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    str[(Integer)e.getItem()].compareTo( str[i] )
    Si tu utilise Java 1.4 (j'ai vu ça "int selectedIndex = ((Integer) value).intValue();"); il faut écrire ça :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    str[ ((Integer)e.getItem()).intValue() ].compareTo( str[i] )

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

Discussions similaires

  1. Récupérer les valeurs d'un JComboBox
    Par Lukoda dans le forum AWT/Swing
    Réponses: 16
    Dernier message: 11/07/2012, 10h53
  2. Récupérer la valeur d'un JCombobox à partir d'une BD
    Par coolanso dans le forum Composants
    Réponses: 2
    Dernier message: 13/08/2010, 00h09
  3. Récupérer valeur d'un JComboBox
    Par Rastapwalu dans le forum AWT/Swing
    Réponses: 20
    Dernier message: 15/11/2007, 13h40
  4. comparer les valeurs d'un tableau
    Par nicerico dans le forum ASP
    Réponses: 4
    Dernier message: 19/08/2004, 11h20
  5. [RegEdit] comparer 2 valeurs
    Par Halleck dans le forum Windows
    Réponses: 2
    Dernier message: 15/03/2004, 21h51

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