关于 Modal 窗体
在 Swing 中只有 JDialog 可以设置为 Modal 窗体,其方法可以在构造函数(例如“JDialog(Frame owner, boolean modal)”)中传参数,也可以用 setModal(boolean b) 方法设定,这个方法是从 Dialog 类继承的。
在 JFrame 类中,无法通过如 JDialog 的方法设置 Modal 窗体,在 优快云 有朋友尝试通过在 windowDeactivated() 时 requestFocus() 来模拟 Modal 窗体,代码如下:
public
class
MyModalFrame
extends
JFrame
implements
WindowListener
...
{
privateJFrameframe=null;
privatebooleanmodal=false;
privateStringtitle=null;

publicMyModalFrame()...{
this(null,false);
}

publicMyModalFrame(JFrameframe)...{
this(frame,false);
}

publicMyModalFrame(JFrameframe,booleanmodal)...{
this(frame,modal,"");
}

publicMyModalFrame(JFrameframe,booleanmodal,Stringtitle)...{
super(title);
this.frame=frame;
this.modal=modal;
this.title=title;
this.init();
}

privatevoidinit()...{
if(modal)
frame.setEnabled(false);
this.addWindowListener(this);
}

publicvoidwindowOpened(WindowEventwindowEvent)...{
}

publicvoidwindowClosing(WindowEventwindowEvent)...{
if(modal)
frame.setEnabled(true);
}

publicvoidwindowClosed(WindowEventwindowEvent)...{
}

publicvoidwindowIconified(WindowEventwindowEvent)...{
}

publicvoidwindowDeiconified(WindowEventwindowEvent)...{
}

publicvoidwindowActivated(WindowEventwindowEvent)...{
}

publicvoidwindowDeactivated(WindowEventwindowEvent)...{
if(modal)
this.requestFocus();
}
}
关于窗体启动位置
有时候想要让窗体启动后在屏幕中间启动,有种比较复杂的方法:
DimensionscreenSize
=
Toolkit.getDefaultToolkit().getScreenSize();
Dimensionsize
=
frame.getSize();
int
x
=
(screenSize.width
-
size.width)
/
2
;
int
y
=
(screenSize.height
-
size.height)
/
2
;
frame.setLocation(x,y);
在 Java 1.4 版之后可以用一条语句代替:
frame.setLocationRelativeTo(null);
Java API 文档中对此方法描述如下:public void setLocationRelativeTo(Component c)
设置此窗口相对于指定组件的位置。如果此组件当前未显示,或者 c 为 null,则此窗口位于屏幕的中央。如果该组件的底部在视线以外,则将该窗口放置在 Component 最接近窗口中心的一侧。因此,如果 Component 在屏幕的右部,则 Window 将被放置在左部,反之亦然。
在应用此方法时应该注意的一点是,setSize() 方法一定要放在 setLocationRelativeTo() 之前,否则只有窗体左上角是正对屏幕或所属组件中心,整个窗体看起来会是偏向右下角的。
本文介绍了在Swing中如何使用JDialog创建Modal窗体,并提供了通过自定义方式模拟Modal窗体的示例代码。同时,文章还讨论了如何使窗体在屏幕中心启动的两种方法。
5万+

被折叠的 条评论
为什么被折叠?



