我找到了以下 example code :
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)文档表明这些坐标也在 parent 的坐标空间中。
当然,对话框的父级是面板,所以在我看来,上面的代码是不正确的,并且在尝试将此对话框居中时不应将 pl.x/pl.y 添加到坐标中。但是,实际上对话框正确居中。
我在这里错过了什么?
(这个问题的上下文是我正在维护一个窗口管理器,并且来自 Java 应用程序的对话框经常放错地方。这表明我的代码是错误的,我正在尝试找出原因/位置)
最佳答案
owner
是对话框的父级,并不是说 Dialog
是面板的父级,而是一个窗口拥有另一个窗口的意义方式的目的。
Frame#getLocation
将返回框架在屏幕上的位置。 pd
是 owner
的(Frame
)大小,dd
是对话框大小...
当然,整个事情可以通过使用 Dialog#setLocationRelativeTo
来实现并将 owner
的引用传递给方法
关于java - AWT 对话框放置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23425121/