如何实现从屏幕中心开始级联排列的JFrame窗口?
实现思路
- 放弃Swing自带的
setLocationByPlatform(true)方法,手动计算每个新窗口的级联位置 - 第一次打开解决方案窗口时,先计算屏幕可用区域的中心点,作为首个窗口的起始位置
- 后续每新建一个窗口,在上一个窗口的位置基础上向右下偏移固定步长,超出屏幕边界时自动重置回中心起始位置,避免窗口超出可视区域
具体实现代码
首先在主JFrame类中定义全局变量记录级联状态:
// 级联偏移步长,可根据需求调整数值,20~30像素效果最佳 private static final int CASCADE_OFFSET = 25; // 记录上一个解决方案窗口的坐标,初始值-1代表尚无打开的解决方案窗口 private int lastSolutionX = -1; private int lastSolutionY = -1;
每次新建解决方案窗口时调用以下位置计算逻辑:
// 1. 获取屏幕可用区域(自动排除任务栏、dock等系统占用区域,适配多屏幕场景) Rectangle screenBounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); int screenWidth = screenBounds.width; int screenHeight = screenBounds.height; // 2. 初始化解决方案窗口 JFrame solutionFrame = new JFrame("解决方案"); // 此处填充你的窗口内容渲染逻辑 solutionFrame.setSize(600, 400); // 若使用pack()自适应大小,需先调用pack()再获取窗口宽高 int frameWidth = solutionFrame.getWidth(); int frameHeight = solutionFrame.getHeight(); // 3. 计算当前窗口坐标 int currentX, currentY; if (lastSolutionX == -1 || lastSolutionY == -1) { // 首个窗口居中显示 currentX = (screenWidth - frameWidth) / 2 + screenBounds.x; currentY = (screenHeight - frameHeight) / 2 + screenBounds.y; } else { // 后续窗口在上一个窗口基础上右下偏移 currentX = lastSolutionX + CASCADE_OFFSET; currentY = lastSolutionY + CASCADE_OFFSET; // 超出屏幕边界则重置回中心位置 if (currentX + frameWidth > screenBounds.x + screenWidth || currentY + frameHeight > screenBounds.y + screenHeight) { currentX = (screenWidth - frameWidth) / 2 + screenBounds.x; currentY = (screenHeight - frameHeight) / 2 + screenBounds.y; } } // 4. 应用坐标并更新全局记录 solutionFrame.setLocation(currentX, currentY); lastSolutionX = currentX; lastSolutionY = currentY; solutionFrame.setVisible(true);
补充说明
如果需要在所有解决方案窗口关闭后重置级联起始位置,只需给每个solutionFrame添加窗口关闭监听器,检测到无存活的解决方案窗口时,将lastSolutionX和lastSolutionY重置为-1即可。
内容的提问来源于stack exchange,提问作者Simone Tarenzi
相关产品推荐
相关产品推荐

