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 :

événements lors d'un changement de panel CardLayout


Sujet :

Agents de placement/Fenêtres Java

  1. #1
    Candidat au Club
    Profil pro
    Inscrit en
    Mars 2009
    Messages
    7
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2009
    Messages : 7
    Points : 2
    Points
    2
    Par défaut événements lors d'un changement de panel CardLayout
    bonjour,
    j'ai quelque problèmes de mise a jour de champs en utilisant un cardlayout.
    pour faire simple :
    j'ai créé un cardlayout avec deux panels,
    dans chacun des panels j'ai un label "date"
    je souhaite mettre a jour ce label avec l'heure actuelle lors du changement de panel.
    y a t il un événement a intercepter? j'ai fait de multiple recherches sans trouver de réponse.
    merci pour votre aide
    Ray

  2. #2
    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 : 54
    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
    Points : 29 131
    Points
    29 131
    Billets dans le blog
    2
    Par défaut
    Salut,

    Il y a bien un ComponentListener/ComponentAdapter qui te permettrait d'être averti lorsque l'un des composants passe visible, mais il faudra enregistrer le listener sur l'ensemble des composants. Pourquoi ne pas simplement le faire dans la méthode qui sélectionne le composant visible.

    Par appel de méthode :
    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
    public class CardLayoutChangeByMethod {
     
    	private static final Color[] COLORS = {Color.ORANGE, Color.GREEN, Color.YELLOW, Color.CYAN};
     
    	public static void main(String[] args) {
     
    		JFrame frame = new JFrame("Demo");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		CardLayout cardLayout = new CardLayout();
    		JPanel mainPanel = new JPanel(cardLayout);
     
    		for(Color color : COLORS) {
    			JPanel cardPanel = new JPanel();
    			cardPanel.setBackground(color);
    			mainPanel.add(cardPanel);
    		}
     
    		JLabel timeLabel = new JLabel(getTime());
     
    		JButton button = new JButton("Change");
    		button.addActionListener(e-> change(mainPanel, cardLayout, timeLabel));
    		JPanel southPanel = new JPanel();
    		southPanel.add(button);
    		southPanel.add(timeLabel);
     
    		frame.add(mainPanel);
    		frame.add(southPanel, BorderLayout.SOUTH);
     
    		frame.setSize(400, 400);
    		frame.setLocationRelativeTo(null);
    		frame.setVisible(true);
     
    	}
     
    	private static void change(JPanel container, CardLayout cardLayout, JLabel timeLabel) {
    		cardLayout.next(container);
    		timeLabel.setText(getTime());
    	}
     
    	private static String getTime() {
    		return DateTimeFormatter.ofPattern("hh:mm:ss").format(LocalDateTime.now());
    	}
     
    }
    Par écouteur :
    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
    public class CardLayoutChangeByListener {
     
    	private static final Color[] COLORS = {Color.ORANGE, Color.GREEN, Color.YELLOW, Color.CYAN};
     
    	public static void main(String[] args) {
     
    		JFrame frame = new JFrame("Demo");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		CardLayout cardLayout = new CardLayout();
    		JPanel mainPanel = new JPanel(cardLayout);
     
     
    		JLabel timeLabel = new JLabel(getTime());
    		ComponentAdapter componentAdapter = new ComponentAdapter() {
    			@Override
    			public void componentShown(ComponentEvent arg0) {
    				timeLabel.setText(getTime());
    			}
    		};
    		for(Color color : COLORS) {
    			JPanel cardPanel = new JPanel();
    			cardPanel.setBackground(color);
    			cardPanel.addComponentListener(componentAdapter);
    			mainPanel.add(cardPanel);
    		}
     
    		JButton button = new JButton("Change");
    		button.addActionListener(e-> cardLayout.next(mainPanel));
    		JPanel southPanel = new JPanel();
    		southPanel.add(button);
    		southPanel.add(timeLabel);
     
    		frame.add(mainPanel);
    		frame.add(southPanel, BorderLayout.SOUTH);
     
    		frame.setSize(400, 400);
    		frame.setLocationRelativeTo(null);
    		frame.setVisible(true);
     
    	} 
     
    	private static String getTime() {
    		return DateTimeFormatter.ofPattern("hh:mm:ss").format(LocalDateTime.now());
    	}
     
    }
    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.

  3. #3
    Candidat au Club
    Profil pro
    Inscrit en
    Mars 2009
    Messages
    7
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2009
    Messages : 7
    Points : 2
    Points
    2
    Par défaut
    merci pour ta réponse, en fait je cherche a mettre à jour un label date qui se trouve dans chaque cardPanel (au final l'application doit mettre a jour une table, j'ai pris l'exemple de la date pour simplifier) et non pas celui ou il y a le bouton.
    désolé pour ne pas avoir été précis
    Ray

  4. #4
    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 : 54
    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
    Points : 29 131
    Points
    29 131
    Billets dans le blog
    2
    Par défaut
    Peu import où se trouve le label, et ce qu'on y met, c'est toujours le même principe de base. Ce qui peut changer c'est la façon d'obtenir le label. On peut procéder par analyse du composant (inspection), mais ça peut poser certains problèmes pour récupérer le bon label, surtout s'il y en a plusieurs. Le plus simple étant de faire un JPanel spécialisé ou une petite classe de description (un wrapper qui contient la référence du panel et la référence du label associé (c'est lui qui écoutera avec le ComponentAdapter)).

    Par classe spécialisée :

    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
    public class CardLayoutChangeByMethodByInspection {
     
    	private static final Color[] COLORS = {Color.ORANGE, Color.GREEN, Color.YELLOW, Color.CYAN};
    	private static final String TIME_LABEL_COMPONENT = "timelabel";
     
    	public static void main(String[] args) {
     
    		JFrame frame = new JFrame("Demo");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		CardLayout cardLayout = new CardLayout();
    		JPanel mainPanel = new JPanel(cardLayout);
     
     
    		ComponentAdapter componentAdapter = new ComponentAdapter() {
    			@Override
    			public void componentShown(ComponentEvent arg0) {
    				setTime((JPanel)arg0.getComponent());
    			}
    		};
    		for(Color color : COLORS) {
    			JPanel cardPanel = createJPanel(getName(color));
    			cardPanel.setBackground(color);
    			cardPanel.addComponentListener(componentAdapter);
    			mainPanel.add(cardPanel);
    		}
     
    		JButton button = new JButton("Change");
    		button.addActionListener(e-> cardLayout.next(mainPanel));
    		JPanel southPanel = new JPanel();
    		southPanel.add(button); 
     
    		frame.add(mainPanel);
    		frame.add(southPanel, BorderLayout.SOUTH);
     
    		frame.addWindowListener(new WindowAdapter() {
    			public void windowOpened(java.awt.event.WindowEvent e) {
    				setTime(getVisible(mainPanel));
    			}
    			public void windowClosing(java.awt.event.WindowEvent e) {
    				for(Component component : mainPanel.getComponents()) {
    					if ( component instanceof JPanel ) {
    						JPanel panel = (JPanel)component;
    						String time = getTime(panel);
    						if ( time.isEmpty() ) {
    							time = "jamais affiché";
    						}
    						System.out.println("Heure du panneau " + getName(panel.getBackground()).toLowerCase() + " : " + time);
    					}
    				}
    			}
    		});
     
    		frame.setSize(400, 400);
    		frame.setLocationRelativeTo(null);
    		frame.setVisible(true);
     
    	} 
     
    	protected static JPanel getVisible(JPanel panel) {
    		for(Component component : panel.getComponents()) {
    			if ( component instanceof JPanel && component.isVisible() ) {
    				 return (JPanel)component; 
    			}
    		}
    		return null;
    	}
     
    	protected static String getTime(JPanel panel) {
    		if ( panel instanceof JPanelTime ) {
    			JPanelTime ptime = (JPanelTime)panel;
    			return ptime.getPanelTime();
    		}
    		return null;
    	}
     
    	protected static void setTime(JPanel panel) {
    		if ( panel instanceof JPanelTime ) {
    			JPanelTime ptime = (JPanelTime)panel;
    			ptime.updatePanelTime();
    		}
    	}
     
    	private static String getName(Color color) {
    		for(Field field : Color.class.getFields()) {
    			try {
    				if ( color==field.get(null) ) {
    					return field.getName();
    				}
    			} catch (IllegalArgumentException | IllegalAccessException e) { 
    			}
    		}
    		return "?";
    	}
     
    	private static String getTime() {
    		return DateTimeFormatter.ofPattern("hh:mm:ss").format(LocalDateTime.now());
    	}
    	private static JPanelTime createJPanel(String texte) {
    		return new JPanelTime(texte);
    	}
     
    	public static class JPanelTime extends JPanel {
     
    		private final JLabel timeLabel;
     
    		public JPanelTime(String texte) {
    			super(new BorderLayout());
    			timeLabel = new JLabel(); // le label qui va afficher l'heure
    			timeLabel.setHorizontalAlignment(JLabel.CENTER);
    			timeLabel.setName(TIME_LABEL_COMPONENT);
    			add(timeLabel, BorderLayout.NORTH);
    			JLabel label2 = new JLabel(texte); // un autre label
    			label2.setHorizontalAlignment(JLabel.CENTER);
    			add(label2, BorderLayout.SOUTH);
    		}
     
    		public void updatePanelTime() {
    			timeLabel.setText(getTime());
    		}
     
    		public String getPanelTime() {
    			return timeLabel.getText();
    		}
     
    	}
     
    }
    par classe de description :
    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
    public class CardLayoutChangeByMethodByInspection {
     
    	private static final Color[] COLORS = {Color.ORANGE, Color.GREEN, Color.YELLOW, Color.CYAN};
    	private static final String TIME_LABEL_COMPONENT = "timelabel";
     
    	public static void main(String[] args) {
     
    		JFrame frame = new JFrame("Demo");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		CardLayout cardLayout = new CardLayout();
    		JPanel mainPanel = new JPanel(cardLayout);
     
    		Map<JPanel, Description> map = new HashMap<>();
    		ComponentAdapter componentAdapter = new ComponentAdapter() {
    			@Override
    			public void componentShown(ComponentEvent arg0) {
    				map.get(arg0.getComponent()).updatePanelTime();
    			}
    		};
    		for(Color color : COLORS) {
    			Description cardPanel = createJPanel(getName(color));
    			cardPanel.getPanel().setBackground(color);
    			cardPanel.getPanel().addComponentListener(componentAdapter);
    			mainPanel.add(cardPanel.getPanel());
    			map.put(cardPanel.getPanel(), cardPanel);
    		}
     
    		JButton button = new JButton("Change");
    		button.addActionListener(e-> cardLayout.next(mainPanel));
    		JPanel southPanel = new JPanel();
    		southPanel.add(button); 
     
    		frame.add(mainPanel);
    		frame.add(southPanel, BorderLayout.SOUTH);
     
    		frame.addWindowListener(new WindowAdapter() {
    			public void windowOpened(java.awt.event.WindowEvent e) {
    				map.get(getVisible(mainPanel)).updatePanelTime();;
    			}
    			public void windowClosing(java.awt.event.WindowEvent e) {
    				for(Component component : mainPanel.getComponents()) {
    					if ( component instanceof JPanel ) {
    						JPanel panel = (JPanel)component;
    						String time = map.get(panel).getPanelTime();
    						if ( time.isEmpty() ) {
    							time = "jamais affiché";
    						}
    						System.out.println("Heure du panneau " + getName(panel.getBackground()).toLowerCase() + " : " + time);
    					}
    				}
    			}
    		});
     
    		frame.setSize(400, 400);
    		frame.setLocationRelativeTo(null);
    		frame.setVisible(true);
     
    	} 
     
    	protected static JPanel getVisible(JPanel panel) {
    		for(Component component : panel.getComponents()) {
    			if ( component instanceof JPanel && component.isVisible() ) {
    				 return (JPanel)component; 
    			}
    		}
    		return null;
    	} 
     
    	private static String getName(Color color) {
    		for(Field field : Color.class.getFields()) {
    			try {
    				if ( color==field.get(null) ) {
    					return field.getName();
    				}
    			} catch (IllegalArgumentException | IllegalAccessException e) { 
    			}
    		}
    		return "?";
    	}
     
    	private static String getTime() {
    		return DateTimeFormatter.ofPattern("hh:mm:ss").format(LocalDateTime.now());
    	}
    	private static Description createJPanel(String texte) {
    		return new Description(texte);
    	}
     
    	public static class Description {
     
    		private final JLabel timeLabel;
    		private final JPanel panel;
     
    		public Description(String texte) {
    			panel = new JPanel(new BorderLayout());
    			timeLabel = new JLabel(); // le label qui va afficher l'heure
    			timeLabel.setHorizontalAlignment(JLabel.CENTER);
    			timeLabel.setName(TIME_LABEL_COMPONENT);
    			panel.add(timeLabel, BorderLayout.NORTH);
    			JLabel label2 = new JLabel(texte); // un autre label
    			label2.setHorizontalAlignment(JLabel.CENTER);
    			panel.add(label2, BorderLayout.SOUTH);
    		}
     
    		public JPanel getPanel() {
    			return panel;
    		}
     
    		public void updatePanelTime() {
    			timeLabel.setText(getTime());
    		}
     
    		public String getPanelTime() {
    			return timeLabel.getText();
    		}
     
    	}
    Par inspection :
    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
    public class CardLayoutChangeByMethodByInspection {
     
    	private static final Color[] COLORS = {Color.ORANGE, Color.GREEN, Color.YELLOW, Color.CYAN};
    	private static final String TIME_LABEL_COMPONENT = "timelabel";
     
    	public static void main(String[] args) {
     
    		JFrame frame = new JFrame("Demo");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		CardLayout cardLayout = new CardLayout();
    		JPanel mainPanel = new JPanel(cardLayout);
     
     
    		ComponentAdapter componentAdapter = new ComponentAdapter() {
    			@Override
    			public void componentShown(ComponentEvent arg0) {
    				displayTimeInPanel((JPanel)arg0.getComponent());
    			}
    		};
    		for(Color color : COLORS) {
    			JPanel cardPanel = createJPanel(getName(color));
    			cardPanel.setBackground(color);
    			cardPanel.addComponentListener(componentAdapter);
    			mainPanel.add(cardPanel);
    		}
     
    		JButton button = new JButton("Change");
    		button.addActionListener(e-> cardLayout.next(mainPanel));
    		JPanel southPanel = new JPanel();
    		southPanel.add(button); 
     
    		frame.add(mainPanel);
    		frame.add(southPanel, BorderLayout.SOUTH);
     
    		frame.addWindowListener(new WindowAdapter() {
    			public void windowOpened(java.awt.event.WindowEvent e) {
    				getTimeLabel(getVisible(mainPanel)).setText(getTime());
    			}
    			public void windowClosing(java.awt.event.WindowEvent e) {
    				for(Component component : mainPanel.getComponents()) {
    					if ( component instanceof JPanel ) {
    						JPanel panel = (JPanel)component;
    						String time = getTimeLabel(panel).getText();
    						if ( time.isEmpty() ) {
    							time = "jamais affiché";
    						}
    						System.out.println("Heure du panneau " + getName(panel.getBackground()).toLowerCase() + " : " + time);
    					}
    				}
    			}
    		});
     
    		frame.setSize(400, 400);
    		frame.setLocationRelativeTo(null);
    		frame.setVisible(true);
     
    	} 
     
    	protected static JPanel getVisible(JPanel panel) {
    		for(Component component : panel.getComponents()) {
    			if ( component instanceof JPanel && component.isVisible() ) {
    				 return (JPanel)component; 
    			}
    		}
    		return null;
    	}
     
    	protected static JLabel getTimeLabel(JPanel panel) {
    		for(Component component : panel.getComponents()) {
    			if ( component instanceof JLabel && TIME_LABEL_COMPONENT.equals(component.getName()) ) {
    				 return (JLabel)component; 
    			}
    		}
    		return null;
    	}
     
    	protected static void displayTimeInPanel(JPanel panel) {
    		getTimeLabel(panel).setText(getTime());
    	}
     
    	private static String getName(Color color) {
    		for(Field field : Color.class.getFields()) {
    			try {
    				if ( color==field.get(null) ) {
    					return field.getName();
    				}
    			} catch (IllegalArgumentException | IllegalAccessException e) { 
    			}
    		}
    		return "?";
    	}
     
    	private static String getTime() {
    		return DateTimeFormatter.ofPattern("hh:mm:ss").format(LocalDateTime.now());
    	}
    	private static JPanel createJPanel(String texte) {
    		JPanel panel = new JPanel(new BorderLayout());
    		JLabel label1 = new JLabel(); // le label qui va afficher l'heure
    		label1.setHorizontalAlignment(JLabel.CENTER);
    		label1.setName(TIME_LABEL_COMPONENT);
    		panel.add(label1, BorderLayout.NORTH);
    		JLabel label2 = new JLabel(texte); // un autre label
    		label2.setHorizontalAlignment(JLabel.CENTER);
    		panel.add(label2, BorderLayout.SOUTH);
    		return panel;
    	}
    }
    Il y a également la soluton MVC : la classe de Description est le modèle, et le JPanel/JLabel écoute les modifications du modèle. Par écouteur (en utilisant SwingPropertyChangeSupport pour gérer ça). On ne modifie plus le JLabel directement, on modifie le modèle et le JLabel se met à jour sur réception de l'évenement.

    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
    public class CardLayoutChangeByMethodByInspection {
     
    	private static final Color[] COLORS = {Color.ORANGE, Color.GREEN, Color.YELLOW, Color.CYAN};
    	private static final String TIME_LABEL_COMPONENT = "timelabel";
     
    	public static void main(String[] args) {
     
    		JFrame frame = new JFrame("Demo");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		CardLayout cardLayout = new CardLayout();
    		JPanel mainPanel = new JPanel(cardLayout);
     
    		Map<JPanel, Description> map = new HashMap<>();
    		ComponentAdapter componentAdapter = new ComponentAdapter() {
    			@Override
    			public void componentShown(ComponentEvent arg0) {
    				map.get(arg0.getComponent()).updatePanelTime();
    			}
    		};
    		for(Color color : COLORS) {
    			Description cardPanel = createJPanel(getName(color));
    			cardPanel.getPanel().setBackground(color);
    			cardPanel.getPanel().addComponentListener(componentAdapter);
    			mainPanel.add(cardPanel.getPanel());
    			map.put(cardPanel.getPanel(), cardPanel);
    		}
     
    		JButton button = new JButton("Change");
    		button.addActionListener(e-> cardLayout.next(mainPanel));
    		JPanel southPanel = new JPanel();
    		southPanel.add(button); 
     
    		frame.add(mainPanel);
    		frame.add(southPanel, BorderLayout.SOUTH);
     
    		frame.addWindowListener(new WindowAdapter() {
    			public void windowOpened(java.awt.event.WindowEvent e) {
    				map.get(getVisible(mainPanel)).updatePanelTime();;
    			}
    			public void windowClosing(java.awt.event.WindowEvent e) {
    				for(Component component : mainPanel.getComponents()) {
    					if ( component instanceof JPanel ) {
    						JPanel panel = (JPanel)component;
    						String time = map.get(panel).getPanelTime();
    						if ( time.isEmpty() ) {
    							time = "jamais affiché";
    						}
    						System.out.println("Heure du panneau " + getName(panel.getBackground()).toLowerCase() + " : " + time);
    					}
    				}
    			}
    		});
     
    		frame.setSize(400, 400);
    		frame.setLocationRelativeTo(null);
    		frame.setVisible(true);
     
    	} 
     
    	protected static JPanel getVisible(JPanel panel) {
    		for(Component component : panel.getComponents()) {
    			if ( component instanceof JPanel && component.isVisible() ) {
    				 return (JPanel)component; 
    			}
    		}
    		return null;
    	} 
     
    	private static String getName(Color color) {
    		for(Field field : Color.class.getFields()) {
    			try {
    				if ( color==field.get(null) ) {
    					return field.getName();
    				}
    			} catch (IllegalArgumentException | IllegalAccessException e) { 
    			}
    		}
    		return "?";
    	}
     
    	private static String getTime() {
    		return DateTimeFormatter.ofPattern("hh:mm:ss").format(LocalDateTime.now());
    	}
    	private static Description createJPanel(String texte) {
    		return new Description(texte);
    	}
     
    	public static class Description {
     
    		private final SwingPropertyChangeSupport propertyChangeSupport;
    		private final JPanel panel;
    		private String time;
     
    		public Description(String texte) {
    			time = "";
    			propertyChangeSupport=new SwingPropertyChangeSupport(this);
    			panel = new JPanel(new BorderLayout());
    			JLabel timeLabel = new JLabel(); // le label qui va afficher l'heure
    			propertyChangeSupport.addPropertyChangeListener("time", e-> timeLabel.setText((String)(e.getNewValue())));
    			timeLabel.setHorizontalAlignment(JLabel.CENTER);
    			timeLabel.setName(TIME_LABEL_COMPONENT);
    			panel.add(timeLabel, BorderLayout.NORTH);
    			JLabel label2 = new JLabel(texte); // un autre label
    			label2.setHorizontalAlignment(JLabel.CENTER);
    			panel.add(label2, BorderLayout.SOUTH);
    		}
     
    		public JPanel getPanel() {
    			return panel;
    		}
     
    		public void updatePanelTime() {
    			String old=time;
    			time=getTime();
    			propertyChangeSupport.firePropertyChange("time", old, time);
    		}
     
    		public String getPanelTime() {
    			return time;
    		}
     
    	}  
     
    }
    On peut même faire qu'un seul modèle, pour tous les panels.
    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
    public class CardLayoutChangeByMethodByInspection {
     
    	private static final Color[] COLORS = {Color.ORANGE, Color.GREEN, Color.YELLOW, Color.CYAN};
    	private static final String TIME_LABEL_COMPONENT = "timelabel";
     
    	public static void main(String[] args) {
     
    		JFrame frame = new JFrame("Demo");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		CardLayout cardLayout = new CardLayout();
    		JPanel mainPanel = new JPanel(cardLayout);
     
    		Model model = new Model();
     
    		ComponentAdapter componentAdapter = new ComponentAdapter() {
    			@Override
    			public void componentShown(ComponentEvent arg0) {
    				model.updatePanelTime(getName(arg0.getComponent().getBackground()));
    			}
    		};
    		for(Color color : COLORS) {
    			JPanel cardPanel = createPanel(color, model);
    			cardPanel.addComponentListener(componentAdapter); 
    			mainPanel.add(cardPanel);
    		}
     
    		JButton button = new JButton("Change");
    		button.addActionListener(e-> cardLayout.next(mainPanel));
    		JPanel southPanel = new JPanel();
    		southPanel.add(button); 
     
    		frame.add(mainPanel);
    		frame.add(southPanel, BorderLayout.SOUTH);
     
    		frame.addWindowListener(new WindowAdapter() {
    			public void windowOpened(java.awt.event.WindowEvent e) {
    				model.updatePanelTime(getName(getVisible(mainPanel).getBackground()));
    			}
    			public void windowClosing(java.awt.event.WindowEvent e) {
    				for(Map.Entry<String, String> times : model.getTimes()) {
    					String time = times.getValue();
    					if ( time.isEmpty() ) {
    						time = "jamais affiché";
    					}
    					System.out.println("Heure du panneau " + times.getKey().toLowerCase() + " : " + time);
    				}
    			}
    		});
     
    		frame.setSize(400, 400);
    		frame.setLocationRelativeTo(null);
    		frame.setVisible(true);
     
    	} 
     
    	protected static JPanel getVisible(JPanel panel) {
    		for(Component component : panel.getComponents()) {
    			if ( component instanceof JPanel && component.isVisible() ) {
    				 return (JPanel)component; 
    			}
    		}
    		return null;
    	} 
     
    	private static String getName(Color color) {
    		for(Field field : Color.class.getFields()) {
    			try {
    				if ( color==field.get(null) ) {
    					return field.getName();
    				}
    			} catch (IllegalArgumentException | IllegalAccessException e) { 
    			}
    		}
    		return "?";
    	}
     
    	private static String getTime() {
    		return DateTimeFormatter.ofPattern("hh:mm:ss").format(LocalDateTime.now());
    	} 
     
    	public static JPanel createPanel(Color color, Model description) {
    		String id = getName(color);
    		JPanel panel = new JPanel(new BorderLayout());
    		panel.setBackground(color);
    		JLabel timeLabel = new JLabel(); // le label qui va afficher l'heure
    		description.add(id, e-> timeLabel.setText((String)(e.getNewValue())));
    		timeLabel.setHorizontalAlignment(JLabel.CENTER);
    		timeLabel.setName(TIME_LABEL_COMPONENT);
    		panel.add(timeLabel, BorderLayout.NORTH);
    		JLabel label2 = new JLabel(id); // un autre label
    		label2.setHorizontalAlignment(JLabel.CENTER);
    		panel.add(label2, BorderLayout.SOUTH);
    		return panel;
    	}
     
    	public static class Model {
     
    		private final SwingPropertyChangeSupport propertyChangeSupport;
    		private Map<String, String> times;
     
    		public Model() {
    			times=new HashMap<>();
    			propertyChangeSupport=new SwingPropertyChangeSupport(this);
    		} 
     
    		public Set<Map.Entry<String,String>> getTimes() {
    			return Collections.unmodifiableSet(times.entrySet());
    		}
     
    		public void add(String id, PropertyChangeListener listener) {
    			if ( !times.containsKey(id) ) {
    				times.put(id,"");
    				propertyChangeSupport.addPropertyChangeListener(id, listener);
    			}
    		}
     
    		public void updatePanelTime(String id) {
    			if ( times.containsKey(id) ) {
    				String newtime=getTime();
    				String old=times.put(id, newtime);
    				propertyChangeSupport.firePropertyChange(id, old, newtime);
    			}
    		}
     
    		public String getPanelTime(String id) {
    			return times.getOrDefault(id, "");
    		}
     
    	}  
     
    }
    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.

  5. #5
    Candidat au Club
    Profil pro
    Inscrit en
    Mars 2009
    Messages
    7
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2009
    Messages : 7
    Points : 2
    Points
    2
    Par défaut
    merci Joel, je pense avoir compris le raisonnement.

Discussions similaires

  1. Problème de changement de Panel avec CardLayout
    Par japhettchabao dans le forum Agents de placement/Fenêtres
    Réponses: 3
    Dernier message: 02/01/2015, 09h48
  2. Problème d'affichage lors du changement de panel
    Par momop72 dans le forum Agents de placement/Fenêtres
    Réponses: 1
    Dernier message: 11/12/2013, 10h43
  3. CardLayout - changement de panel
    Par jerem721 dans le forum Agents de placement/Fenêtres
    Réponses: 4
    Dernier message: 06/03/2009, 23h27
  4. [C#] problème scintillement lors du changement de panel
    Par chasse dans le forum Windows Forms
    Réponses: 3
    Dernier message: 04/10/2006, 15h00
  5. [JScrollPane] Changement du panel
    Par -=Spoon=- dans le forum Composants
    Réponses: 5
    Dernier message: 09/12/2004, 23h35

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