0

When i started developping my application, I just developped Seprate JFrame frames and test them one by one. Now, i want to make a main window for my app. I read a lot, but until now, it's difficult for me to do this in java and swing. I tried this by creating a main window as an instance of JFrame, but i got errors that shows i can't show JFrame inside another JFrame.

public class MainWindow extends JFrame{
private JFrame frame1;
private JFrame frame2;


public MainWindow(){

frame1 = new JFrame();
frame2 = new JFrame();

setLayout(new BorderLayout());

add(frame1,BorderLayout.CENTER);
add(frame2,BorderLayout.NORTH);

pack(); 

}

}
abdou amer
  • 819
  • 2
  • 16
  • 43

3 Answers3

1

A JFrame is a window.

You can't put a window inside a window.

You might be looking for JPanel. A JPanel is a fairly simple container for other components (which could include more JPanels). You can add JPanels to a JFrame.

user253751
  • 57,427
  • 7
  • 48
  • 90
  • i want to add the entrie JFrame inside a panel or Parent JFrame, how i can do this? – abdou amer Jan 10 '15 at 09:54
  • @abdouamer As immibis said, you can't. This is why we discourage people from extending from `JFrame` as it locks you into a implementation. Instead, use a `JPanel` and either a `CardLayout` or `JTabedPane` (or even other layout manager) to display the separate views... – MadProgrammer Jan 10 '15 at 09:58
1

This is one of the reasons why it is generally discouraged to extend directly from top level containers like JFrame, they lock you into a single use.

You can't add window based components to other containers. You will have to separate each of your current frames into a more basic container, like JPanel, only then can you add them to another window.

You may consider using a CardLayout or JTabbedPane or even a JDesktopPane or other layout manager to make your individual views available to your users depending on your needs.

See...

for some more ideas

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

There are different ways to handle this
First of all you can't use Jframe inside of JFrame like you noticed so instead use JPanel

panel = new JPanel();

add(panel,BorderLayout.Center);

JPanel is an other container in which you can pack a lot of swing components.

If you want to open a new Window make anoter JFrame and make it visible. Note you can't add it to your Jframe with the method add. but you can save it in a variable and handle what you see in the other frame from the same class.
As you wanna have a mainwindow add this code into the mainwindow:

frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

this makes that if you close your main Frame the application will end (in the other frames you shouldn't implement this normally)

tung
  • 719
  • 2
  • 14
  • 30