MDI Applications
MDI apps or Multiple Document Interface is a common thing to see in todays programs. For instance in Microsoft Word, every new document you make is shown as a small window inside
the big one. That is MDI. To use MDI in a Swing program you must use a JDesktopPane in place of
the usual JPanel on your JFrame. To make the actual small windows use JInternalFrame(s). A
JInternalFrame is used just like a JFrame with a few differences of how you create it. Other
than creating the JInternalFrame, you still add a JPanel to its contentpane and add components
to the JPanel. How 'bout we take a look at the code to add the JDesktopPane to the JFrame?
Here's the code:
JFrame frame = new JFrame("MDI App With Swing");
JDesktopPane desktop = new JDesktopPane();
frame.setSize(560,560);
frame.getContentPane().add(desktop);
frame.pack();
frame.show();
That's easy enough, how 'bout adding that JInternalFrame ?
Here it is:
JFrame frame = new JFrame("MDI App With Swing");
JDesktopPane desktop = new JDesktopPane();
JInternalFrame intframe = new JInternalFrame("Title Text",true,true,true,true);
frame.setSize(560,560);
intframe.setSize(256,256);
frame.getContentPane().add(desktop);
desktop.add(intframe);
intframe.pack();
intframe.show();
frame.pack();
frame.show();
Looking at this code you are probably thinking, "Hey what is those extra
trues for when intframe is made?", to answer your question: those trues tell Java that we want
the window to be able to be resized, maximized, minimized and closed. So far so good, but now
we need to add a JPanel and a JButton to that JInternalFrame. How is this done?
Answer: Just
like usual, just add the JPanel to the JInternalFrame's contentpane and then add a JButton to
the JPanel. Wanna see the code? yes?
Here it is:
JFrame frame = new JFrame("MDI App With Swing");
JDesktopPane desktop = new JDesktopPane();
JInternalFrame intframe = new JInternalFrame("Title Text",true,true,true,true);
JPanel pane = new JPanel();
JButton button1 = new JButton("Button Text");
frame.setSize(560,560);
intframe.setSize(256,256);
intframe.getContentPane().add(pane);
pane.add(button1);
frame.getContentPane().add(desktop);
desktop.add(intframe);
frame.pack();
frame.show();
intframe.pack();
intframe.show();
Yep, we're getting into longer and longer code samples now. But, if
you look the code is still just as hard as when we started. It hasn't gotten much harder!