2012-08-26 45 views
4

我想達到以下內透明的選擇窗口中使用玻璃面板

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

我目前能夠使用如下代碼半透明的glassPane背景成功繪製矩形:

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(); 
} 

但是,這很有效,我希望矩形內的區域完全透明,而外部仍然很暗,就像上面的截圖一樣。

任何想法?

+1

爲了更好地幫助越早,張貼[SSCCE(HTTP:// SSCCE。組織/)。 –

+1

謝謝你的提示,下次會做;-) –

回答

5

..有矩形內的區域是完全透明的,而外面仍然很暗,就像上面的截圖一樣。

  • 創建RectanglecomponentRect),其被塗的組件的大小。 (new Area(componentRect)))。
  • 創建selectionRectangleAreaselectionArea)。
  • 致電componentArea.subtract(selectionArea)刪除選定的零件。
  • 致電Graphics.setClip(componentArea)
  • 塗上半透明顏色。
  • (如果需要更多的繪畫操作,請清除裁剪區域)。
+1

太快了! 1+ –

+0

@HovercraftFullOfEels告訴我有關:P – MadProgrammer

+0

@madProgrammer我給了第一個答案的正確答案,但是我提高了你們兩個的答案。 –

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(); 
} 

Show and Hide

+1

Niice .. :)值得等待4分鐘。 –

+3

1+ **但是**我認爲你不應該在從JVM獲得的Graphics對象上調用'dispose()'。這似乎是您傳播的OP代碼中的錯誤。當然,如果你已經創建了Graphics對象,那麼在完成它的時候,一定要把它處置掉。 –

+0

@HovercraftFullOfEels是的,你是對的,我偷了PatrickM的代碼並修改,對我不利。我已經更新了示例以使用'g.create()'而不是 – MadProgrammer