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 :

[debutant]getListCellRendererComponent appelé sans raison


Sujet :

AWT/Swing Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé Avatar de Romain93
    Inscrit en
    Septembre 2005
    Messages
    71
    Détails du profil
    Informations forums :
    Inscription : Septembre 2005
    Messages : 71
    Par défaut [debutant]getListCellRendererComponent appelé sans raison
    Bonjour,

    Bon, mon programme de depart etait assez gros, et je l'ai reduit au minimum pour cerner le probleme. Donc forcement, ca ressemble plus a grand chose, soyez indulgent

    J'ai deux RadioButtons "Flight" et "Train", et un JCombobox Company, avec soit {"air france", ...} soit {"sncf", ...} selon le RadioButton selectionne.

    J'ai aussi trois boutons add, remove, et change, et une JList. En cliquant sur Add, la chaine "Flight AirFrance" est ajoute dans la JList.

    Lorsqu'on selectionne une ligne de la JList, le RadioButton "Flight" ou "Train" est selectionne, selon la nature de la ligne.

    J'ai dans ma classe une classe MyCellRenderer qui implemente ListCellRenderer. Dans le programme tel quel elle ne sert a rien puisque je ne fais qu'afficher un string dans la JList, mais mes objets au depart etaient plus complexes.

    Le probleme est que quand on a ajoute une ligne, si l'on clique sur le RadioButton qui n'est pas selectionne, la methode getListCellRendererComponent est appelee, et donc l'autre bouton est selectionne. Le mieux est d'essayer pour comprendre...

    Voila le code:

    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
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
     
    public class test4 extends JPanel implements ListSelectionListener {
     
    	int compteur = 0;
     
    	private DefaultListModel trip;
    	private JList list;
     
    	private JButton addButton;
    	private JButton changeButton;
    	private JButton removeButton;
     
    	private static final String[] flightCompanyStrings = {"Air France", "Lufthansa", "US Airways"};
    	private static final String[] trainCompanyStrings = {"Amtrak", "SNCF", "Tshoo railways"};
     
    	private static final String flightString = "Flight";
    	private static final String trainString = "Train";
    	private static final String addString = "Add";
    	private static final String changeString = "Change";
    	private static final String removeString = "Remove";
    	private static final String companyString = "Company: ";
     
    	private JComboBox companyBox;
     
    	private JRadioButton flightRadioButton;
    	private JRadioButton trainRadioButton;
     
     
    	public test4() {
     
            super(new BorderLayout());        
     
    	    trip = new DefaultListModel();
     
    	    //Create the list and put it in a scroll pane.
    	    list = new JList(trip);
    	    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    	    //list.setSelectedIndex(-1);
    	    list.addListSelectionListener(this);
    	    list.setVisibleRowCount(5);
    	    list.setCellRenderer(new MyCellRenderer());
    	    JScrollPane listScrollPane = new JScrollPane(list);
     
    	    JPanel listActions = new JPanel();
    	    listActions.add(getActions(), BorderLayout.CENTER);
    	    listActions.add(listScrollPane, BorderLayout.NORTH);
     
    	    add(listActions, BorderLayout.CENTER);
    	}
     
    	private JPanel getActions() {
    		JPanel actions = new JPanel(new BorderLayout());
    		actions.add(getChoice(), BorderLayout.WEST);
    		actions.add(getFields(), BorderLayout.CENTER);
    		actions.add(getButtons(), BorderLayout.EAST);
    		return actions;
    	}
     
    	private JPanel getChoice() {
    		JPanel choice = new JPanel();
     
    		choice.setLayout(new BoxLayout(choice, BoxLayout.Y_AXIS));
     
    		flightRadioButton = new JRadioButton (flightString);
    		trainRadioButton = new JRadioButton (trainString);
     
    		flightRadioButton.addActionListener(new FlightActionListener());
    		trainRadioButton.addActionListener(new TrainActionListener());
     
    		ButtonGroup group = new ButtonGroup();
    		group.add(flightRadioButton);
    		group.add(trainRadioButton);
     
    		choice.add(flightRadioButton);
    		choice.add(trainRadioButton);
     
    		return choice;
    	}
     
     
    	class FlightActionListener implements ActionListener {
    		public void actionPerformed(ActionEvent arg0) {
    			compteur++; System.out.println(compteur + "entree actionperformed bouton flight");
     
    			companyBox.removeAllItems();
    			for (String company:flightCompanyStrings)
    				companyBox.addItem(company);
     
    			compteur++; System.out.println(compteur + "sortie actionperformed bouton flight");
    		}
    	}
     
    	class TrainActionListener implements ActionListener {
    		public void actionPerformed(ActionEvent arg0) {
    			compteur++; System.out.println(compteur + "entree actionperformed bouton train");
     
    			companyBox.removeAllItems();
    			for (String company:trainCompanyStrings)
    				companyBox.addItem(company);
     
    			compteur++; System.out.println(compteur + "sortie actionperformed bouton train");
    		}
    	}
     
    	private JPanel getFields() {
    		JPanel fields = new JPanel ();
    		fields.add(getCompany());
    		return fields;
    	}
     
     
    	private JPanel getCompany() {
    		JPanel company = new JPanel(new FlowLayout());
    		company.add(new JLabel(companyString));
    		companyBox = new JComboBox();
    		company.add(companyBox);
    		return company;
    	}
     
     
    	private JPanel getButtons() {
    		JPanel buttons = new JPanel();
     
    		addButton = new JButton(addString);
    		removeButton = new JButton(removeString);
    		changeButton = new JButton(changeString);
     
    		removeButton.addActionListener(new RemoveListener ());
    		changeButton.addActionListener(new ChangeListener());
    		addButton.addActionListener(new AddListener());
     
    		buttons.setLayout(new BoxLayout(buttons, BoxLayout.Y_AXIS));
    		buttons.add(removeButton);
    		buttons.add(changeButton);
    		buttons.add(addButton);
     
    		removeButton.setEnabled(false);
    		changeButton.setEnabled(false);
     
    		return buttons;
    	}
     
        class RemoveListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                //This method can be called only if
                //there's a valid selection
                int index = list.getSelectedIndex();
                trip.remove(index);
     
                int size = trip.getSize();
     
                if (size == 0) { //Nothing's left, disable removing
                    removeButton.setEnabled(false);
                } else { //Select an index.
                    if (index == trip.getSize()) {
                        //removed item in last position
                        index--;
                    }
     
                    list.setSelectedIndex(index);
                    list.ensureIndexIsVisible(index);
                }
            }
        }
     
        class ChangeListener implements ActionListener {
    		public void actionPerformed(ActionEvent e) {
     
                //This method can be called only if
                //there's a valid selection
            	int index=list.getSelectedIndex();
     
    	        if (flightRadioButton.isSelected())
    	        	trip.setElementAt("Flight" + (String) companyBox.getSelectedItem(), index);
     
    	        if (trainRadioButton.isSelected())
    	        	trip.setElementAt("Train" + (String) companyBox.getSelectedItem(), index);
     
            	list.setModel(trip);
                list.setSelectedIndex(index);
                list.ensureIndexIsVisible(index);
            }
        }
     
        class AddListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
     
                int index = list.getSelectedIndex(); //get selected index
                if (index == -1) { //no selection, so insert at beginning
                    index = 0;
                } else {           //add after the selected item
                    index++;
                }
     
    		    if (flightRadioButton.isSelected())
    		       	trip.insertElementAt("Flight" + (String) companyBox.getSelectedItem(), index);
     
    		    if (trainRadioButton.isSelected())
    		       	trip.insertElementAt("Train" + (String) companyBox.getSelectedItem(), index);
     
     
    	        if (!(flightRadioButton.isSelected() || trainRadioButton.isSelected()))         
                   	JOptionPane.showMessageDialog(null,"Select one radio button between Flight, Train and Car.");
     
     
     
                //Select the new segment and make it visible.
                list.setSelectedIndex(index);
                list.ensureIndexIsVisible(index);
            }
        }
     
        private void fillFields(int index) {
     
    		compteur++; System.out.println(compteur + "entree fillFields");
     
        	String segment = (String) trip.get(index);
        	char first = segment.charAt(0);
     
        	if (first=='F') {
        			flightRadioButton.setVisible(false);
        			flightRadioButton.doClick();
        			flightRadioButton.setVisible(true);
        	} 
     
        	if (first=='T') {
        			trainRadioButton.setVisible(false);
        			trainRadioButton.doClick();
        			trainRadioButton.setVisible(true);
        	} 
     
    		compteur++; System.out.println(compteur + "sortie fillFields");
        }
     
    	class MyCellRenderer extends JLabel implements ListCellRenderer {
     
    		public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) {
    			compteur++; System.out.println(compteur + "entree getListCellRendererComponent");
     
    			setText((String)value);
    		   	if (isSelected) {
    		   		setBackground(list.getSelectionBackground());
    			    setForeground(list.getSelectionForeground());
    			    fillFields(index);
    			} else {
    			    setBackground(list.getBackground());
    			    setForeground(list.getForeground());
    			   }
    			setEnabled(list.isEnabled());
    			setFont(list.getFont());
    			setOpaque(true);
    			compteur++; System.out.println(compteur + "sortie getListCellRendererComponent");
    			return this;
    		}
     
    	}
     
    	public void valueChanged(ListSelectionEvent e) {
    		compteur++; System.out.println(compteur + "entree valueChanged");
     
            if (e.getValueIsAdjusting() == false) {
                if (list.getSelectedIndex() == -1) {
                //No selection, disable fire button.
                    removeButton.setEnabled(false);
                    changeButton.setEnabled(false);
                } else {
                //Selection, enable the fire button.
                    removeButton.setEnabled(true);
                    changeButton.setEnabled(true);
                }
            }
     
    		compteur++; System.out.println(compteur + "sortie valueChanged");
    	}
     
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("TripTracker");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            //Create and set up the content pane.
            JComponent newContentPane = new test4();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
     
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        }
     
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
     
        }
     
    }
    Vous vous demanderez peut-etre a quoi sert le JPanel listActions: en fait si on l'enleve, le probleme disparait, mais si je l'enleve dans mon programme complet, le probleme est toujours la, donc je prefererais trouver le probleme avec.

    Pour ceux qui n'ont rien d'autre a faire, voila le programme complet:

    http://www.send-large-file.com/credi...a8e0f61b1444ab

    Le comportement est encore plus erratique avec le programme complet: il n'apparait qu'au bout de la troisieme ligne, et se produit non pas quand un RadioButton est selectionne, mais la JComboBox company... alors qu'il y a trois autres JComboBox qui fonctionnent parfaitement!

    Enfin voila, merci d'avance si vous avez le courage de regarder ca. C'est peut-etre juste un truc tout bete que je n'ai pas compris sur la methode getListCellRendererComponent: je croyais qu'elle n'etait appelee que lorsqu'une ligne de la JList etait selectionnee...

    Merci d'avance,

    Romain

  2. #2
    Membre Expert
    Avatar de xavlours
    Inscrit en
    Février 2004
    Messages
    1 832
    Détails du profil
    Informations forums :
    Inscription : Février 2004
    Messages : 1 832
    Par défaut
    Bonjour,

    pourquoi appelles-tu la méthode fillFields dans le Renderer ? C'est à mon avis ça qui fait tout partir en vrille. J'ai tenté de la commenter et c'est de suite plus stable (dans le code allégé)

    Si tu cherches une méthode à exécuter à chaque fois que la sélection de la JList change, utilise un ListSelectionListener. Le ListCellRenderer ne doit s'occuper QUE de l'affichage, jamais de changer l'état d'autres composants de ton application.
    "Le bon ni le mauvais ne me feraient de peine si si si je savais que j'en aurais l'étrenne." B.V.
    Non au langage SMS ! Je ne répondrai pas aux questions techniques par MP.
    Eclipse : News, FAQ, Cours, Livres, Blogs.Et moi.

  3. #3
    Membre confirmé Avatar de Romain93
    Inscrit en
    Septembre 2005
    Messages
    71
    Détails du profil
    Informations forums :
    Inscription : Septembre 2005
    Messages : 71
    Par défaut
    ouaip, c'etait bien ca! c'est ma premiere JList j'avais mis ca sans trop reflechir

    Merci!

  4. #4
    Membre Expert
    Avatar de xavlours
    Inscrit en
    Février 2004
    Messages
    1 832
    Détails du profil
    Informations forums :
    Inscription : Février 2004
    Messages : 1 832
    Par défaut
    Citation Envoyé par Romain93
    c'est ma premiere JList
    Eh beh, c'est un peu costaud pour un Hello world
    "Le bon ni le mauvais ne me feraient de peine si si si je savais que j'en aurais l'étrenne." B.V.
    Non au langage SMS ! Je ne répondrai pas aux questions techniques par MP.
    Eclipse : News, FAQ, Cours, Livres, Blogs.Et moi.

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

Discussions similaires

  1. [XL-2003] exécution d'une macro qui appel un autre classeur sans raisons
    Par fllyann dans le forum Macros et VBA Excel
    Réponses: 4
    Dernier message: 28/03/2011, 10h38
  2. [C#][debutant] tableau String sans donner la taille ?
    Par Sylk dans le forum Windows Forms
    Réponses: 4
    Dernier message: 29/11/2005, 20h42
  3. NET::FTP unknown error sans raison
    Par niocco dans le forum Modules
    Réponses: 11
    Dernier message: 29/06/2005, 20h21
  4. ma base gonfle sans raison !!!
    Par hiul dragonfel dans le forum Access
    Réponses: 6
    Dernier message: 20/06/2005, 10h00
  5. [Debutant(e)]Appel d'une servlet dans une page jsp
    Par kouadjalain dans le forum Servlets/JSP
    Réponses: 5
    Dernier message: 20/07/2004, 15h02

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