java - Add JPanel to frame using if statement -



java - Add JPanel to frame using if statement -

i'm trying add together jpanel frame on click of jmenuitem. i've looked in past posts , i've tried using:

getcontentpane().add(myjpanel) revalidate(); repaint();

to no avail. game class constructor size set , background colour now. oh , sorry messy code, had deleted non working original , done give thought of i've tried. suggestions appreciated.

package game; import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.jframe; import javax.swing.jmenu; import javax.swing.jmenubar; import javax.swing.jmenuitem; import javax.swing.joptionpane; import javax.swing.swingutilities; public class main extends jframe{ static boolean gameactive = false; game game; jmenubar menubar; jmenu file; jmenuitem startgame; jmenuitem checkscore; jmenuitem closegame; int userscore; public main() { game = new game(); gameactive = false; //set jmenubar menubar = new jmenubar(); file = new jmenu("file"); startgame = new jmenuitem("start game"); checkscore = new jmenuitem("check score"); closegame = new jmenuitem("close game"); menubar.add(file); file.add(startgame); file.add(checkscore); file.add(closegame); startgame.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent e) { gameactive = true; } }); if(gameactive == true){ getcontentpane().add(game); revalidate(); repaint(); } checkscore.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent e) { joptionpane.showmessagedialog(checkscore, "your score " + userscore); } }); closegame.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent e) { system.exit(0); } }); setjmenubar(menubar); //jframe properties setdefaultcloseoperation(jframe.exit_on_close); setsize(400, 300); setlocationrelativeto(null); settitle("battlegrounds"); setresizable(false); setvisible(true); } public static void main(string[] args){ swingutilities.invokelater(new runnable(){ public void run(){ new main(); } }); } }

move statements inside actionlistener rather having them in constructor:

startgame.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent e) { gameactive = true; add(game); revalidate(); repaint(); } });

notice gameactive check redundant current code. getcontentpane().add(game) can written add(game).

note cardlayout purposely designed manage type of functionality.

java swing if-statement actionlistener jmenuitem

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -