setLocationRelativeTo() 一个组件,然后稍微移动它 [英] setLocationRelativeTo() a component, and then shifting it slightly

查看:46
本文介绍了setLocationRelativeTo() 一个组件,然后稍微移动它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在内部 JPanel 中相对于 JButton 定位 JDialog - 我可以使用 dialog.setLocationRelativeTo(button) 来做到这一点,但对话框随后覆盖了按钮.我一直在尝试将对话框稍微移开,但没有成功.

I'm trying to position a JDialog relative to a JButton in an internal JPanel- which I can do using dialog.setLocationRelativeTo(button), but the dialog then covers the button. I've been trying, quite unsuccessfully, to then move the dialog slightly out of the way.

我发现了一些看起来很有希望的不同方法,然后只产生完全相同的结果,从在设置相对位置(似乎相互覆盖)后仅使用 setLocation(x,y) 到获得按钮在屏幕上的位置.

I've found a few different approaches that seemed promising, to then only produce exactly the same result, from just using setLocation(x,y) after setting the relative location (which seem to override each other), to getting the location of the button from the screen.

我很担心被人用勺子喂这种东西,并且在过去几天里问了几个问题,但是有没有人有任何提示,比如我应该在 API 中查找的位置?我应该考虑将相对于组件的坐标转换为屏幕坐标吗?这是我的下一个最佳猜测……但我不会撒谎,这绝对让我感到困惑.

I'm warey of being spoonfed this sort of stuff, and having asked a few questions over the last few days, but does anyone have any hints at all, like where I should be looking in the API? Should I be looking at converting the coordinates relative to the component to a screen coordinate? That's my next best guess...but I'm not going to lie, it's definitely confusing me.

推荐答案

你不需要自己转换,感谢 Component.getLocationOnScreen():

You don't need to convert yourself, thanks to Component.getLocationOnScreen():

public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> {
        final JFrame f = new JFrame("test");
        final JButton b = new JButton("Hello");
        f.getContentPane().setLayout(new BorderLayout());
        f.getContentPane().add(b, BorderLayout.NORTH);
        f.setSize(300, 200);
        f.setVisible(true);
        b.addActionListener((e) -> {
            JDialog dialog = new JDialog(f);
            dialog.getContentPane().add(new JLabel(new Date().toString()));
            dialog.pack();
            Point point = b.getLocationOnScreen();
            //dialog.setLocationRelativeTo(b); // Shows over button, as doc says
            dialog.setLocation(new Point(point.x, point.y + b.getHeight()));
            dialog.setVisible(true);
        });
    });
}

对我有用...

Window.setLocationRelativeTo(...) 的文档说:

如果组件不为空并且显示在屏幕上,则窗口的位置使得窗口的中心与组件的中心重合.

If the component is not null and is shown on the screen, then the window is located in such a way that the center of the window coincides with the center of the component.

所以你得到的行为是正常的.

So the behavior you get is normal.

(希望我已经正确理解了您的问题)

(Hope I have correctly understood your issue)

这篇关于setLocationRelativeTo() 一个组件,然后稍微移动它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆