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

本文介绍了在Swing中如何使用JDialog创建Modal窗体,并提供了通过自定义方式模拟Modal窗体的示例代码。同时,文章还讨论了如何使窗体在屏幕中心启动的两种方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于 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() 之前,否则只有窗体左上角是正对屏幕或所属组件中心,整个窗体看起来会是偏向右下角的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值