3

i want to switch content of jpanels.lets say i have jpanel1 and jpanel2 and i want to change content of jpanel1 to jpanel2 and also jpanel2 to jpanel1.those panels have completely different content .so i can't change properties of jpanel and all elements instead switch.this image for clarify enter image description here

void switchPanels (){
Content c1=jPanel1.getContent();
jPanel1.setContent(jPanel2.getContent());
jPanel2.setContent(c1);
}

i know above codes not work .i want to know how can i implement this .

Piumi Wandana
  • 220
  • 1
  • 5
  • 14
  • 2
    Use a [`CardLayout`](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html), as shown [here](http://stackoverflow.com/questions/5665156/calling-awt-frame-methods-from-subclass/5786005#5786005). – Andrew Thompson Aug 12 '14 at 13:26
  • Or to reorder components in a container, but them in a list (`JList`) that allows D-n-D reordering. – Andrew Thompson Aug 12 '14 at 13:29
  • 1
    @AndrewThompson but i want to see both.for example in this case i want yello panel content add to green one and also green panel content add to yello. – Piumi Wandana Aug 12 '14 at 13:30
  • 3
    Why don't you switch the locations of `JPanel`'s themselves, instead of switching their content? – predi Aug 12 '14 at 13:31
  • 2
    So use a `JList` to display panels 1 & 2. See also the [Intro to Drag & Drop](http://docs.oracle.com/javase/tutorial/uiswing/dnd/intro.html) which is based around a `JList`. – Andrew Thompson Aug 12 '14 at 13:33

1 Answers1

3

Instead of adding 2 panels and switching their content I would place them in another container JPanel with BorderLayout (CENTER). TO swap them just remove the first panel from container1 and add to the container2.

JPanel container1=new JPanel();
container1.setLayout(new BorderLayout());
container1.add(thepanel1);
JPanel container2=new JPanel();
container2.setLayout(new BorderLayout());
container2.add(thepanel2);

public void swap() {
  container2.add(thepanel1);
  container1.add(thepanel2);
  revalidate();
  repaint();
}
StanislavL
  • 56,971
  • 9
  • 68
  • 98