2012-10-15 143 views
1

我用下面的代碼在JPanel上繪製了一個BufferedImage。如何將鼠標偵聽器添加到JPanel圖像?

protected void paintComponent(Graphics g) { 
    if (image != null) { 
     super.paintComponent(g); 

     Graphics2D g2 = (Graphics2D) g; 

     double x = (getWidth() - scale * imageWidth)/2; 
     double y = (getHeight() - scale * imageHeight)/2; 
     AffineTransform at = AffineTransform.getTranslateInstance(x, y); 
     at.scale(scale, scale); 
     g2.drawRenderedImage(image, at); 
    } 
} 

如何添加一個鼠標點擊偵聽器到該圖像?另外,我想獲得圖像的點擊座標,而不是JPanel。

+1

首先,確保你總是叫'super.paintComponent'無論狀態'image' – MadProgrammer

+1

爲了更好地幫助,請發佈[SSCCE](http://sscce.org/)。 –

+1

請看看[示例](http://stackoverflow.com/a/11890169/1057230) –

回答

4

按照常規向窗格中添加MouseListener

mouseClicked方法檢查,看看是否Point是圖像的矩形內...

public void mouseClicked(MouseEvent evt) { 

    if (image != null) { 
     double width = scale * imageWidth; 
     double height = scale * imageHeight; 
     double x = (getWidth() - width)/2; 
     double y = (getHeight() - height)/2; 
     Rectangle2D.Double bounds = new Rectangle2D.Double(x, y, width, height); 
     if (bounds.contains(evt.getPoint()) { 
      // You clicked me... 
     } 
    } 
} 
相關問題