Bonjour,
J'ai une jframe qui contient dans son centre un panel et en dessous un bouton. Quand j'appuye sur le bouton du dessous le panel suivant est affiché.
Petit schéma pour que ce soir clair :
Donc en appuyant plusieurs fois sur next, le centre du borderLayout va contenir le panel0 puis le panel1, panel2, de nouveau le panel0, panel1, ...
Le problème est que lorsqu'un panel apparait pour la première fois il est bien affiché mais lorsque je le réaffiche une seconde fois rien ne se passe, on vois toujours le panel qui était là avant.
J'ai vu ceci dans la javadoc pour la méthode add de Container :
et j'ai bien ajouté la méthode validate() mais ca ne fonctionne pas.Note: If a component has been added to a container that has been displayed, validate must be called on that container to display the new component. If multiple components are being added, you can improve efficiency by calling validate only once, after all the components have been added.
Voici le code complet :
(le changement de panel se fait dans la méthode actionPerformed, qui se trouve au milieu du 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 /* * créé le Apr 1, 2005 par Monkeyget */ package gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class TestMultiplePanel extends JFrame implements ActionListener{ private JPanel[] panels; private int currentPanel; public static void main(String[] args) { new TestMultiplePanel(); } public TestMultiplePanel(){ this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(640, 480); // tableau contenant 3 Jpanel panels = new JPanel[]{new Panel0(), new Panel1(), new Panel2()}; currentPanel = 0; this.getContentPane().add(panels[currentPanel], BorderLayout.CENTER); //bouton pour changer de panel JButton next = new JButton("Next panel"); next.addActionListener(this); this.getContentPane().add(next, BorderLayout.SOUTH); this.setVisible(true); } //action pour le bouton next. On affiche le panel suivant du tableau de JPanel public void actionPerformed(ActionEvent arg0) { currentPanel = (currentPanel+1)%panels.length; System.out.println(currentPanel); this.getContentPane().add(panels[currentPanel]); this.validate(); this.setVisible(true); } } class Panel0 extends JPanel{ public Panel0(){ this.add(new JLabel("Panel 0")); this.setBackground(Color.BLACK); } } class Panel1 extends JPanel{ public Panel1(){ this.add(new JLabel("Panel 1")); this.setBackground(Color.YELLOW); } } class Panel2 extends JPanel{ public Panel2(){ this.add(new JLabel("Panel 2")); this.setBackground(Color.RED); } }
Partager