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

Java Discussion :

Recupérer valeurs JList


Sujet :

Java

  1. #1
    Membre éclairé Avatar de pendoRa
    Homme Profil pro
    Ingénieur intégration
    Inscrit en
    Mai 2007
    Messages
    317
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur intégration
    Secteur : Industrie

    Informations forums :
    Inscription : Mai 2007
    Messages : 317
    Par défaut Recupérer valeurs JList
    Bonjour,
    je souhaite récuperer les valeurs d'une JList dans une même classe je suppose, or, je ne parviens pas à récuperer les valeurs correspondantes aux items d'une JList d'une autre classe ( que je souhaite placer par la suite dans un paramètre runtime.exec)

    J'ai codé ceci :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    radio = ListeEx.booklist.getSelectedValue();
    // ou bien
    radio = ListEx.booklist.getSelectedIndices();
    // ou bien encore
    radio = ListeEx.booklist.getModel().getElementAt(selected[i]);
    //sans succès




    Mon bout de code correspondant a la fonction runtime:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    try {
     
    						Runtime.getRuntime().exec(new String[] {chemin , radio} ); // je souhaite placer en 2eme paramètres (ici, "radio") la valeur choisi dans la JList!
    					} catch (IOException e) {
     
    						e.printStackTrace();
    					}
    et le code de la classe ou se situe ma JList :

    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
     public class ListEx extends JPanel { 
     
        	    /**
                     * 
                     */
    		private static final long serialVersionUID = 1L;
     
    			private BookEntry books[] = {
        	    		new BookEntry("Item 1", "shortIcon.jpg"),
        	    		new BookEntry("Item 2", "longIcon.jpg")
     
        	    };
     
        	    private JList booklist = new JList(books);
     
        	    public ListEx() {
        	    	setLayout(new BorderLayout());
        	    	JButton button = new JButton("Connect");
        	    	button.addActionListener(new PrintListener());
     
        	    	booklist = new JList(books);
        	    	booklist.setCellRenderer(new BookCellRenderer());
        	    	booklist.setVisibleRowCount(4);
        	    	JScrollPane panez = new JScrollPane(booklist);
     
        	    	add(panez, BorderLayout.NORTH);
        	    	add(button, BorderLayout.SOUTH);
     
        	    }
     
        	    class PrintListener implements ActionListener {
        	    	public void actionPerformed(ActionEvent e) {
        	    		int selected[] = booklist.getSelectedIndices();
        	    		System.out.println("Selected Elements :  ");
     
        	    		for (int f = 0; i < selected.length; i++) {
        	    			BookEntry element = (BookEntry) booklist.getModel().getElementAt(selected[i]);
        	    			System.out.println("   " + element.getTitle());
     
        	    			}
        	    		}
        	    	}
        	    }
     
        	    class BookEntry {
        	    	private final String title;
     
        	    	private final String imagePath;
     
        	    	private ImageIcon image;
     
        	    	public BookEntry(String title, String imagePath) {
        	    		this.title = title;
        	    		this.imagePath = imagePath;
     
        	    	}
     
    				public String getTitle() {
    					// TODO Auto-generated method stub
    					return title;
    				}
    				public ImageIcon getImage() {
    					if(image == null) {
    						image = new ImageIcon(imagePath);
    					}
     
        	    	return image;
        	    }
     
        	    public String toString() {
        	    	return title;
        	    }
        	}
     
        	@SuppressWarnings("serial")
    		static class BookCellRenderer extends JLabel implements ListCellRenderer {
     
        		private final Color HIGHLIGHT_COLOR = new Color(0, 0, 128);
     
        		public BookCellRenderer() {
        			setOpaque(true);
        			setIconTextGap(12);
        		}
     
        		public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        			BookEntry entry = (BookEntry) value;
        			setText(entry.getTitle());
        			setIcon(entry.getImage());
        			if(isSelected) {
        				setBackground(HIGHLIGHT_COLOR);
        				setForeground(Color.white);
        			} else {
        				setBackground(Color.white);
        				setForeground(Color.black);
        			}
        			return this;
        			}
    Merci a vous.

  2. #2
    Membre chevronné
    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    299
    Détails du profil
    Informations personnelles :
    Âge : 46
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Janvier 2009
    Messages : 299
    Par défaut
    ListeEx.booklist est private, il est donc normal de ne pas pouvoir y accéder depuis une autre class.
    Après le passer en public n'est pas forcement une bonne solution pour autant.
    Préfère l'utilisation de getter()/setter() pour accéder aux attributs de ton objet.
    Tu pourrais donc rajouter dans ta class ListEx une méthode :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    public BookEntry getSelectedBookEntry(){
      return (BookEntry)booklist.getSelectedValue();
    }

  3. #3
    Membre chevronné
    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    299
    Détails du profil
    Informations personnelles :
    Âge : 46
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Janvier 2009
    Messages : 299
    Par défaut
    Autre remarque en ce qui concerne "ListeEx.booklist", j'ai validé un peu vite.
    Ce n'est pas un attribut static, il faut donc passer par une instance pour pouvoir l'utiliser.

    Ex. :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    ListEx listex = new ListEx();
    //... ...
     
    String radio = listex.getSelectedBookEntry().toString();

  4. #4
    Membre éclairé Avatar de pendoRa
    Homme Profil pro
    Ingénieur intégration
    Inscrit en
    Mai 2007
    Messages
    317
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur intégration
    Secteur : Industrie

    Informations forums :
    Inscription : Mai 2007
    Messages : 317
    Par défaut
    Merci Caalador, j'ai donc créé une méthode ( identique à celle que tu m'a soumise) dans la Classe ListEx puis je l'ai appelé dans ma Classe principale..
    Ce qui donne
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    radio = ListEx.getSelectedBookEntry();
    J'ai donc placé un system.out.println(radio); pour voir ce qu'il récupère...
    (Remarque : Je souhaite récupérer une variable d'emplacement ou de type URL.)
    J'ai un retour "null" ...

  5. #5
    Membre chevronné
    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    299
    Détails du profil
    Informations personnelles :
    Âge : 46
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Janvier 2009
    Messages : 299
    Par défaut
    La réponse est dans la 2e réponse que j'ai donné un peu tardivement ^^

  6. #6
    Membre éclairé Avatar de pendoRa
    Homme Profil pro
    Ingénieur intégration
    Inscrit en
    Mai 2007
    Messages
    317
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur intégration
    Secteur : Industrie

    Informations forums :
    Inscription : Mai 2007
    Messages : 317
    Par défaut
    Oui j'ai remarqué, cependant j'ai toujours un retour null en procédant ainsi..

  7. #7
    Membre chevronné
    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    299
    Détails du profil
    Informations personnelles :
    Âge : 46
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Janvier 2009
    Messages : 299
    Par défaut
    Redonne le nouveau code que tu as, et la manière dont tu l'utilises.

  8. #8
    Membre éclairé Avatar de pendoRa
    Homme Profil pro
    Ingénieur intégration
    Inscrit en
    Mai 2007
    Messages
    317
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur intégration
    Secteur : Industrie

    Informations forums :
    Inscription : Mai 2007
    Messages : 317
    Par défaut
    Bonjour,

    voici la classe ListeRadio ( anciennement ListEx ).
    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
    import java.awt.BorderLayout;
     
     
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
     
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.ListCellRenderer;
    import javax.swing.text.html.parser.Element;
     
    public  class ListeRadio extends JPanel { 
     
     
    	int i=0; // 
    	// DECLARATION DES VARIABLES URL DES DIFFERENTES RADIOS
    	 String rmc = 		 ("C:\\Users\\pendoRa\\Music\\PTI\\rmc.mp3"); 
    	 String rfm =  		("C:\\Users\\pendoRa\\Music\\PTI\\rfm.mp3");
    	 String nrj =       ("C:\\Users\\pendoRa\\Music\\PTI\\nrj.mp3");
    	 String skyrock =  ("C:\\Users\\pendoRa\\Music\\PTI\\skyrock.mp3");
     
     
     
     
    		private static final long serialVersionUID = 1L;
     
    			public    BookEntry books[] = {
     
    					// ITEMS DE LA JLIST DES RADIOS AVEC LIENS DES ICONES CORRESPONDANTS 
    					// (INTITULE, ICONE, VARIABLE D'URL),
     
        	    		new BookEntry("NRJ", "image\\NRJ.jpg", nrj), 
        	    		new BookEntry("RMC", "image\\RMC.jpg", rmc),
    					new BookEntry("RFM", "image\\RFM.jpg", rfm),
    					new BookEntry("SKYROCK", "image\\SKYROCK.jpg", skyrock)
     
    			};
     
        	      JList booklist = new JList(books);
        	    public JButton button = new JButton("Connect");
     
     
        	    public ListeRadio() {
        	    	setLayout(new BorderLayout());
        	    	JButton button = new JButton("Connect");
     
     
        	    	booklist = new JList(books);
        	    	booklist.setCellRenderer(new BookCellRenderer());
        	    	booklist.setVisibleRowCount(4);
        	    	JScrollPane panez = new JScrollPane(booklist);
     
        	    	add(panez, BorderLayout.NORTH);
        	    	add(button, BorderLayout.SOUTH);
        	    	this.add(booklist);
        	    	booklist.setVisible(true);
     
        	    }
     
        	    public BookEntry getSelectedBookEntry() {
        			// TODO Auto-generated method stub
        			return (BookEntry) booklist.getSelectedValue();
        		}
     
     
        	  public class PrintListener implements ActionListener {
        	    	public void actionPerformed(ActionEvent e) {
        	    		int selected[] = booklist.getSelectedIndices();
        	    		System.out.println("Selected Elements   <> :  ");
     
        	    		for (int i = 0; i < selected.length; i++) {
        	    			BookEntry element = (BookEntry) booklist.getModel().getElementAt(selected[i]);
        	    			System.out.println("   " + element.string);
     
     
     
        	    				} 
        	    		}
     
     
        	    	}
     
        	    class BookEntry {
        	    	private final String title;
     
        	    	private final String imagePath;
     
        	    	private ImageIcon image;
     
    				private Object string;
     
    				// METHODE DE LA LISTE DES RADIO 
    				// NOM, LIEN DE L'ICONE, ET VARIABLE D'URL
     
        	    	public BookEntry(String title, String imagePath, String string) {
        	    		this.title = title;
        	    		this.imagePath = imagePath;
        	    		this.string = string;
     
        	    	}
     
    				public String getTitle() {
    					// TODO Auto-generated method stub
    					return title;
    				}
     
    				public ImageIcon getImage() {
    					if(image == null) {
    						image = new ImageIcon(imagePath);
    					}
     
        	    	return image;
        	    }
    				public String string() {
     
     
    					return null;
     
    				} 
     
        	}
     
     
    }
    Et dans ma classe principale, j'ai codé ceci :

    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
    public class FenetrePrincipale extends JFrame
     
        implements ActionListener, MouseListener
    {
     
    	/**
             * 
             */
    	private static final long serialVersionUID = 1L;
     
     
    ListeRadio RadioL = new ListeRadio(); 
     
     
     
     
    	public static void main(String argc []) {
     
    		new FenetrePrincipale();
     
    				}
     
    // ...
    String radio;
    public FenetrePrinicpale() {
    // ...
     
     
              radio = RadioL.getSelectedBookEntry().toString();
    Et si je met un bouton de Test, avec un system.out.println(RadioL.getSelectedBookEntry().toString());

    J'ai en retour console : "ListeRadio$BookEntry@c378f6" et il differe a propre à chaque item.

  9. #9
    Membre chevronné
    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    299
    Détails du profil
    Informations personnelles :
    Âge : 46
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Janvier 2009
    Messages : 299
    Par défaut
    C'est donc pas null.
    Il faut que tu redéfinisses toString() pour qu'il t'affiche ce que tu souhaites.

  10. #10
    Membre éclairé Avatar de pendoRa
    Homme Profil pro
    Ingénieur intégration
    Inscrit en
    Mai 2007
    Messages
    317
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur intégration
    Secteur : Industrie

    Informations forums :
    Inscription : Mai 2007
    Messages : 317
    Par défaut
    Bonjour,
    mais redéfinir toString() en quoi, je ne vois pas comment faire pour récupérer mes url...
    Merci.

  11. #11
    Membre Expert
    Inscrit en
    Mai 2006
    Messages
    1 364
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 1 364
    Par défaut
    Si ta liste renvoie un "ListeRadio$BookEntry" ca veut dire qu'elle te renvoie un objet "BookEntry".

    Donc si tu veux recuperer l'URL, tu peux redefinir la methode toString de la classe BookEntry pour qu'elle te renvoie
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    public String toString()
    {
    return this.string;
    }
    a+

  12. #12
    Membre éclairé Avatar de pendoRa
    Homme Profil pro
    Ingénieur intégration
    Inscrit en
    Mai 2007
    Messages
    317
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur intégration
    Secteur : Industrie

    Informations forums :
    Inscription : Mai 2007
    Messages : 317
    Par défaut
    Je n'ai pas de classe BookEntry seulement une méthode.

    Et si je code
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    public (BookEntry) getSelectedBookEntry() {
    return (BookEntry) booklist.getSelectedValue();
    }
    public String toString();
    {
    return.this.string;
    }
    J'ai toujours un ListeRadio@BookEntry@....

    A vrai dire je ne comprend pas pourquoi je n'arrive pas à simplement récupérer les valueurs des items correspondant dans la JList.
    ps : Le code n'a pa bouger.

  13. #13
    Membre Expert
    Inscrit en
    Mai 2006
    Messages
    1 364
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 1 364
    Par défaut
    Citation Envoyé par pendoRa Voir le message
    Je n'ai pas de classe BookEntry seulement une méthode.
    Non, tu as bien une sous classe BookEntry. Elle est la, avec la methode à ajouter :
    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
    class BookEntry {
        	    	private final String title;
     
        	    	private final String imagePath;
     
        	    	private ImageIcon image;
     
    				private Object string;
     
    				// METHODE DE LA LISTE DES RADIO 
    				// NOM, LIEN DE L'ICONE, ET VARIABLE D'URL
     
        	    	public BookEntry(String title, String imagePath, String string) {
        	    		this.title = title;
        	    		this.imagePath = imagePath;
        	    		this.string = string;
     
        	    	}
     
    				public String getTitle() {
    					// TODO Auto-generated method stub
    					return title;
    				}
     
    				public ImageIcon getImage() {
    					if(image == null) {
    						image = new ImageIcon(imagePath);
    					}
     
        	    	return image;
        	    }
    				public String toString() {
     
     
    					return this.string;
     
    				} 
     
        	}

  14. #14
    Membre éclairé Avatar de pendoRa
    Homme Profil pro
    Ingénieur intégration
    Inscrit en
    Mai 2007
    Messages
    317
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur intégration
    Secteur : Industrie

    Informations forums :
    Inscription : Mai 2007
    Messages : 317
    Par défaut
    Merci a toi, oui désolé je commence à aoir les yeux fatigué.

    Donc oui j'ai placé la méthode toString() dans la classe BookEntry.
    Ensuite j'ai fait un bouton de test avec un
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    system.out.println(RadioL.booklist.getSelectedValue().toString());
    dans ma classe principale et il m'affiche bien la valeur correspondant à l'item choisi dans la list !
    Mille merci, bonne journée.

    ps : Je reviendrai surement plus tard, car je souhaite que la JList aille chercher la valeur de ses items dans un fichier XML ! ( pour un système de MAJ ).

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

Discussions similaires

  1. recupérer valeur checkbox
    Par Emcy dans le forum Général JavaScript
    Réponses: 11
    Dernier message: 15/09/2009, 15h13
  2. Recupération valeur JList
    Par pierrot2908 dans le forum Composants
    Réponses: 1
    Dernier message: 14/05/2007, 10h31
  3. Réponses: 4
    Dernier message: 11/04/2007, 16h03
  4. recupérer valeur de checkbox
    Par Emcy dans le forum Général JavaScript
    Réponses: 16
    Dernier message: 06/02/2007, 11h00
  5. recupérer valeur de champs
    Par Echizen1 dans le forum Access
    Réponses: 14
    Dernier message: 14/09/2006, 20h24

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