You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何将内嵌Browser的Shell移至屏幕右上角?setBounds无效解决方案

解决SWT Shell定位到屏幕右上角的问题

嗨,我来帮你搞定这个Shell定位的问题~你之前的代码里有个小误区,导致setBounds没生效,咱们一步步来修正:

为什么你的setBounds没起作用?

你给Shell设置了FillLayout,这个布局管理器会强制让内部的Browser组件填满整个Shell,所以你给Browser设置的bounds会被布局覆盖掉。真正需要设置位置和大小的是Shell本身,而不是Browser。

步骤1:获取屏幕右上角的坐标

要拿到屏幕右上角的位置,咱们需要通过SWT的Display类获取屏幕的尺寸信息:

  • 获取当前Display实例:Display display = Display.getDefault();
  • 获取主屏幕的边界矩形:Rectangle screenBounds = display.getPrimaryMonitor().getBounds();
  • 计算右上角坐标:假设你的Shell宽200、高200,那么x坐标就是「屏幕宽度 - Shell宽度」,y坐标就是屏幕的顶部位置(用screenBounds.y更严谨,能适配多屏幕场景)

步骤2:设置Shell到指定位置

直接给Shell调用setBounds或者分开用setLocation+setSize都可以,这里推荐直接用setBounds一步到位。

完整修正后的代码

Display display = Display.getDefault();
final Shell shell = new Shell(display);

// FillLayout会让Browser自动填满Shell,不用给Browser设bounds
shell.setLayout(new FillLayout());
Browser browser = new Browser(shell, SWT.NONE);

// 获取主屏幕的尺寸
Rectangle screenBounds = display.getPrimaryMonitor().getBounds();
int shellWidth = 200;
int shellHeight = 200;

// 计算屏幕右上角的坐标
int x = screenBounds.width - shellWidth;
int y = screenBounds.y; // 屏幕顶部的y坐标,多屏幕场景下也能正确适配

// 设置Shell的位置和大小
shell.setBounds(x, y, shellWidth, shellHeight);

shell.open();
// 标准的SWT事件循环
while (!shell.isDisposed()) {
    if (!display.readAndDispatch()) {
        display.sleep();
    }
}
display.dispose();

额外提示:多屏幕场景适配

如果你想把Shell放到其他屏幕的右上角,可以遍历display.getMonitors()数组,找到目标显示器的Bounds再计算坐标,比如:

// 获取所有屏幕
Monitor[] monitors = display.getMonitors();
// 假设要放到第二个屏幕的右上角(索引从0开始)
if (monitors.length > 1) {
    Rectangle secondScreenBounds = monitors[1].getBounds();
    int x = secondScreenBounds.width - shellWidth;
    int y = secondScreenBounds.y;
    shell.setBounds(x, y, shellWidth, shellHeight);
}

内容的提问来源于stack exchange,提问作者sajeet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:21:25