我发现下面的example code:AWT对话框放置
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static final int WIDTH = 300;
private static final int HEIGHT = 250;
public static void main(String[] args) {
new DialogExample();
}
public DialogExample() {
final Frame f = new Frame();
f.setTitle("Dialog Example");
f.setSize(WIDTH, HEIGHT);
Panel p1 = new Panel() {
public void paint(Graphics g) {
int left = DialogExample.WIDTH/2 - 45; // don't use WIDTH shadowed by Panel class
int top = DialogExample.HEIGHT/2 - 20; // same as above
g.drawString("Dialog Example", left, top);
}
};
f.add("Center", p1);
Panel p2 = new Panel();
f.add("South", p2);
Button b = new Button("Show Dialog");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showDialog(f);
}
});
p2.add(b);
// close window on X
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
f.setVisible(true);
}
private void showDialog(Frame owner) {
final Dialog d = new Dialog(owner, "The Dialog", true); // true for modal
d.add("Center", new Label("Hi, how are you?"));
Button ok = new Button("OK");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
d.setVisible(false);
}
});
d.add("South", ok);
d.pack();
// locate dialog to the center
Dimension dd = d.getSize();
Dimension pd = owner.getSize();
Point pl = owner.getLocation();
d.setLocation(
pl.x + ((int) (pd.getWidth() - dd.getWidth()))/2,
pl.y + ((int) (pd.getHeight() - dd.getHeight()))/2
);
d.setVisible(true);
}
}
我糊涂了由部分:
Point pl = owner.getLocation();
d.setLocation(
pl.x + ((int) (pd.getWidth() - dd.getWidth()))/2,
pl.y + ((int) (pd.getHeight() - dd.getHeight()))/2
);
的getLocation()的文件说,这将返回该组件的的左上角限制在组件的父代的坐标空间。由于此面板没有父级,因此它看起来像是指相对于屏幕左上角的坐标。同样,setLocation(x, y)文档建议这些坐标也在父母的坐标空间中。
当然,对话框的父母是面板,所以在我看来,上面的代码是不正确的,并且当试图居中对话框时,它不应该将pl.x/pl.y添加到坐标。但是,实际上对话框正确居中为。
缺少什么我在这里?
(这个问题的背景是,我保持一个窗口管理器,并从Java应用程序对话常常放错了地方。这表明我的代码是错误的,我试图找出为什么/哪里)
查找实现一些更近的例子。认真。 AWT在Java 1.2中被Swing有效地取代。由于在1.4中引入了setLocationRelativeTo(null)',所以查找宽度和高度的组件的中心点已经不必要了。但定位框架的最佳方法是在Java 1.6中引入'setLocationByPlatform(true)'。 –