java - setLocationRelativeTo() 一个组件,然后稍微移动它

标签 java swing

我正在尝试将 JDialog 相对于内部 JPanel 中的 JButton 进行定位 - 我可以使用 dialog.setLocationRelativeTo(button) 来完成此操作,但对话框随后会覆盖该按钮。我一直在尝试将对话框稍微移开,但很不成功。

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

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

最佳答案

借助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.

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

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

关于java - setLocationRelativeTo() 一个组件,然后稍微移动它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44007219/

相关文章:

java - JPA:删除时违反约束

java - 需要 MatOfMatch 对象做什么?

java - Swing 漆部件加工

java - 将 Outlook 电子邮件和其他文件拖放到 Java 应用程序

java - 调整 FlowLayout 面板的大小

java - 在broadleaf安装中无法在mysql中创建表

getResourceAsStream 的 java.lang.NullPointerException

java - 如何有效(性能)从Java中的列表中删除许多项?

java - 更新 Java Swing 应用程序中的按钮状态

java - Pascal GUI 居中