Making multiple frames in a single program

krato picture krato · Jul 15, 2013 · Viewed 26.3k times · Source

I always wondered on how can I make a program with multiple JFrames. I mean I just want one class to handle all the GUIs and stuff but how can I effectively do this? A lot of tutorials say that we make JFrame by inheriting from JFrame. But what If I want many frames?

Ex: Title of Application in one frame with some options Menu is one frame Main working application is one frame Like in a game.

But I am not sure if I am pertaining to JPanel? I am completely puzzled with the 2. I just want one un-moving frame but basically the content of the frame is changing. When I click START for example, it will change to the gaming style of frame.

Answer

Russell Uhl picture Russell Uhl · Jul 15, 2013

you are looking for a JFrame with a CardLayout. Some background:

A JFrame is the physical window. It comes with a title bar and three buttons: minimize, maximize, and close. Think of this as a picture frame.

A JPanel is a "content holder" of sorts. Typically, you put your other components (buttons, animations, whatever) on a JPanel, and then slap that JPanel into a JFrame. Using our picture frame example, a JPanel would be the photo paper you put in the picture frame. The other components would then be the actual contents of the picture itself, and what you have at the end is a nice picture...or in your case, an application.

Setting the JFrame to utilize a CardLayout essentially lets you have multiple JPanels inside the same JFrame at once, while still only showing one at a time. So for your application, you would have (at least) two JPanels: one for the menu, and one for the game. When the app starts, you show the MenuPanel. When the user clicks "start", you switch to the GamePanel. The MenuPanel will be put in the background and will be inaccessible until you call it to the foreground again.

If, on the other hand, you create multiple JFrames, you will have two or more physically separate windows that can be dealt with individually. This can actually be kind of cool for game development. Although it takes more time to build and link the GUI for the second window, you can then have that window affect game settings in realtime (rate of fire, bullet strength, player speed, etc.)