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

王朝system·作者佚名  2007-04-02
窄屏简体版  字體: |||超大  

关于 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);

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航