关于 Modal 窗体
在 Swing 中只有 JDialog 可以设置为 Modal 窗体,其方法可以在构造函数(例如“JDialog(Frame owner, boolean modal)”)中传参数,也可以用 setModal(boolean b) 方法设定,
这个方法是从 Dialog 类继续的。
在 JFrame 类中,无法通过如 JDialog 的方法设置 Modal 窗体,在 CSDN 有朋友尝试通过在 windowDeiconified() 时 requestFocus() 来模拟 Modal 窗体,代码如下:
public class MyModalFrame extends JFrame implements WindowListener ...{ PRivate JFrame frame = null; private boolean modal = false; private String title = null; public MyModalFrame() ...{ this(null, false); } public MyModalFrame(JFrame frame) ...{ this(frame, false); } public MyModalFrame(JFrame frame, boolean modal) ...{ this(frame, modal, ""); } public MyModalFrame(JFrame frame, boolean modal, String title) ...{ super(title); this.frame = frame; this.modal = modal; this.title = title; this.init(); } private void init() ...{ if(modal) frame.setEnabled(false); this.addWindowListener(this); } public void windowOpened(WindowEvent windowEvent) ...{ } public void windowClosing(WindowEvent windowEvent) ...{ if(modal) frame.setEnabled(true); } public void windowClosed(WindowEvent windowEvent) ...{ } public void windowIconified(WindowEvent windowEvent) ...{ } public void windowDeiconified(WindowEvent windowEvent) ...{ } public void windowActivated(WindowEvent windowEvent) ...{ } public void windowDeactivated(WindowEvent windowEvent) ...{ if(modal) this.requestFocus(); }}关于窗体启动位置
有时候想要让窗体启动后在屏幕中间启动,有种比较复杂的方法:
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();Dimension size = 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);