如何忽略 JFrame 不透明度?

How to ignore JFrame opacity?

我需要在显示动画的同时实现"lights off"的效果。目前已使用透明 Jframe、黑色背景和 50% 不透明度显示器大小完成。然后,这个 canvas 组件应该绘制 RGBA 缓冲图像。

当 JFrame 不透明度也影响 Canvas 时会出现问题,使其成为半透明。这就是我要避免的。

//** Window class extends Canvas

public Window(){

    GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
    int hostMonitorWidth = gd.getDisplayMode().getWidth();
    int hostMonitorHeight = gd.getDisplayMode().getHeight();

    Dimension dimension = new Dimension(hostMonitorWidth, hostMonitorHeight);
    super.setPreferredSize(dimension);

    window = new JFrame();
    window.setUndecorated(true);
    window.setOpacity(0.55f);
    window.setLayout(new GridLayout());
    window.setSize(hostMonitorWidth, hostMonitorHeight);
    window.add(this);

    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setLocationRelativeTo(null);
    window.setVisible(true);
    window.requestFocus();
    window.setFocusableWindowState(true);


    super.createBufferStrategy(3);
}

public void draw(){
    BufferStrategy buffer = super.getBufferStrategy();
    java.awt.Graphics g = buffer.getDrawGraphics();

    g.setColor(Color.BLACK);
    g.fillRect(0,0, super.getWidth(), super.getHeight());
    g.drawImage(batch.getImage(), 0, 0, super.getWidth(), super.getHeight(), null);

    g.dispose();
    buffer.show();
}

我已经尝试将以下代码与 Jpanel、分层窗格、Jlabel 等进行组合。它似乎总是保持不透明/抛出无法解释的异常/出于任何原因不工作。

我的做法正确吗?我在这里错过了什么?

不要使用 setOpacity,在 JFrame 上使用 setBackground 并为其传递基于 alpha 的颜色。这将使框架变得透明而不影响其他组件。

但是,您可能会发现 Canvas 不喜欢基于 alpha 的颜色(因为它只有不透明状态)