当前位置: 技术问答>java相关
关于dialog的一个简单问题
来源: 互联网 发布时间:2015-03-18
本文导语: 一个dialog有一个owner是frame,怎样让这个dialog在frame的中间显示? | 下面的代码应该对你会有帮助 public class MyFrame extends Frame { BorderLayout borderLayout1 = new BorderLayout(); Dialog di...
一个dialog有一个owner是frame,怎样让这个dialog在frame的中间显示?
|
下面的代码应该对你会有帮助
public class MyFrame extends Frame
{
BorderLayout borderLayout1 = new BorderLayout();
Dialog dialog =new Dialog(this,"I'm a diglog");
Button but=new Button("test");
public MyFrame()
{
try{
init();
}
catch(Exception e)
{
e.printStackTrace();
}
}
private void init() throws Exception
{
this.setLayout(borderLayout1);
this.setSize(200,200);
but.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e)
{
but_actionPerformed(e);
}
});
this.add(but,BorderLayout.CENTER);
}
public void but_actionPerformed(ActionEvent e)
{
int px=this.getX();
int py=this.getY();
int pw=this.getWidth();
int ph=this.getHeight();
dialog.setSize(100,40);
int width=dialog.getWidth();
int height=dialog.getHeight();
dialog.setLocation(px+(pw-width)/2,py+(ph-height)/2);
dialog.show();
}
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
System.exit(0);
}
}
}
public class MyFrame extends Frame
{
BorderLayout borderLayout1 = new BorderLayout();
Dialog dialog =new Dialog(this,"I'm a diglog");
Button but=new Button("test");
public MyFrame()
{
try{
init();
}
catch(Exception e)
{
e.printStackTrace();
}
}
private void init() throws Exception
{
this.setLayout(borderLayout1);
this.setSize(200,200);
but.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e)
{
but_actionPerformed(e);
}
});
this.add(but,BorderLayout.CENTER);
}
public void but_actionPerformed(ActionEvent e)
{
int px=this.getX();
int py=this.getY();
int pw=this.getWidth();
int ph=this.getHeight();
dialog.setSize(100,40);
int width=dialog.getWidth();
int height=dialog.getHeight();
dialog.setLocation(px+(pw-width)/2,py+(ph-height)/2);
dialog.show();
}
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
System.exit(0);
}
}
}
|
得到frame的大小和左上角位置,再根据Dialog的本身大小,通过setLocation就可设置。