您可以复制几乎任何 JDialog 行为,除了它在 JFrame 之上的定位(对于 Win 平台的这种情况有一些本机解决方案,但使用它是一件坏事......真的)。
以下是您可以在几分钟内完成的操作的示例:
ChildFrameTest.java
public class ChildFrameTest
{
public static void main ( String[] args )
{
JFrame application = new JFrame ();
application.setSize ( 600, 600 );
application.setLocationRelativeTo ( null );
application.setDefaultCloseOperation ( JFrame.DISPOSE_ON_CLOSE );
JChildFrame tool = new JChildFrame ( application );
tool.setModalExclusionType ( Dialog.ModalExclusionType.APPLICATION_EXCLUDE );
tool.setSize ( 100, 600 );
tool.setLocation ( application.getX () + application.getWidth (), application.getY () );
new WindowFollowListener ( tool, application );
application.setVisible ( true );
tool.setVisible ( true );
}
public static class JChildFrame extends JFrame
{
public JChildFrame ( JFrame parent )
{
super ();
parent.addWindowListener ( new WindowAdapter ()
{
public void windowClosing ( WindowEvent e )
{
dispose ();
}
} );
}
}
}
和 WindowFollowListener 添加一些不错的子框架行为:
WindowFollowListener.java
public class WindowFollowListener extends ComponentAdapter
{
private boolean enabled = true;
private Window followingWindow;
private Window parentWindow;
private Point ll;
public WindowFollowListener ( Window followingWindow, Window parentWindow )
{
super ();
this.followingWindow = followingWindow;
this.parentWindow = parentWindow;
this.ll = parentWindow.getLocation ();
parentWindow.addComponentListener ( this );
}
public boolean isEnabled ()
{
return enabled;
}
public void setEnabled ( boolean enabled )
{
this.enabled = enabled;
}
public Window getFollowingWindow ()
{
return followingWindow;
}
public void setFollowingWindow ( Window followingWindow )
{
this.followingWindow = followingWindow;
}
public Window getParentWindow ()
{
return parentWindow;
}
public void setParentWindow ( Window parentWindow )
{
this.parentWindow = parentWindow;
}
public void componentResized ( ComponentEvent e )
{
this.ll = parentWindow.getLocation ();
}
public void componentMoved ( ComponentEvent e )
{
if ( enabled && followingWindow != null && parentWindow != null )
{
Point nl = parentWindow.getLocation ();
Point fwl = followingWindow.getLocation ();
followingWindow.setLocation ( fwl.x + nl.x - ll.x, fwl.y + nl.y - ll.y );
this.ll = nl;
}
}
}