【问题标题】:How to ignore JFrame opacity?如何忽略 JFrame 不透明度?
【发布时间】:2016-05-23 00:32:20
【问题描述】:

我需要在显示动画的同时实现“关灯”的效果。目前使用透明 Jframe、黑色背景和 50% 的不透明度(显示器大小)完成。然后,有这个画布组件应该绘制 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 等的组合。它似乎总是保持不透明/抛出无法解释的异常/出于任何原因无法正常工作。

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

【问题讨论】:

    标签: java swing canvas jframe awt


    【解决方案1】:

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

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

    【讨论】:

    • 我已经试过了,好像背景色占据了画布。你能展示它应该如何正确地完成吗?
    • 而且,正如我所说,Canvas 可能不喜欢你正在做的事情,因为它只有一个不透明的状态(它不支持透明度),如果你想绘制一个半透明的组件,您将需要改用基于 Swing 的组件
    • 你最好的建议是什么?
    • 使用基于 Swing 的组件,如 JComponentJPanel 并覆盖 paintComponent 方法,在其中绘制半透​​明效果(记得将组件设置为透明,setOpaque(false)),例如this 之类的东西
    • 会做的,非常感谢。
    猜你喜欢
    • 2014-01-14
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多