使用GlassPane的Java内部透明选择窗口
我正在努力实现以下目标 我目前能够使用以下代码在半透明玻璃窗格背景上成功绘制矩形:使用GlassPane的Java内部透明选择窗口,java,swing,glasspane,Java,Swing,Glasspane,我正在努力实现以下目标 我目前能够使用以下代码在半透明玻璃窗格背景上成功绘制矩形: protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; g.setColor(Color.black); // black background g.fillRect(0, 0, frame.getWidth(), frame.getHeight()
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g.setColor(Color.black); // black background
g.fillRect(0, 0, frame.getWidth(), frame.getHeight());
g2.setColor(Color.GREEN.darker());
if (getRect() != null && isDrawing()) {
g2.draw(getRect()); // draw our rectangle (simple Rectangle class)
}
g2.dispose();
}
这很好,但是,我希望矩形内的区域完全透明,而外部仍然像上面的截图一样变暗
有什么想法吗
…使矩形内的区域完全透明,而外部仍然变暗,就像上面的屏幕截图一样
- 创建一个
(矩形
),它是正在绘制的组件的大小componentRect
- 创建该形状的
区域(
)(componentArea
)newarea(componentRect)
- 创建
的选择矩形
(区域
)选择区域
- 调用
以删除所选零件componentArea。减去(selectionArea)
- 调用
Graphics.setClip(componentArea)
- 涂上半透明的颜色
- (如果需要更多的绘制操作,请清除剪裁区域)
要更快地获得更好的帮助,请发布一条。谢谢你的提示,下次就可以了;-)@Hoverfullofeels告诉我:P@madProgrammer我给了安德鲁正确的答案,让他先回答,但我还是投了你们两个的大票。妮丝:)值得等待4分钟。1+但我认为您不应该对从JVM获得的图形对象调用
dispose()
。这似乎是您传播的OP代码中的错误。当然,如果你已经创建了图形对象,那么在处理完之后,一定要处理掉它。@HovercraftFullOfEels是的,你说得对,我偷了PatrickM的代码并修改了,对我很坏。我已将示例更新为使用g.create()
insteadThank you;)。你们太棒了。
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g.setColor(Color.black); // black background
Area area = new Area();
// This is the area that will filled...
area.add(new Area(new Rectangle2D.Float(0, 0, getWidth(), getHeight())));
g2.setColor(Color.GREEN.darker());
int width = getWidth() - 1;
int height = getHeight() - 1;
int openWidth = 200;
int openHeight = 200;
int x = (width - openWidth) / 2;
int y = (height - openHeight) / 2;
// This is the area that will be uneffected
area.subtract(new Area(new Rectangle2D.Float(x, y, openWidth, openHeight)));
// Set up a AlphaComposite
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
g2.fill(area);
g2.dispose();
}