一般的编程语言都会提供显著的MDI功能,但Java似乎不那么明显,问了一些经常使用Java的同学居然一时也没说上来如何实现。于是借助网络的强大力量,我们知道了在Swing中提供了JDesktopPane和JInternalFrame,结合使用即可实现MDI的效果。
代码是简单的,先在主窗体(可是以一个JFrame)中加入一个JDesktopPane,为MDI“提供活动的空间”:
JDesktopPane desktop
=
new
JDesktopPane ();
?? .add(desktop);
?? .add(desktop);
当然,如果想这个Pane在需要时可以滚动,可以使用常用的技巧,把它加入一个JScrollPane,这里比较特殊,需要重载它的preferredSizeOfAllFrames函数才能获得正确的尺寸,才有正确的滚动效果:
public class JDesktop extends JDesktopPane
{
public void paint(Graphics g)
{
super.paint(g);
Dimension d = preferredSizeOfAllFrames();
this .setPreferredSize(d);
this .revalidate();
}
/* *
* @return 返回最佳desktop尺寸..
*/
public Dimension preferredSizeOfAllFrames()
{
JInternalFrame [] array = getAllFrames();
int maxX = 0 ;
int maxY = 0 ;
for ( int i = 0 ; i < array.length; i ++ )
{
if ( array[ i ].isVisible() )
{
int cx;
cx = array[i].getX();
int x = cx + array[i].getWidth();
if (x > maxX) maxX = x;
int cy;
cy = array[i].getY();
int y = cy + array[i].getHeight();
if (y > maxY) maxY = y;
}
}
return new Dimension(maxX, maxY);
}
}
{
public void paint(Graphics g)
{
super.paint(g);
Dimension d = preferredSizeOfAllFrames();
this .setPreferredSize(d);
this .revalidate();
}
/* *
* @return 返回最佳desktop尺寸..
*/
public Dimension preferredSizeOfAllFrames()
{
JInternalFrame [] array = getAllFrames();
int maxX = 0 ;
int maxY = 0 ;
for ( int i = 0 ; i < array.length; i ++ )
{
if ( array[ i ].isVisible() )
{
int cx;
cx = array[i].getX();
int x = cx + array[i].getWidth();
if (x > maxX) maxX = x;
int cy;
cy = array[i].getY();
int y = cy + array[i].getHeight();
if (y > maxY) maxY = y;
}
}
return new Dimension(maxX, maxY);
}
}
然后可以往里加入子窗口JInternalFrame了:
JInternalFrame frame
=
new
??
();
desktop.add(frame);
try {
frame.setVisible( true );
frame.setSelected( true );
} catch (java.beans.PropertyVetoException ex){}
desktop.add(frame);
try {
frame.setVisible( true );
frame.setSelected( true );
} catch (java.beans.PropertyVetoException ex){}
具体可以查看JDK的demo/jfc/metaworks例子,或JDK关于JInternalFrame的帮助。