awt - Show a panel in CardLayout in Java -
i wrote following code showing 3 panels depending upon of 3 buttons clicked @ bottom.
import java.awt.borderlayout; import java.awt.button; import java.awt.cardlayout; import java.awt.color; import java.awt.frame; import java.awt.panel; import java.awt.event.actionevent; import java.awt.event.actionlistener; import java.awt.event.windowadapter; import java.awt.event.windowevent; public class cart extends frame implements actionlistener { panel cardpanel; panel firstp, secondp, thirdp; panel buttonp; button b1, b2, b3; cardlayout clayout; cart() { cardpanel = new panel(); clayout = new cardlayout(); cardpanel.setlayout(clayout); firstp = new panel(); firstp.setbackground(color.blue); secondp = new panel(); secondp.setbackground(color.red); thirdp = new panel(); thirdp.setbackground(color.yellow); b1 = new button("first"); b2 = new button("second"); b3 = new button("third"); b1.addactionlistener(this); b2.addactionlistener(this); b3.addactionlistener(this); buttonp = new panel(); buttonp.add(b1); buttonp.add(b2); buttonp.add(b3); add(buttonp, borderlayout.south); add(cardpanel, borderlayout.center); cardpanel.add("first", firstp); cardpanel.add("second", secondp); cardpanel.add("third", thirdp); setsize(400, 500); setvisible(true); addwindowlistener(new windowadapter() { public void windowclosing(windowevent e) { system.exit(0); } }); }// constructor ends here public void actionperformed(actionevent e) { if (e.getsource() == b1) { clayout.show(cardpanel, "firstp"); system.out.print("first"); } else if (e.getsource() == b2) { clayout.show(cardpanel,"secondp"); system.out.print("second"); } else if (e.getsource() == b3) { clayout.show(cardpanel, "thirdp"); } } public static void main(string args[]) { new cart(); } }
the methods handling 3 buttons called,and print terminal button clicked panels don't change.it's firstp that's visible.