如何让JDialog显示在JFrame中间,当窗体被移动时,再去点击,弹出的子窗体仍然在主窗体中间
我知道让主窗体显示在屏幕中间是通过获取屏幕的高和宽,和主窗体的高和宽,不过子窗体和主窗体好像没办法这样子来做,请教一下各位朋友,谢谢!...
我知道让主窗体显示在屏幕中间是通过获取屏幕的高和宽,和主窗体的高和宽,不过子窗体和主窗体好像没办法这样子来做,请教一下各位朋友,谢谢!
展开
1个回答
2013-05-16
展开全部
可以的。你只要获得主窗体在屏幕的坐标就行啦。埋拆核下面给你一个参考代码。 import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.*;public class Test extends JFrame{
private int width,height;//父窗体的宽度和高度
private Point point;/弯掘/记录父窗体在屏幕的坐标
public Test(){
Toolkit tk = Toolkit.getDefaultToolkit();
width = 400;
height = 300;
this.setSize(width, height);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//设置主御悉窗体显示在屏幕中间
this.setLocation((tk.getScreenSize().width - width)/2,
(tk.getScreenSize().height - height)/2);
JButton button = new JButton("点击我,弹出JDialog");
button.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog();
dialog.setTitle("我是子窗体");
dialog.setSize(300, 200);
point = Test.this.getLocation();//获得主窗体在屏幕的坐标
dialog.setLocation(
point.x + width/2 - dialog.getWidth()/2,
point.y + height/2 - dialog.getHeight()/2);
dialog.setVisible(true);
}
}
);
add(button);
this.setVisible(true);
}
public static void main(String [] args){
new Test();
}
}
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.*;public class Test extends JFrame{
private int width,height;//父窗体的宽度和高度
private Point point;/弯掘/记录父窗体在屏幕的坐标
public Test(){
Toolkit tk = Toolkit.getDefaultToolkit();
width = 400;
height = 300;
this.setSize(width, height);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//设置主御悉窗体显示在屏幕中间
this.setLocation((tk.getScreenSize().width - width)/2,
(tk.getScreenSize().height - height)/2);
JButton button = new JButton("点击我,弹出JDialog");
button.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog();
dialog.setTitle("我是子窗体");
dialog.setSize(300, 200);
point = Test.this.getLocation();//获得主窗体在屏幕的坐标
dialog.setLocation(
point.x + width/2 - dialog.getWidth()/2,
point.y + height/2 - dialog.getHeight()/2);
dialog.setVisible(true);
}
}
);
add(button);
this.setVisible(true);
}
public static void main(String [] args){
new Test();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询