我从这个问题中了解到,您可以GraphicsDevice[]使用以下代码在 Swing 应用程序中获取当前显示:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gd = ge.getScreenDevices();
Run Code Online (Sandbox Code Playgroud)
我知道从这里我可以自己设置设备,让用户选择要在菜单中使用的设备等。我的目标是检测应用程序当前显示在这些 GraphicsDevices 中的哪一个,因此我可以默认为当前全屏GraphicsDevice 而不会打扰用户。
我正在使用如下代码来全屏显示我的应用程序:
JFrame frame = new JFrame();
// ... when I want to fullscreen:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
if (gd.isFullScreenSupported()){
frame.dispose();
frame.setUndecorated(true);
frame.setAlwaysOnTop(true);
gd.setFullScreenWindow(frame);
frame.setVisible(true);
}
Run Code Online (Sandbox Code Playgroud)
我在 GraphicsDevice 或 GraphicsEnvironment API 中找不到任何内容来获取显示 JFrame 的当前 GraphicsDevice。我知道通过直接定位窗口可能存在黑客攻击(如上面的链接所述),但我想知道是否有更简单/更优雅的解决方案。
如何快速有效地将 a 的所有像素设置BufferedImage为透明,以便我可以简单地为每一帧重新绘制我想要的精灵图形?
我正在用 Java 设计一个简单的游戏引擎,它更新背景和前景BufferedImage并将它们绘制到一个复合体VolatileImage以进行有效缩放,然后绘制到JPanel. 这个可扩展的模型允许我添加更多层并迭代每个绘图层。
我将我的应用程序简化为下面给出的一类来演示我的问题。使用箭头键在图像上移动一个红色方块。挑战是我想将更新游戏图形与将复合图形绘制到游戏引擎中分离。我已经研究了这个问题看似彻底的答案,但无法弄清楚如何将它们应用于我的应用程序:
这是未正确清除像素的关键部分。注释掉的部分来自我已经阅读过的堆栈溢出答案,但它们将背景绘制为不透明的黑色或白色。我知道foregroundImage在我的实现中以透明像素开始,因为您可以backgroundImage在应用程序启动时看到红色精灵背后的随机像素噪声。现在,图像没有被清除,所以之前绘制的图像仍然存在。
/** Update the foregroundGraphics. */
private void updateGraphics(){
Graphics2D fgGraphics = (Graphics2D) foregroundImage.getGraphics();
// set image pixels to transparent
//fgGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR));
//fgGraphics.setColor(new Color(0,0,0,0));
//fgGraphics.clearRect(0, 0, width, height);
//fgGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
// draw again.
fgGraphics.setColor(Color.RED);
fgGraphics.fillRect(sx, sy, spriteSize, spriteSize);
fgGraphics.dispose();
}
Run Code Online (Sandbox Code Playgroud)
这是我的整个示例代码:
/**
* The goal is to draw two BufferedImages quickly onto a scalable JPanel, using
* a VolatileImage as …Run Code Online (Sandbox Code Playgroud)