java - Using multiple JPanels in a single JFrame -
i've been trying make menu game using jframe , switching out 2 jpanels (one menu , 1 actual game). i'm trying implement basic format can think of can't seem work. if explain what's wrong code appreciate it.
here's jframe, menu panel, , actionlistener
package buttonmenu; import java.awt.borderlayout; import java.awt.button; 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.jpanel; public class skeleton extends jframe implements actionlistener{ jpanel menu; jbutton button; public skeleton(){ setdefaultcloseoperation(exit_on_close); setsize(400, 400); setvisible(true); menu = new jpanel(); button = new jbutton("button"); menu.setsize(400, 400); menu.setbackground(color.black); menu.setvisible(true); menu.add(button); button.setlocation(200, 200); button.addactionlistener(this); add(menu, borderlayout.center); } public void actionperformed(actionevent a){ jpanel panel = game.game(); this.remove(menu); this.add(panel); } public static void main(string args[]){ new skeleton(); } }
the actionperformed calls panel created in class
package buttonmenu; import java.awt.color; import javax.swing.jpanel; public class game{ public static jpanel game(){ jpanel panel = new jpanel(); panel.setsize(400, 400); panel.setbackground(color.white); return panel; } }
again, if explain me what's wrong code appreciate it. thanks
when adding/removing components, need revalidate
parent container force relay out...
public void actionperformed(actionevent a){ jpanel panel = game.game(); this.remove(menu); this.add(panel); this.revalidate(); }
a better solution use cardlayout
take @ how use cardlayout more details
ps- should add. should avoid extending directly jframe
, instead create application entire on base component, jpanel
. when need display it, create instance of jframe , add application component it. way application becomes more flexible in terms of deployment , re-use
Comments
Post a Comment