使用GlassPane在Java中的内部透明选择窗口

Pat*_*k M 4 java swing glasspane

我正在努力实现以下目标

http://www.qksnap.com/i/3hunq/4ld0v/screenshot.png

我目前能够使用以下代码在半透明玻璃板背景上成功绘制矩形:

    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();
}
Run Code Online (Sandbox Code Playgroud)

然而,哪个效果很好,我希望矩形内的区域完全透明,而外部仍然变暗,就像上面的截图一样.

有任何想法吗?

And*_*son 5

..矩形内的区域是完全透明的,而外部仍然像上面的截图一样变暗.

  • 创建一个Rectangle(componentRect),它是正在绘制的组件的大小.
  • 创建Area(componentArea即形状)( new Area(componentRect)).
  • 创建一个Area(selectionArea)selectionRectangle.
  • 致电componentArea.subtract(selectionArea)删除所选部分.
  • 呼叫 Graphics.setClip(componentArea)
  • 涂上半透明的颜色.
  • (如果需要更多的涂漆操作,请清除剪裁区域).


Mad*_*mer 5

正如安德鲁建议的那样(在我完成我的例子时,只是打败了我)

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();
}
Run Code Online (Sandbox Code Playgroud)

显示和隐藏

  • 1+**但**我不认为你应该在从JVM获得的Graphics对象上调用`dispose()`.这似乎是您传播的OP代码中的错误.当然,如果你已经创建了Graphics对象,那么在完成它之后一定要处理掉它. (3认同)