`
kuwoleft
  • 浏览: 1078557 次
文章分类
社区版块
存档分类
最新评论

Swing 中设置模态窗体和启动位置

 
阅读更多

关于 Modal 窗体


在 Swing 中只有 JDialog 可以设置为 Modal 窗体,其方法可以在构造函数(例如“JDialog(Frame owner, boolean modal)”)中传参数,也可以用 setModal(boolean b) 方法设定,这个方法是从 Dialog 类继承的。

在 JFrame 类中,无法通过如 JDialog 的方法设置 Modal 窗体,在 CSDN 有朋友尝试通过在 windowDeactivated() 时 requestFocus() 来模拟 Modal 窗体,代码如下:


publicclassMyModalFrameextendsJFrameimplementsWindowListener...{
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();
intx=(screenSize.width-size.width)/2;
inty=(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() 之前,否则只有窗体左上角是正对屏幕或所属组件中心,整个窗体看起来会是偏向右下角的。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics